Dissecting Display

The display function seems on the surface to be fairly simple. However, the functioning of it is fairly complicated and intertwined with the initialization done in the init function.

Example 1.1. The display Function

glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);

glUseProgram(theProgram);

glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);

glDrawArrays(GL_TRIANGLES, 0, 3);

glDisableVertexAttribArray(0);
glUseProgram(0);

glutSwapBuffers();

Let us examine this code in detail.

The first two lines clear the screen. glClearColor is one of those state setting functions; it sets the color that will be used when clearing the screen. It sets the clearing color to black. glClear does not set OpenGL state; it causes the screen to be cleared. The GL_COLOR_BUFFER_BIT parameter means that the clear call will affect the color buffer, causing it to be cleared to the current clearing color we set in the previous function.

The next line sets the current shader program to be used by all subsequent rendering commands. We will go into detail as to how this works later.

The next three commands all set state. These commands set up the coordinates of the triangle to be rendered. They tell OpenGL the location in memory that the positions of the triangle will come from. The specifics of how these work will be detailed later.

The glDrawArrays function is, as the name suggests, a rendering function. It uses the current state to generate a stream of vertices that will form triangles.

The next two lines are simply cleanup work, undoing some of the setup that was done for the purposes of rendering.

The last line, glutSwapBuffers, is a FreeGLUT command, not an OpenGL command. The OpenGL framebuffer, as we set up in framework.cpp, is double-buffered. This means that the image that is currently being shown to the user is not the same image we are rendering to. Thus, all of our rendering is hidden from view until it is shown to the user. This way, the user never sees a half-rendered image. glutSwapBuffers is the function that causes the image we are rendering to be displayed to the user.

Fork me on GitHub