2. OpenGL 4 Shaders

Introduction
Because our OpenGL 3.2 core-profile path is shader based, I am going to show you how to integrate the shader code from the GLSL section of the website. I am not going to go back through every GLSL detail here, as I have already done that in the GLSL portion of the site. This tutorial is a quick guide on getting shaders working in our current framework. So why don’t we get to it, so we can move on to using matrices in the new pipeline. Keep in mind that we only need Vertex and Fragment shaders for this tutorial; Geometry shaders are another optional stage and can wait until we actually have a reason to use one.
Coding
The code for this tutorial is going to be fairly minimal, and I may have updates to the shader.cpp and shader.h files that are in the GLSL portion of the site. If you have any queries, feel free to ask.
The first thing we are going to do, is copy our shader.h and shader.cpp files from the GLSL section of the site, and add them into our new Visual Studio project. Then go ahead and open opengl_3.h.
Opengl_3.h
Inside of opengl_3.h where we have our opengl context class structure, jump up the top and make sure you include the shader.h file into your source code.
#include "shader.h"
Once we have done this, go down into our private variables for our context class, and add an instance of a shader variable. If you are working with several shaders, you can make this into an array, or create separate shader variables. Personally I would create an array of shaders.
class OpenGLContext {
...
private:
int windowWidth; // Store the width of our window
int windowHeight; // Store the height of our window
Shader *shader; // Our GLSL shader
...
};
Opengl_3.cpp
Once we have a shader variable declared that we can play with, open up opengl_3.cpp and jump down to the setupScene method. Inside of here we are going to set our shader to a new shader object, based on shader.vert and shader.frag. Both of which are included in the project.
void OpenGLContext::setupScene(void) {
glClearColor(0.4f, 0.6f, 0.9f, 0.0f); // Set the clear colour based on Microsofts CornflowerBlue (default in XNA)
shader = new Shader("shader.vert", "shader.frag"); // Create our shader by loading our vertex and fragment shader
}
And then all we have left to do is jump to our renderScene method and bind and unbind our shader as required. You will notice that we don’t have any geometry to draw yet, so you won’t see anything yet, but don’t worry, we are getting there 🙂
void OpenGLContext::renderScene(void) {
glViewport(0, 0, windowWidth, windowHeight); // Set the viewport size to fill the window
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // Clear required buffers
shader->bind(); // Bind our shader
shader->unbind(); // Unbind our shader
SwapBuffers(hdc); // Swap buffers so we can see our rendering
}
Shader.cpp
I mentioned at the start that these are pretty much the same shader.cpp and shader.h files that are in the GLSL section of the website. There is one important change for the core-profile code: I want the shader inputs in_Position and in_Color to use known attribute locations.
We can ask OpenGL to bind those names to locations 0 and 1 with glBindAttribLocation. The important bit – and this is where the old version of this tutorial had the order wrong – is that the bindings have to be made before glLinkProgram, because the linker is what assigns the locations.
void Shader::init(const char *vsFile, const char *fsFile) {
...
shader_id = glCreateProgram();
glAttachShader(shader_id, shader_vp);
glAttachShader(shader_id, shader_fp);
// Bind our vertex shader input names before linking.
glBindAttribLocation(shader_id, 0, "in_Position");
glBindAttribLocation(shader_id, 1, "in_Color");
glLinkProgram(shader_id);
...
}
These are not magic permanent variables and OpenGL will not guess that “the second VBO must be colour” later on. Location 0 and location 1 are simply agreed input slots. When we build our VAO/VBO setup, we will explicitly point each stream of vertex data at the matching location.
Shader.vert
Because this tutorial has been so short, I am going to give a quick talk about the changes in GLSL 1.50. GLSL 1.50 is the shading-language version associated with OpenGL 3.2. To declare which version we are using, put this right at the top of the shader:
#version 150 core
In a GLSL 1.50 core shader we no longer have compatibility inputs such as gl_Vertex or built-in matrices such as gl_ModelViewMatrix, so we declare our own inputs and send our own matrices. We will get to the model, view and projection matrices in the next tutorial.
For now we need to declare in_Position and in_Color to match the attribute names we bound above. GLSL 1.50 also uses out from the vertex shader and matching in values in the fragment shader instead of the older varying keyword.
Uniforms absolutely still exist – the old tutorial said they were gone, which was wrong. In fact, the next tutorial is going to use uniforms to send our matrices to the shader.
#version 150 core
in vec3 in_Position;
in vec3 in_Color;
out vec3 pass_Color;
void main(void)
{
gl_Position = vec4(in_Position, 1.0);
pass_Color = in_Color;
}
Shader.frag
In our fragment shader, we are also going to declare the version of GLSL that we are working with and because we had an “out” variable in our shader.vert file, then we need an “in” variable of the same name in our fragment shader. So we are going to create an “in” variable, of type vec3 called pass_Color. Now fragment shaders no longer have gl_FragColor, instead we need to manually declare an “out” variable of type vec4, which will give our colour to our GPU. I am going to call this “out” variable out_Color and I am going to set it to the pass_Color, which is the variable we sent in to our shader.
#version 150 core
in vec3 pass_Color;
out vec4 out_Color;
void main(void)
{
out_Color = vec4(pass_Color, 1.0);
}
If all went well, you should now be set up to use shaders in your application and your program should link without any shader errors. Stick with me for the next two tutorials and by the end of the fourth tutorial we will finally be rendering something to the screen. The core-profile route takes a bit more preparation than the old immediate mode, but the payoff is that our data flow is explicit and we are using the buffer/shader path modern OpenGL was designed around. We are not magically guaranteed “maximum speed” just because we stopped using immediate mode, but we are at least using the right foundation.
Source & downloads
Questions or corrections? If something doesn’t work or you spot something I’ve got wrong, leave a comment below. These tutorials have been around a long time, so useful corrections are always welcome!
In the downloadable project it appears you have a memory leak in the OpenGLContext class. Function setupScene() dynamically creates a new instance of the Shader class. However, there is no “delete” statement anywhere, so the Shader instance never gets cleaned up. Since Shader’s destructor does not get invoked, I’m wondering what impact there is on graphics card performance or resource availability before the computer is powered down since glDetachShader(), glDeleteShader(), and glDeleteProgram() are never invoked.
Hi Graeme,
setupScene() is only supposed to be called once when the application is first run, so you are not constantly creating a new shader.
Resource availability before the computer is powered down isn’t an issue because once the OpenGL context is destroyed, everything belonging to it is destroyed.
Best practice would be to clean everything up yourself and therefore destroy the shader manually when it is either no longer needed or the application is shut down.
Thanks,
Swiftless
Why do you use ancient GLSL in what is supposed to be a 4 + tutorial?
glBindAttribLocation is no longer needed, you should be using layout modifiers.
Hi Phil,
Not sure what you mean by layout modifiers and have you checked the OpenGL 4 Core reference pages? There is nothing wrong with this call being used. It serves the purpose of allowing you to specify the index and name of a variable being used within a shader as opposed to letting OpenGL do it automatically.
Thanks,
Swiftless
Not sure which is more correct in Opengl 4 but there is a layout call that can be used inside the shader for passed in generic vertex arrays. it looks something like
layout(location = 2) in vec3 values[4];
I use them both
files of pdf version and project are broken, can’t download it. Tried IE9, IE10 and Chrome
Hi!
Very good tutorials.
But i have a problem. (Which i don’t know if it is a problem yet). But when i run the application the background color isn’t blue as it’s supposed to be, and when i resize the window, the parts that i enlarge have the color black.
Is this something that will be managed in the later tutorials, or is their something wrong?
The right link for the zip file is: http://www.swiftless.com/tutorials/opengl4/2-opengl-shaders/2-opengl-shaders.zip
😉
hi !
this tutorials are just great… nice job!!
i am actually trying to compile this tutorial, but i have trouble displaying the text like in the video u posted on top pf this page… i thing there is smth wrong with the shaders cause the only thing that is being diplayed is the window like in the tutorial 1 (empty window). what could possibly be wrong?
thnx
You don’t know how to read – that’s the thing that could possibly be wrong.
“Stick with me for the next two tutorials, and by the end of the fourth tutorial, we will now be rendering things to the screen.”
Read last few words 5 more times and I hope you’ll complete your first step on the long way of coding.
Hi!
Good tutorial.
But why do you insist on naming it OpenGL **4** tutorial?
You use OpenGL/SL 3.2…
Hey przemo_li,
I mention this in the tutorial, but my hardware at the time of writing didn’t support OpenGL 4.x so I was limited to OpenGL 3.2 and lower. However OpenGL 3 and 4 are almost identical with OpenGL 4 removing some of OpenGL 3’s deprecated methods and adds some extra extensions.
I am avoiding all deprecated and removed methods to make it fully OpenGL 3 and OpenGL 4 compatible, all you need to change is the reference to 3.2 in the code and replace it with 4.0 or higher.
Cheers,
Swiftless