Fixing the Last Example

Let's fix the last example's problems by using the z-buffer. I just copied all the code over to a new class called ZBufferTest and modified the present() method of the new ZBufferScreen class, as shown in Listing 10-4.

Listing 10-4. Excerpt from Using the Z-buffer

@0verride public void present(float deltaTime) { GL10 gl = glGraphics.getGL();


gl.glViewport(0, 0, glGraphics.getWidth(), glGraphics.getHeight());



GLU.gluPerspective(gl, 67, glGraphics.getWidth() / (float)glGraphics.getHeight(), 0.1f, 10f); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity();

gl.glEnable(GL10. GL_DEPTH_TEST);


vertices.draw(GL10.GL_TRIANGLES, 0, 6); vertices.unbind();

gl.glDisable(GL10. GL_DEPTH_TEST);

The first thing we changed is the arguments to the call to glClear(). We now clear both buffers instead of just the framebuffer.

We also enable depth-testing before we render our two triangles. After we are done with rendering all our 3D geometry, we disable depth-testing again. Why? Imagine that we want to render 2D UI elements on top of our 3D scene, like the current score or buttons. Since we'd use the SpriteBatcher for this, which only works in 2D, we wouldn't have any meaningful z-coordinates for the vertices of the 2D elements. We wouldn't need depth-testing either, since we would explicitly specify the order we want the vertices to be drawn to the screen.

The output of this example, shown in Figure 10-6, looks as expected now.

Figure 10-6. The z-buffer in action, making our rendering order-independent

Finally the green triangle in the middle is rendered correctly behind the red triangle, thanks to our new best friend, the z-buffer. But as with most friends, there are times when your friendship suffers a little from minor issues. Let's examine some caveats when using the z-buffer.

Was this article helpful?

0 0

Post a comment