一、为何封装
通过前面几节的介绍,大家已经知道要想实现一张图片的渲染,从载入到呈现到屏幕上,中间经历了很多过程,还是很繁琐的,这时候我们需要一个框架把这些细节封装起来,更利于我们的理解和使用。
二、具体封装
1.着色器,shader
// 调用之前已经生成的着色器程序
Shader &Shader::Use()
{
glUseProgram(this->ID);
return *this;
}
// 通过传送顶点、片段、几何源文件,生成着色器程序
void Shader::Compile(const GLchar* vertexSource, const GLchar* fragmentSource, const GLchar* geometrySource)
{
GLuint sVertex, sFragment, gShader;
// Vertex Shader
sVertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(sVertex, 1, &vertexSource, NULL);
glCompileShader(sVertex);
checkCompileErrors(sVertex, "VERTEX");
// Fragment Shader
sFragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(sFragment, 1, &fragmentSource, NULL);
glCompileShader(sFragment);
checkCompileErrors(sFragment, "FRAGMENT");
// If geometry shader source code is given, also compile geometry shader
if (geometrySource != nullptr)
{
gShader = glCreateShader(GL_GEOMETRY_SHADER);
glShaderSource(gShader, 1, &geometrySource, NULL);
glCompileShader(gShader);
checkCompileErrors(gShader, "GEOMETRY");
}
// Shader Program
this->ID = glCreateProgram();
glAttachShader(this->ID, sVertex);
glAttachShader(this->ID, sFragment);
if (geometrySource != nullptr)
glAttachShader(this->ID, gShader);
glLinkProgram(this->ID);
checkCompileErrors(this->ID, "PROGRAM");
// Delete the shaders as they're linked into our program now and no longer necessery
glDeleteShader(sVertex);
glDeleteShader(sFragment);
if (geometrySource != nullptr)
glDeleteShader(gShader);
}
// 为着色器中的uniform变量设置不同的值
void Shader::SetFloat(const GLchar *name, GLfloat value, GLboolean useShader)
{
if (useShader)
this->Use();
glUniform1f(glGetUniformLocation(this->ID, name), value);
}
void Shader::SetInteger(const GLchar *name, GLint value, GLboolean useShader)
{
if (useShader)
this->Use();
glUniform1i(glGetUniformLocation(this->ID, name), value);
}
void Shader::SetVector2f(const GLchar *name, GLfloat x, GLfloat y, GLboolean useShader)
{
if (useShader)
this->Use();
glUniform2f(glGetUniformLocation(this->ID, name), x, y);
}
void Shader::SetVector2f(const GLchar *name, const glm: