Target: OpenGL ES 3.0
Suppose my default Framebuffer (the screen) already contains part of my scene rendered; its color and depth buffers contain valid data.
Now suppose I have another part of the scene rendered to an intermediate FBO 'fbo1' already. Its color data is kept in texture 'mColor', which is attached to fbo1.COLOR0 attachment, and its depth is kept in another texture 'mDepth', which is attached to the DEPTH attachment of yet another FBO 'fbo2'.
Now I would like to take mColor and render it to the Screen, taking into account the depth from mDepth. I know how to render a texture containing only color data to the screen, but I don't know how to do so taking into account the mDepth.
Essentially it looks like when we render the Quad textured with mColor to the screen, we need to compare the Screen's depth buffer not with the depth from the Quad, but with depth from mDepth. How to do that?
If you are splitting your pipeline and rendering FBO0 in multiple passes interleaved with off-screen rendering then the simple answer is "you're doing it wrong".
You're forcing the GPU to write out and read-back your intermediate states which is horribly inefficient, in particular on mobile with tile-based architectures.
Render each off-screen pass first, and then render the window surface (FBO0) to completion in a single pass.
We need to compare the Screen's depth buffer not with the depth from the Quad, but with depth from mDepth. How to do that?
Load the depth value from the depth texture, and assign that value to gl_FragDepth
in your fragment shaders. However this will force all of your fragments to a late-zs depth update, which is horribly slow compared to using the real triangle z-value at early-zs as you have to run the shader before you determine if you need to keep the fragment or not. So, as per the above I'd suggest redesigning your rendering pipeline so you don't need to do this ...