OpenGL中使用GLSL着色器步骤
GLSL既适用于顶点着色器,也适用于片段着色器。
使用着色器对象的步骤:
1、创建着色器对象:
GLuint glCreateShader(GLenum type);
//创建一个着色器对象,type值必须是GL_VERTEX_SHADER或GL_FRAGMENT_SHADER。error返回0
2、把着色器的源码与着色器对象相关联:
glShaderSource(GLuint shader, GLsizei count, const GLChar** string, const GLint* length);
3、编译着色器对象的源码:
void glCompileShader(GLuint shader);
glGetShaderiv(GL_CIMPILE_STATUS); //查询编译结果
glGetShaderInfoLog(GLuint shader, GLsizei bufSize, GLsizei *length, char* infoLog);
4、创建一个空的着色器程序:
Gluint glCreateProgram(); //if error, return 0;
5、把着色器对象连接到着色器程序:
glAttachShader(GLuint program, GLuint shader); //glDetachShader(program, shader);
6、把连接到着色器程序中的对象链接成一个可执行程序:
voi glLinkProgram(GLuint program);
glGetProgramiv(GL_LINK_STATUS); //查询链接结果, GL_TRUE represent success
glGetProgramInfoLog(GLuint shader, GLsizei bufSize, GLsizei *length, char* infoLog);
7、启动顶点或片段着色器程序:
void glUseProgram(GLuint program); //使用程序的对象句柄作为参数
eg:
GLuint shader,program; GLuint compiled, linked; const GLchar* shaderSrc[] = { "void main(){" " gl_Position = gl_ModelViewProjectionMatrix *gl_Vertex;" "}" }; shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(shader, 1, shaderSrc, NULL); glCompileShader(shader); glGetShaderInfoLog(shader, GL_COMPILE_STATUS, &compiled); if(!compiled){ GLint length; GLchar* log; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length); log = (GLchar*)malloc(length); glGetShaderInfoLog(shader, length, &length, log); fprintf(stderr, "compile log = '%s '\n", log); free(log); } program =glCreateProgram(); glAttachShader(program, shader); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &linked); if(linker){ glUseProgram(program); }else{ GLint length; GLchar* log; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length); log = (GLchar*)malloc(length); glGetProgramInfoLog(program, length, &length, log); fprintf(stderr, "link log = '%s ' \n", log); free(log); }
删除着色器:
void glDeleteShader(GLuint shader); //若正在被使用,标记为删除,使用完后删除
判断是否是否是有效的着色器程序名:
GLboolean glIsProgram(GLuint program); //GL_TRUE
验证一个着色器是否可在当前的OpenGL状态下执行:
void glValidateProgram(GLuint program);
//若验证通过,GL_VALIDATE_STATUS被设置为GL_TRUE, 调用glGetProgramiv()查询GL_VALIDATE_STATUS的值。