OpenGL - How to access depth buffer values? - Or: gl_FragCoord.z vs. Rendering depth to texture

后端 未结 2 1284
面向向阳花
面向向阳花 2020-12-05 03:36

I want to access the depth buffer value at the currently processed pixel in a pixel shader.

How can we achieve this goal? Basically, there seems to be two options:

2条回答
  •  臣服心动
    2020-12-05 04:07

    On question 1: You can't directly read from the depth buffer in the fragment shader (unless there are recent extensions I'm not familiar with). You need to render to a Frame Buffer Object (FBO). Typical steps:

    1. Create and bind an FBO. Look up calls like glGenFramebuffers and glBindFramebuffer if you have not used FBOs before.
    2. Create a texture or renderbuffer to be used as your color buffer, and attach it to the GL_COLOR_ATTACHMENT0 attachment point of your FBO with glFramebufferTexture2D or glFramebufferRenderbuffer. If you only care about the depth from this rendering pass, you can skip this and render without a color buffer.
    3. Create a depth texture, and attach it to the GL_DEPTH_ATTACHMENT attachment point of the FBO.
    4. Do your rendering that creates the depth you want to use.
    5. Use glBindFramebuffer to switch back to the default framebuffer.
    6. Bind your depth texture to a sampler used by your fragment shader.
    7. Your fragment shader can now sample from the depth texture.

    On question 2: gl_FragCoord.z is the depth value of the fragment that your shader is operating on, not the current value of the depth buffer at the fragment position.

提交回复
热议问题