130 CHAPTER 4: Turning On the Lights^
The first is called the painter’s algorithm. This means simply to draw the furthest objects
first. This is very easy in something as simple as one sphere orbiting another. But what
happens when you have very complicated 3D immersive worlds like World of Warcraft or
Second Life? These would actually use a variant of painter’s algorithm, but with some
precomputed information ahead of time that determines all possible orders of occlusion.
That information is then used to form a binary space partitioning (BSP) tree. Any place in
the 3D world can be mapped to an element in the tree, which can then be traversed to
fetch the optimum order for viewer’s location. This is very fast in execution but
complicated to set up. Fortunately, it is way overkill for our simple universe. The second
means of depth sorting isn’t sorting at all but actually uses the z component of each
individual pixel. A pixel on the screen has an x and y value, but it can also have a z value
as well, even though the Viewsonic in front of me is a flat 2D surface. As one pixel is
ready to draw on top of another, the z values are compared, and the closer of the two
wins out. Called z-buffering, it is very simple and straightforward but can chew up extra
CPU time and graphics memory for very complicated scenes. I prefer the latter, and
OpenGL makes z-buffering very easy to implement, but GLKit makes it easier. As this
book was being written, iOS5 was announced, and with great delight, I was able to
gleefully delete about 1½ pages of code and comments to replace them with a single
line to add somewhere to your view controller’s initialization code:
glEnable(GL_DEPTH_TEST);
The GLKViewController manages all of setup code now, and Apple’s wizard produced
code defaults to a depth buffer using:
view.drawableDepthFormat = GLKViewDrawableDepthFormat24;
You can select to have no buffer, one that’s 16 bits or 24 bits of resolution. The extra 8
bits is reserved for use by stencils, which will be covered later.
If it works right, you should now see the earth eclipsing the sun when in front or being
hidden while in back. See Figure 4-18.