Search code examples
c++opengldeferred-rendering

Deferred Rendering: Use depth buffer from Gbuffer in default framebuffer


I am making a deferred rendering application with C++ and OpenGL. After doing the geometry and light passes I want to render some particles. But I need some depth testing on those. So what I want to do is to use the depth buffer binded to my GBuffer to do some depth testing when drawing to the default OpenGL framebuffer.

I make and bind the depth buffer/texture to the framebuffer/GBuffer like this

glGenTextures(1, &_depthTextureID);
glBindTexture(GL_TEXTURE_2D, _depthTextureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, _width, _height, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, _depthTextureID, 0);

How do I bind the Gbuffer depth buffer to the default framebuffer for depth testing on the geometry pass?


Solution

  • You can't bind created render buffers or textures to the default framebuffer. The default framebuffer is fixed.

    But you can copy the depth texture to the default framebuffer when rendering the GBuffer to it by setting gl_FragDepth in your fragment shader.