FBO and depth buffer

After I rendered a scene in normal color and depth buffers, is it possible to draw to a FBO while doing the depth testing on the regular depth buffer I draw the original scene to?

No, it’s not possible.

You could try copying the depth to a texture with glCopyTexSubImage and binding this to the FBO, but I’m not sure if that’s the fastest approach. It might be that just rendering the same scene a second time might be faster, depending on how complex the scene is.

I think that you can achieve what you are after by creating a FBO with two color attachments and using the draw buffers extension to draw to them one at a time (making them use the same depth buffer).

Here is some sample code. First initialise the FBO:

// generate the framebuffer object
glGenFramebuffersEXT(1, &fb); 

// bind framebuffer
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);
    
// attach color texture 0 to framebuffer
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_RECTANGLE_ARB, color_tex_0, 0);
    
// attach color texture 1 to framebuffer
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_TEXTURE_RECTANGLE_ARB, color_tex_1, 0);

// attach depth renderbuffer
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_rb);

Then render your scene to the first color buffer:

// only draw to colour (and depth)
glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);

// render scene

Then change to rendering to the second color buffer (while still using the same depth buffer):

// only draw to colour (and depth)
glDrawBuffer(GL_COLOR_ATTACHMENT1_EXT);

// render scene

Finally, use a fullscreen textured quad to draw whichever color buffer you want to the window system FBO. If you need to copy the depth buffer to the window system FBO, you can use a depth component texture instead of a depth render buffer and write a basic fragment shader to set fragment depths.