Shaders and Shader Program
We need to program at least a Vertex and Fragment shader to tell OpenGL what to do with the incomming Vertex and Pixel data.
Vertex Shader
A vertex shader is handling vertices. Lets create one with glCreateShader.
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
Now we have to tell where to find the source of it. We do that with glShaderSource.
const GLchar* vertexShaderSource = {
"#version 450\n"
"layout(location = 0) in vec3 iposition;\n"
"layout(location = 1) in vec3 icolor;\n"
"out vec4 color;"
"void main() {\n"
"color = vec4(icolor, 1.0f);\n"
"gl_Position = vec4(iposition, 1.0f);\n"
"}"
};
glShaderSource(vertexShader, 1, &vertexShaderSource, nullptr);
After telling how the source looks like we have to compile the source with glCompileShader.
glCompileShader(vertexShader);
Fragment Shader
A fragment shader is handling pixels (multiple pixels = fragments). We create it with the same function as we used for the vertex shader but with a different parameter.
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
Then of course we have to tell again where to find the source as we did for the vertex shader.
const GLchar* fragmentShaderSource = {
"#version 450\n"
"in vec4 color;\n"
"layout(location = 0) out vec4 ocolor;\n"
"void main() {\n"
" ocolor = color;\n"
"}"
};
glShaderSource(fragmentShader, 1, &fragmentShaderSource, nullptr);
And of course the same, we have to compile this fragment shader too.
glCompileShader(fragmentShader);
Shader Program
The shader program holds different shader types and will be used during rendering. We create a shader program with glCreateProgram.
GLuint shaderProgram = glCreateProgram();
Now we need to attach the shaders we created before to this shader program. We do that with glAttachShader.
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
And finally as we do for normal c/c++ programs we have to link them to the shader program. This is done with glLinkProgram.
glLinkProgram(shaderProgram);
At this point if we don't have any errors, we are ready to use this shader program.
Last updated
Was this helpful?