Pro OpenGL ES for iOS

(singke) #1

CHAPTER 10: OpenGL ES 2, Shaders, and... (^311)


Back to the Spinning Cubes

So, now let’s jump back to the original example of the dueling cubes and break down
how a basic OpenGL ES 2 program is structured. As you’ll see, the process of
generating a shader is not unlike generating most any other application. You have your
basic compile, link, and load sequence. Listing 10-1 demonstrates the first part of that
process, compiling the thing. In Apple’s example, all of these steps are placed in a view
controller, but they can go anywhere.


Listing 10-1. Compiling a Shader



  • (BOOL)compileShader:(GLuint )shader //1
    type:(GLenum)type file:(NSString
    )file
    {
    GLint status;
    const GLchar *source;


source = (GLchar *)[[NSString stringWithContentsOfFile:file
encoding:NSUTF8StringEncoding error:nil] UTF8String];


if (!source)
{
NSLog(@"Failed to load vertex shader");
return NO;
}


*shader = glCreateShader(type); //2


glShaderSource(shader, 1, &source, NULL); //3
glCompileShader(
shader); //4


#if defined(DEBUG)


GLint logLength;
glGetShaderiv(*shader, GL_INFO_LOG_LENGTH, &logLength); //5


if (logLength > 0)
{
GLchar log = (GLchar )malloc(logLength);
glGetShaderInfoLog(*shader, logLength, &logLength, log); //6
NSLog(@"Shader compile log:\n%s", log);
free(log);
}


#endif


glGetShaderiv(*shader, GL_COMPILE_STATUS, &status); //7


if (status == 0)
{
glDeleteShader(*shader); //8
return NO;
}

Free download pdf