Search code examples
webgldepth-buffer

Depth image webgl


I want to draw just the depth image without any color in the following manner:

enter image description here

Is this possible? If so, can someone point me to the correct resource to get this information or give a basic explanation about the same?


Solution

  • There's no direct way to visualize the actual contents of the depth buffer in WebGL. However, it's easy to draw the depth; this is basically identical to drawing fog (in the old fixed-function style).

    In your vertex shader, pass the z component of the vertex position through a varying. While you're at it, rescale its range from [-1, 1] to [0, 1].

    // do this after you've set gl_Position, of course.
    vZ = (gl_Position.z + 1.0) / 2.0;
    

    In your fragment shader, use this value as the color.

    gl_FragColor = vec4(vZ, vZ, vZ, 0.0);
    

    Note that this will produce shading which is nonlinear in the same way as the actual depth buffer values are nonlinear. If you want linear brightness from the near plane to the far plane, you'll need to take the z coordinate from just before the projection transform, and rescale it based on the near and far plane distance.