Saturday, May 14, 2011

glCreateProgram example

Name

glCreateProgram — Creates a program object

C Specification

GLuint glCreateProgram(void);

Description

glCreateProgram creates an empty program object and returns a non-zero value by which it can be referenced. A program object is an object to which shader objects can be attached. This provides a mechanism to specify the shader objects that will be linked to create a program. It also provides a means for checking the compatibility of the shaders that will be used to create a program (for instance, checking the compatibility between a vertex shader and a fragment shader). When no longer needed as part of a program object, shader objects can be detached. (glCreateProgram)
One or more executables are created in a program object by successfully attaching shader objects to it with glAttachShader, successfully compiling the shader objects withglCompileShader, and successfully linking the program object with glLinkProgram. These executables are made part of current state when glUseProgram is called. Program objects can be deleted by calling glDeleteProgram. The memory associated with the program object will be deleted when it is no longer part of current rendering state for any context.

Notes

Like buffer and texture objects, the name space for program objects may be shared across a set of contexts, as long as the server sides of the contexts share the same address space. If the name space is shared across contexts, any attached objects and the data associated with those attached objects are shared as well.
Applications are responsible for providing the synchronization across API calls when objects are accessed from different execution threads.


Example of glCreateProgram


Following code fragment shows a glCreateProgram example. To use the compiled shader objects (vertex shader and fragment shader), you should create a program object and associate the compiled shader object to the program.


Code collected from GLWiki.

/* The vertex shader */
 char *vsSource = file2string("wave.vert");
 char *fsSource = file2string("wave.frag");
 
 /* Compile and load the program */
 
 GLuint vs, /* Vertex Shader */
     fs, /* Fragment Shader */
     sp; /* Shader Program */
 
 
 vs = glCreateShader(GL_VERTEX_SHADER);
 glShaderSource(vs, 1, &vsSource, NULL);
 glCompileShader(vs);
 printLog(vs);
 
 fs = glCreateShader(GL_FRAGMENT_SHADER);
 glShaderSource(fs, 1, &fsSource, NULL);
 glCompileShader(fs);
 printLog(fs);
 
 free(vsSource);
 free(fsSource);
 
 sp = glCreateProgram();
 glAttachShader(sp, vs);
 glAttachShader(sp, fs);
 glLinkProgram(sp);
 printLog(sp);
 
 glUseProgram(sp);

Example of glCreateProgram