Advertisement Jump to content
Sign in to follow this  

OpenGL Matching raymarcher and polygon depth values

This topic is 2487 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a raymarcher that I'm trying to integrate into a normal polygon render. For test purposes this is just the basic OpenGL pipeline, while the raymarcher uses GLSL.

I'm having trouble writing the correct Z values in the raymarcher. I appreciate most of the problems could be solved by sorting, but I don't want to have to disable the depth check when rendering polygon objects near the raymarched objects.

The projection matrix is:
static float p_fMatProj[16] = { 0 };
float aspect = width / height;
float D = 1.303f;
float zp = D;
p_fMatProj[ 0] = zp;
p_fMatProj[ 5] = zp * aspect;
p_fMatProj[10] = 1.0f;
p_fMatProj[11] = zp / D;
p_fMatProj[14] = -D;

And the ray calculation is (view space):

vec2 position = -1.0 + (2.0 * (gl_FragCoord.xy / resolution.xy));
position.y *= resolution.y / resolution.x;
vec3 target = vec3(position, 0.);
vec3 eye = vec3(0., 0., -1.303); // FOV 75 degrees.
vec3 ray = normalize(target - eye);

The Z for the polygon objects is written by the GPU, and the Z for the raymarcher is written like this:

float zc = (gl_ProjectionMatrix * vec4(point, 1.)).z;
float wc = (gl_ProjectionMatrix * vec4(point, 1.)).w;
gl_FragDepth = zc / wc;

From what I've Googled and read, that should be the correct value, or the GPU should use it to write the correct value to the Z. But the Z for the raymarcher is clearly following a different curve - polygons get drawn over it when it's near, and it gets drawn over polygons when its far.

Can anyone tell me where I'm going wrong? Or is there just not enough accuracy with a basic D projection matrix?

Share this post

Link to post
Share on other sites
After running the values manually though a spreadsheet (oh for a decent GLSL debugger) I found I needed to multiply the view space ray by 2. I'm admit I'm not mathematically certain why I need to do this, but I don't normally do my projection matrix this way (I usually use the far-near Z variety) so it could be a quirk I've introduced through that. Or it could be the view space being from -1 -> 1 instead of 0 -> 1. Note that this only works if zp == D in the above post.

I'm happy I've got it working, but I'd like to understand why. Can anyone explain? :)

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!