Setting Up a 3D Canvas
Figure 3.1 shows a simple viewing volume that we use for the examples in this chapter. The area enclosed by this volume is a Cartesian coordinate space that ranges from 100 to +100 on all three axesx, y, and z. (For a review of Cartesian coordinates, see Chapter 1, "Introduction to 3D Graphics and OpenGL.") Think of this viewing volume as your three-dimensional canvas on which you draw with OpenGL commands and functions.
We established this volume with a call to glOrtho, much as we did for others in the preceding chapter. Listing 3.1 shows the code for the ChangeSize function that is called when the window is sized (including when it is first created). This code looks a little different from that in preceding chapter, and you'll notice some unfamiliar functions (glMatrixMode, glLoadIdentity). We spend more time on these functions in Chapter 4, exploring their operation in more detail.
Figure 3.1 Cartesian viewing volume measuring 100x100x100.
Listing 3.1 Code to Establish the Viewing Volume in Figure 3.1
// Change viewing volume and viewport. Called when window is resized void ChangeSize(GLsizei w, GLsizei h) { GLfloat nRange = 100.0f; // Prevent a divide by zero if(h == 0) h = 1; // Set Viewport to window dimensions glViewport(0, 0, w, h); // Reset projection matrix stack glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Establish clipping volume (left, right, bottom, top, near, far) if (w <= h) glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange); else glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange); // Reset Model view matrix stack glMatrixMode(GL_MODELVIEW); glLoadIdentity(); }
Why the Cart Before the Horse?
Look at any of the source code in this chapter, and you'll notice some new functions in the RenderScene functions: glRotate, glPushMatrix, and glPopMatrix. Although they're covered in more detail in Chapter 4, we're introducing them now. They implement some important features that we want you to have as soon as possible. These functions let you plot and draw in 3D and help you easily visualize your drawing from different angles. All this chapter's sample programs employ the arrow keys for rotating the drawing around the x- and y-axes. Look at any 3D drawing dead-on (straight down the z-axis), and it might still look two-dimensional. But when you can spin the drawings around in space, it's much easier to see the 3D effects of what you're drawing.
There is a lot to learn about drawing in 3D, and in this chapter, we want you to focus on that. By changing only the drawing code for any of the examples that follow, you can start experimenting right away with 3D drawing and still get interesting results. Later, you'll learn how to manipulate drawings using the other functions.