Game Development Reference
In-Depth Information
to the average human field of view. By increasing or decreasing this value, you can see more
or less to the left and right. The next thing we specify is the aspect ratio, which is the screen's
width divided by its height. Note that this will be a floating-point number, so we have to cast one
of the values to a float before dividing. The final arguments are the near and far clipping plane
distances. Given that the virtual camera is located at the origin looking down the negative z axis,
anything with a z value less than −0.1 and greater than −10 will be between the near and far
clipping planes, and thus be potentially visible. Figure 10-5 shows the output of this example.
Figure 10-5. Perspective (mostly correct)
Now we are actually doing proper 3D graphics. As you can see, there is still a problem with the
rendering order of our triangles. That can be fixed by using the almighty z-buffer.
Z-buffer: Bringing Order to Chaos
What is a z-buffer? In Chapter 3 we discussed the framebuffer. It stores the color for each pixel
on the screen. When OpenGL ES renders a triangle to the framebuffer, it just changes the color
of the pixels that make up that triangle.
The z-buffer is very similar to the framebuffer in that it also has a storage location for each pixel
on the screen. Instead of storing colors, it stores depth values. The depth value of a pixel is
roughly the normalized distance of the corresponding point in 3D to the near clipping plane of
the view frustum.
OpenGL ES will write a depth value for each pixel of a triangle to the z-buffer by default (if a
z-buffer was created alongside the framebuffer). We simply have to tell OpenGL ES to use this
information to decide whether a pixel being drawn is closer to the near clipping plane than
the pixel that's currently there. For this, we just need to call glEnable() with an appropriate
parameter:
GL10.glEnable(GL10.GL_DEPTH_TEST);
OpenGL ES then compares the incoming pixel depth with the pixel depth that's already in the
z-buffer. If the incoming pixel depth is smaller, its corresponding pixel is closer to the near
clipping plane and thus in front of the pixel that's already in the frame- and z-buffer.
Figure 10-5 illustrates the process. The z-buffer starts off with all values set to infinity (or a very
high number). When you render the first triangle, compare each of its pixels' depth values to
the value of the pixel in the z-buffer. If the depth value of a pixel is smaller than the value in the
 
Search WWH ::




Custom Search