Created
October 23, 2019 22:32
-
-
Save Popov72/7e856b2589f659b2e9ff7ca0a7a6f815 to your computer and use it in GitHub Desktop.
Linearize / Delinearize z depth values in fragment shaders
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment