Getting the true z value from the depth buffer

后端 未结 3 620
广开言路
广开言路 2020-11-28 02:24

Sampling from a depth buffer in a shader returns values between 0 and 1, as expected. Given the near- and far- clip planes of the camera, how do I calculate the true z value

3条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 02:58

    I know this is an old, old question, but I've found myself back here more than once on various occasions, so I thought I'd share my code that does the forward and reverse conversions.

    This is based on @Calvin1602's answer. These work in GLSL or plain old C code.

    uniform float zNear = 0.1;
    uniform float zFar = 500.0;
    
    // depthSample from depthTexture.r, for instance
    float linearDepth(float depthSample)
    {
        depthSample = 2.0 * depthSample - 1.0;
        float zLinear = 2.0 * zNear * zFar / (zFar + zNear - depthSample * (zFar - zNear));
        return zLinear;
    }
    
    // result suitable for assigning to gl_FragDepth
    float depthSample(float linearDepth)
    {
        float nonLinearDepth = (zFar + zNear - 2.0 * zNear * zFar / linearDepth) / (zFar - zNear);
        nonLinearDepth = (nonLinearDepth + 1.0) / 2.0;
        return nonLinearDepth;
    }
    

提交回复
热议问题