Reconstructing world coordinates from depth buffer and arbitrary view-projection matrix

前端 未结 3 1901
有刺的猬
有刺的猬 2021-02-15 13:20

I\'m trying to reconstruct 3D world coordinates from depth values in my deferred renderer, but I\'m having a heck of a time. Most of the examples I find online assume a standard

相关标签:
3条回答
  • 2021-02-15 14:16

    Your general approach is correct, you just did not invert the window space transform correctly. Window space z (which you probably wtrot into your depth texture) is [0,1] (by default, more general would be glDepthRange()), but NDC space z is [-1,1]. So you could change that line analogous to your x and y mappings to

    clipSpaceLocation.z = texture(depthSampler, texcoord).r * 2.0 - 1.0;
    
    0 讨论(0)
  • 2021-02-15 14:18

    I only needed to make a tiny fix. The line:

    clipSpaceLocation.z = texture(depthSampler, texcoord).r;
    

    should read:

    clipSpaceLocation.z = texture(depthSampler, texcoord).r * 2.0f - 1.0f;
    

    The way I understand it, projection matrices are designed so they map the near and far planes to [-1,1], not [0,1] like I had always assumed. OpenGL then normalizes them to the range [0,1] (a.k.a. "Window Space"), so I needed to perform the inverse of that normalization.

    This is all assuming glDepthRange(0, 1), which it is by default, and there's little reason to change it.

    0 讨论(0)
  • 2021-02-15 14:18

    See my answer on gamedev.stackexchange for a more efficient way to reconstruct world and view space positions:

    https://gamedev.stackexchange.com/a/111885/24009

    0 讨论(0)
提交回复
热议问题