Search code examples
copenglglsl

Depth issue with infinite grid in opengl 3.3 with glsl


I'm following this article, using sokol_gfx with opengl core 3.3 profile. The grid renders, is transparent, is rendered after other objects in the scene, and blending is enabled.

When the camera is close to objects the grid will render behind them, however, as the camera moves away the grid will render in front of the objects. Also, when the camera is close to objects the grid doesnt render behind them when it should, it penetrates the object a little and then becomes transparent.

Here is an image showing the grid rendering on top of an object it should not, but also rendering behind an object it should. Both of the cubes are above the grid, it should be rendering behind both of them.

Depth

And here is an image showing the grid rendering past where it should. The bottom of the cube is on the same plane as the grid, the grid should stop at the edge of the cube, not go in a little ways and then stop.

Too much grid

Depth calculation from grid fragment shader:

float compute_depth (vec3 position) {
    vec4 clip_space_position = frag_projection * frag_view * vec4 (position.xyz, 1.0);
    return (clip_space_position.z / clip_space_position.w);
}

The full project is located here


Solution

  • I had the same issue. The problem is that the article is written for Vulkan, which handles the depth differently from OpenGL. After reading GLSL gl_FragCoord.z Calculation and Setting gl_FragDepth I managed to solve the issue by modifying the fragment shader like this:

    float compute_depth (vec3 position) {
        vec4 clip_space_position = frag_projection * frag_view * vec4 (position.xyz, 1.0);
        return 0.5 + 0.5 * (clip_space_position.z / clip_space_position.w);
    }