PDA

View Full Version : How to unproject the gl_FragCoord?



zrzmonkey
06-03-2011, 02:14 AM
I want to unproject the gl_FragCoord to get the 3D coordinats in camera space. This is my code in fragment shader,but it doesn't work.The input is gl_FragCoord.
vec4 getcoord (vec4 a)
{
vec4 d=vec4(a.x*2/Size-1,a.y*2/Size-1,a.z*2-1,1);
vec4 c=gl_ProjectionMatrixInverse*d;
return c/c.w;
}

And,I want to calculate the coordinats in camera space using a depth buffer.So,as I know the depth of a pixel,how do I get the coordinats in camera space?I do it like this in fragment shader.Does it work?
vec4 getcoord (sampler2D depth,vec2 a)//a is the pixel's 2D screen coordinate
{
float de=texelFetch2D(depth,ivec2(a),0);
vec4 b=vec4(a,de,1.0);
vec4 c=vec4(b.x*2/Size-1,b.y*2/Size-1,b.z*2-1,1);
vec4 e=gl_ProjectionMatrixInverse*c;
return e/e.w;
}
Thanks!

Alfonse Reinheart
06-03-2011, 02:24 AM
This is my code in fragment shader,but it doesn't work.

The perspective divide happens after the projection matrix when transforming to camera space to clip space. Therefore, when reversing the transformation, it must happen before. And the division needs to be done with gl_FragCoord.w.

You can find functioning code to do this here (http://www.arcsynthesis.org/gltut/Illumination/Tut10%20Distant%20Points%20of%20Light.html).

The second part is going to be more difficult, since you don't have gl_FragCoord.w. So you're going to have to compute it.

zrzmonkey
06-03-2011, 07:52 AM
Thanks.
But I still have some confusion with the webpage you give me.
Does "clipToCameraMatrix" equal to gl_ProjectionMatrixInverse?
And I think the factor "1/gl_FragCoord.w" doesn't influence the result of "clipToCameraMatrix * clipPos",for this is a homogeneous coordinate,and I can divide the result's w after multiplying.

Alfonse Reinheart
06-03-2011, 10:47 AM
Does "clipToCameraMatrix" equal to gl_ProjectionMatrixInverse?

Yes.


And I think the factor "1/gl_FragCoord.w" doesn't influence the result of "clipToCameraMatrix * clipPos",for this is a homogeneous coordinate,and I can divide the result's w after multiplying.

But applying 1/gl_FragCoord.w to "ndcPos" is how you get "clipPos." Until you do this division, you're not in homogeneous space, and your matrix multiplication will most certainly not come out wrong.

When you invert a series of steps, you must do the inverse in reverse order.