PDA

View Full Version : Question about obtaining position from depth..



Jose Goruka
11-28-2008, 01:29 PM
Hi! well, here's another question.. i'm trying to compute the fragment "position" from the depth (all in the fragment shader).

I have the depth texture (previously used as depth buffer in a FBO) i loaded as texture, so i'm trying to use that.. i also have the screen size (ssize) and a texture that goes from 0 to 1 in both axis (gl_TexCoord[0]) in worldspace coordinates, so i tried to do: (in the fragment)

pos.z = -z_near - (depth * (z_far - z_near));
pos.x = (gl_TexCoord[0].s - 0.5) * 2.0 * viewport_size.x / z_near * -pos.z;
pos.y = (gl_TexCoord[0].t - 0.5) * 2.0 * viewport_size.y/ z_near * -pos.z;

however, this doesn't seem to be working properly.. is my understanding of the depth buffer wrong?

Brolingstanz
11-29-2008, 03:20 AM
Probably the easiest way to attack this is to invert the matrix that gets you from world to raster space, which is M V P W, W being the window transform that includes viewport x, y, z scaling and bias (all of this is covered in e.g. the redbook).

Mind this is a perspective transform, so you need to divide the result through by w.

If you're starting with texcoords in [0, 1] then you need to scale by (viewportwidth, viewportheight) to get a raster pos.

Jose Goruka
11-30-2008, 07:25 AM
Ah thanks a lot! I had some idea that the z stored in the zbuffer was linear, but thinking about it again, it makes sense that it's the resulting z from the perspective transform..