Apple does a great job of making sample code available and starting you off with simple templates to build your apps. But one thing I’ve found lacking is that the default OpenGL ES template (and GLSprite sample code) don’t have a depth buffer. I’m like, “Seriously? How can you do a 3D graphics demo or template without including a depth buffer?!”.
So here’s how you do it. First, enable depth testing somewhere in your graphics initialization code (like, say, the “– (id)init” function of ESRenderer1.m or whatever file has the OpenGL calls in it) as follows:
// enable depth testing
Then, be sure that you’re clearing the depth buffer in your render loop. There’s probably a glClear() function call in there somewhere. Replace it with this:
// clear depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
Now, finally, you’ll need to be sure that depth buffer is created once the render buffer size has been determined. If you’re using the GLSprite code or creating from an OpenGL ES template, this would be in the “– (BOOL)resizeFromLayer:(CAEAGLLayer *)layer” function, right after backingWidth and backingHeight have been set by glGetRenderbufferParameterivOES(). Here’s what you add:
// create depth render buffer storage
glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);
Oh, you’ll also need to add a “GLuint depthRenderbuffer;” to the appropriate header file, but you probably figured that out when you tried to compile the stuff above, right? Very good.
See you next class!
UPDATE: You should probably delete the depth buffer in your dealloc code as well. Here’s the code for that:
// delete depth buffer
depthRenderbuffer = 0;