Now that I've discussed the theory behind OpenGL, let's see how to put it to use. To draw any shape onto the screen, there are three main steps. They are:
Clearing the screen
Resetting the view
Drawing the scene
Of these the third step consists of multiple sub-steps. I'll cover the details next.
Clearing the Screen
To set the stage for drawing, clearing the screen is a must. This can be done by using the glClear() command. This command clears the screen by setting the values of the bit plane area of the view port. glClear() takes a single argument that is the bitwise OR of several values indicating which buffer is to be cleared. The values of the parameter can be:
GL_COLOR_BUFFER_BIT, which indicates the buffers currently enabled for color writing have to be cleared.
GL_DEPTH_BUFFER_BIT, which is used to clear the depth buffer.
GL_ACCUM_BUFFER_BIT, which is used if the accumulation buffer has to be cleared.
GL_STENCIL_BUFFER_BIT, which is passed as parameter when the stencil buffer has to be cleared.
Next, the color to be used as the erasing color is specified. This can be done using glClearColor(). This command clears the color buffers specified. That means when the specified color buffers are cleared the screen is recreated accordingly. So to clear the depth buffer and set the clearing color to blue the statements would be:
The background and the required buffers have been cleared. But the actual model of the image is based on the view. The view can be considered the matrix representation of the image. In order to draw this matrix, it has to be configured as an identity. This is done using glLoadIdentity(). The statement would be:
Drawing the Scene
To draw the scene we tell OpenGL to do two things: start and stop the drawing, and issue the drawing commands.
Commands to start and stop the drawing are issued through the calls to glBegin() and glEnd(). The glBegin() command takes one parameter, namely the type of shape to be drawn. To draw using three points use GL_TRIANGLES. Use GL_QUADS for points and GL_POLYGON for multiple points. The glEnd() command tells OpenGL to stop the drawing. For example, to draw a triangle the statements would be:
glBegin(GL_TRIANGLES); : : glEnd();
The drawing commands come between these commands.
Within the drawing commands, vertex data is specified. These commands are of the type glVertex*f() where * corresponds to the number of parameters, either two or three. Each call creates a point and then connects it with the point created with the earlier call. So to create a triangle with the coordinates (0.0, 1.0, 0.0), (-1.0,-1.0, 0.0) and (1.0,-1.0, 0.0) the commands would be: