Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read the depth buffer in WebGL?

Using the WebGL API, how can I get a value from the depth buffer, or in any other way determine 3D coordinates from screen coordinates (i.e. to find a location clicked on), other than by performing my own raycasting?

like image 205
Kevin Reid Avatar asked Sep 07 '11 00:09

Kevin Reid


2 Answers

Several years have passed, these days the WEBGL_depth_texture extension is widely available... unless you need to support IE.

General usage:

Preparation:

  1. Query the extension (required)
  2. Allocate a separate color and depth texture (gl.DEPTH_COMPONENT)
  3. Combine both textures in to a single framebuffer (gl.COLOR_ATTACHMENT0, gl.DEPTH_ATTACHMENT)

Rendering:

  1. Bind the framebuffer, render your scene (usually a simplified version)
  2. Unbind the framebuffer, pass the depth texture to your shaders and read it like any other texture:

    texPos.xyz = (gl_Position.xyz / gl_Position.w) * 0.5 + 0.5;
    float depthFromZBuffer = texture2D(uTexDepthBuffer, texPos.xy).x;
    
like image 90
Paul-Jan Avatar answered Sep 21 '22 04:09

Paul-Jan


I don't know if it's possible to directly access the depth buffer but if you want depth information in a texture, you'll have to create a rgba texture, attach it as a colour attachment to an frame buffer object and render depth information into the texture, using a fragment shader that writes the depth value into gl_FragColor.

For more information, see the answers to one of my older questions: WebGL - render depth to fbo texture does not work

If you google for opengl es and shadow mapping or depth, you'll find more explanations and example source code.

like image 29
Markus Avatar answered Sep 22 '22 04:09

Markus