在 OpenGL ES 2.0 中,当将 FBO 与纹理深度缓冲区一起使用时,深度纹理缓冲区不起作用

In OpenGL ES 2.0 depth texture buffer is not working when using FBO with texture depth buffer

目前我正在开发一个项目,首先将应用程序渲染到帧缓冲区对象 (FBO),然后使用 OpenGL ES 2.0 中的 FBO 颜色和深度纹理附件将应用程序渲染回来。

现在可以使用颜色缓冲区很好地呈现多个应用程序。当我尝试使用来自深度纹理缓冲区的深度信息时,它似乎不起作用。

我试着用纹理坐标采样来渲染深度纹理,它全是白色的。人们说灰度可能略有不同,即即使在阴影部分也接近 1.0。所以我将片段着色器修改为如下所示:

    vec4 depth;
    depth = texture2D(s_depth0, v_texCoord);

    if(depth.r == 1.0)
        gl_FragColor = vec4(1.0,0.0,0.0,1.0);

毫不奇怪,它全是红色的。

申请代码:

void Draw ( ESContext *esContext )
{
UserData *userData = esContext->userData;

// Clear the color buffer
glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Draw a triangle
GLfloat vVertices[] = {  0.0f,  0.5f, 0.5f, 
                       -0.5f, -0.5f,-0.5f,
                        0.5f, -0.5f,-0.5f };

// Set the viewport
glViewport ( 0, 0, esContext->width, esContext->height );

// Use the program object
glUseProgram ( userData->programObject );

// Load the vertex position
glVertexAttribPointer ( 0, 3, GL_FLOAT, GL_FALSE, 0, vVertices );

glEnableVertexAttribArray ( 0 );

glDrawArrays ( GL_TRIANGLES, 0, 3 ); 

eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );
}

那么,如果颜色缓冲区工作正常,而深度缓冲区不工作,那会有什么问题?

深度纹理需要线性化才能在视口中看到,因为它以指数形式保存。在片段中试试这个:

uniform float farClip, nearClip;

float depth = texture2D(s_depth0, v_texCoord).x;
float depthLinear = (2 * nearClip) / (farClip + nearClip - depth * (farClip - nearClip));

我终于解决了。这个原因最终是缺少 GL_DEPTH_TEST 从客户端应用程序启用。

因此,如果您遇到同样的问题,请务必在 OpenGL ES 初始化期间通过调用 glEnable(GL_DEPTH_TEST); 来启用 GL_DEPTH_TEST。我想默认情况下它是为了性能而禁用的。

感谢所有的建议和回答。