這是一篇OpenGL ES的實(shí)戰(zhàn)吝梅,緊接 入門教程3
學(xué)了OpenGL ES一段時(shí)間,用這個(gè)應(yīng)用來練練手。
OpenGL ES系列教程在這里舵抹。
OpenGL ES系列教程的代碼地址 - 你的star和fork是我的源動(dòng)力,你的意見能讓我走得更遠(yuǎn)劣砍。
效果展示
demo來自蘋果官方惧蛹,可以學(xué)習(xí)蘋果的工程師如何應(yīng)用OpenGL ES。
這次的內(nèi)容包括刑枝,shader香嗓,CoreGraphics、手勢識(shí)別装畅、運(yùn)動(dòng)軌跡靠娱、模糊點(diǎn)效果;
shader
自定義enum洁灵,方便OC與shader之間的賦值饱岸,配合下面的自動(dòng)assign功能,非常便捷徽千。
enum {
PROGRAM_POINT,
NUM_PROGRAMS
};
enum {
UNIFORM_MVP,
UNIFORM_POINT_SIZE,
UNIFORM_VERTEX_COLOR,
UNIFORM_TEXTURE,
NUM_UNIFORMS
};
enum {
ATTRIB_VERTEX,
NUM_ATTRIBS
};
typedef struct {
char *vert, *frag;
GLint uniform[NUM_UNIFORMS];
GLuint id;
} programInfo_t;
programInfo_t program[NUM_PROGRAMS] = {
{ "point.vsh", "point.fsh" }, // PROGRAM_POINT
};
創(chuàng)建program的過程苫费,用glBindAttribLocation()
和 glueGetUniformLocation ()
來綁定attribute和uniform變量。
/* Convenience wrapper that compiles, links, enumerates uniforms and attribs */
GLint glueCreateProgram(const GLchar *vertSource, const GLchar *fragSource,
GLsizei attribNameCt, const GLchar **attribNames,
const GLint *attribLocations,
GLsizei uniformNameCt, const GLchar **uniformNames,
GLint *uniformLocations,
GLuint *program)
{
GLuint vertShader = 0, fragShader = 0, prog = 0, status = 1, i;
prog = glCreateProgram();
status *= glueCompileShader(GL_VERTEX_SHADER, 1, &vertSource, &vertShader);
status *= glueCompileShader(GL_FRAGMENT_SHADER, 1, &fragSource, &fragShader);
glAttachShader(prog, vertShader);
glAttachShader(prog, fragShader);
for (i = 0; i < attribNameCt; i++)
{
if(strlen(attribNames[i]))
glBindAttribLocation(prog, attribLocations[i], attribNames[i]);
}
status *= glueLinkProgram(prog);
status *= glueValidateProgram(prog);
if (status)
{
for(i = 0; i < uniformNameCt; i++)
{
if(strlen(uniformNames[i]))
uniformLocations[i] = glueGetUniformLocation(prog, uniformNames[i]);
}
*program = prog;
}
if (vertShader)
glDeleteShader(vertShader);
if (fragShader)
glDeleteShader(fragShader);
glError();
return status;
}
shader的編譯之前困擾過我很久双抽,這個(gè)demo介紹了一種方法可以獲取編譯錯(cuò)誤信息百框,非常的nice。
#define glError() { \
GLenum err = glGetError(); \
if (err != GL_NO_ERROR) { \
printf("glError: %04x caught at %s:%u\n", err, __FILE__, __LINE__); \
} \
}
CoreGraphics
自定義textureInfo_t結(jié)構(gòu)體牍汹,在textureFromName()
用CoreGraphics把url對(duì)應(yīng)的image data緩存到OpenGLES铐维,并通過textureInfo_t返回信息柬泽。
// Texture
typedef struct {
GLuint id;
GLsizei width, height;
} textureInfo_t;
// Create a texture from an image
- (textureInfo_t)textureFromName:(NSString *)name
{
CGImageRef brushImage;
CGContextRef brushContext;
GLubyte *brushData;
size_t width, height;
GLuint texId;
textureInfo_t texture;
// First create a UIImage object from the data in a image file, and then extract the Core Graphics image
brushImage = [UIImage imageNamed:name].CGImage;
// Get the width and height of the image
width = CGImageGetWidth(brushImage);
height = CGImageGetHeight(brushImage);
// Make sure the image exists
if(brushImage) {
// Allocate memory needed for the bitmap context
brushData = (GLubyte *) calloc(width * height * 4, sizeof(GLubyte));
// Use the bitmatp creation function provided by the Core Graphics framework.
brushContext = CGBitmapContextCreate(brushData, width, height, 8, width * 4, CGImageGetColorSpace(brushImage), kCGImageAlphaPremultipliedLast);
// After you create the context, you can draw the image to the context.
CGContextDrawImage(brushContext, CGRectMake(0.0, 0.0, (CGFloat)width, (CGFloat)height), brushImage);
// You don't need the context at this point, so you need to release it to avoid memory leaks.
CGContextRelease(brushContext);
// Use OpenGL ES to generate a name for the texture.
glGenTextures(1, &texId);
// Bind the texture name.
glBindTexture(GL_TEXTURE_2D, texId);
// Set the texture parameters to use a minifying filter and a linear filer (weighted average)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// Specify a 2D texture image, providing the a pointer to the image data in memory
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (int)width, (int)height, 0, GL_RGBA, GL_UNSIGNED_BYTE, brushData);
// Release the image data; it's no longer needed
free(brushData);
texture.id = texId;
texture.width = (int)width;
texture.height = (int)height;
}
return texture;
}
手勢識(shí)別
這里的手勢只有點(diǎn)擊和滑動(dòng),通過記錄touchesBegan嫁蛇,獲取第一個(gè)點(diǎn)的位置锨并,之后滑動(dòng)的過程中touchesMoved獲取到這次的位置和上次的位置,可以畫出一道手指滑動(dòng)的軌跡睬棚,通過renderLineFromPoint()
繪制第煮。
// Handles the start of a touch
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGRect bounds = [self bounds];
UITouch* touch = [[event touchesForView:self] anyObject];
firstTouch = YES;
// Convert touch point from UIView referential to OpenGL one (upside-down flip)
location = [touch locationInView:self];
location.y = bounds.size.height - location.y;
}
// Handles the continuation of a touch.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
CGRect bounds = [self bounds];
UITouch* touch = [[event touchesForView:self] anyObject];
// Convert touch point from UIView referential to OpenGL one (upside-down flip)
if (firstTouch) {
firstTouch = NO;
previousLocation = [touch previousLocationInView:self];
previousLocation.y = bounds.size.height - previousLocation.y;
} else {
location = [touch locationInView:self];
location.y = bounds.size.height - location.y;
previousLocation = [touch previousLocationInView:self];
previousLocation.y = bounds.size.height - previousLocation.y;
}
// Render the stroke
if (!lyArr) {
lyArr = [NSMutableArray array];
}
[lyArr addObject:[[LYPoint alloc] initWithCGPoint:previousLocation]];
[lyArr addObject:[[LYPoint alloc] initWithCGPoint:location]];
[self renderLineFromPoint:previousLocation toPoint:location];
}
// Handles the end of a touch event when the touch is a tap.
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
CGRect bounds = [self bounds];
UITouch* touch = [[event touchesForView:self] anyObject];
if (firstTouch) {
firstTouch = NO;
previousLocation = [touch previousLocationInView:self];
previousLocation.y = bounds.size.height - previousLocation.y;
[self renderLineFromPoint:previousLocation toPoint:location];
}
}
// Handles the end of a touch event.
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
// If appropriate, add code necessary to save the state of the application.
// This application is not saving state.
NSLog(@"cancell");
}
運(yùn)動(dòng)軌跡
通過把起點(diǎn)到終點(diǎn)的軌跡分解成若干個(gè)點(diǎn),分別來繪制每個(gè)點(diǎn)抑党,從而達(dá)到線的效果包警。
count = MAX(ceilf(sqrtf((end.x - start.x) * (end.x - start.x) + (end.y - start.y) * (end.y - start.y)) / kBrushPixelStep), 1);
這行代碼是核心思想,分出count個(gè)點(diǎn)底靠。
然后通過glDrawArrays(GL_POINTS, 0, (int)vertexCount);
繪制害晦。
// Drawings a line onscreen based on where the user touches
- (void)renderLineFromPoint:(CGPoint)start toPoint:(CGPoint)end
{
static GLfloat* vertexBuffer = NULL;
static NSUInteger vertexMax = 64;
NSUInteger vertexCount = 0,
count,
i;
[EAGLContext setCurrentContext:context];
glBindFramebuffer(GL_FRAMEBUFFER, viewFramebuffer);
// Convert locations from Points to Pixels
CGFloat scale = self.contentScaleFactor;
start.x *= scale;
start.y *= scale;
end.x *= scale;
end.y *= scale;
// Allocate vertex array buffer
if(vertexBuffer == NULL)
vertexBuffer = malloc(vertexMax * 2 * sizeof(GLfloat));
// Add points to the buffer so there are drawing points every X pixels
count = MAX(ceilf(sqrtf((end.x - start.x) * (end.x - start.x) + (end.y - start.y) * (end.y - start.y)) / kBrushPixelStep), 1);
for(i = 0; i < count; ++i) {
if(vertexCount == vertexMax) {
vertexMax = 2 * vertexMax;
vertexBuffer = realloc(vertexBuffer, vertexMax * 2 * sizeof(GLfloat));
}
vertexBuffer[2 * vertexCount + 0] = start.x + (end.x - start.x) * ((GLfloat)i / (GLfloat)count);
vertexBuffer[2 * vertexCount + 1] = start.y + (end.y - start.y) * ((GLfloat)i / (GLfloat)count);
vertexCount += 1;
}
// Load data to the Vertex Buffer Object
glBindBuffer(GL_ARRAY_BUFFER, vboId);
glBufferData(GL_ARRAY_BUFFER, vertexCount*2*sizeof(GLfloat), vertexBuffer, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(ATTRIB_VERTEX);
glVertexAttribPointer(ATTRIB_VERTEX, 2, GL_FLOAT, GL_FALSE, 0, 0);
// Draw
glUseProgram(program[PROGRAM_POINT].id);
glDrawArrays(GL_POINTS, 0, (int)vertexCount);
// Display the buffer
glBindRenderbuffer(GL_RENDERBUFFER, viewRenderbuffer);
[context presentRenderbuffer:GL_RENDERBUFFER];
}
模糊點(diǎn)的效果
點(diǎn)模糊的效果通過開啟混合模式,并設(shè)置混合函數(shù)
// Enable blending and set a blending function appropriate for premultiplied alpha pixel data
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
注意color和texture2D的操作符是*暑中,不是+壹瘟。
uniform sampler2D texture;
varying lowp vec4 color;
void main()
{
gl_FragColor = color * texture2D(texture, gl_PointCoord);
}
最后
送上一張圖
附上源碼
思考題
- 如何改動(dòng)開頭的加油?