opengl3drenderingdepth-bufferstencil-buffer

Can I solve this OpenGL problem with the depth/stencil buffers


I'm trying to render meshes with the points and edges as black lines and points, similar to a modeling engine like blender. I have 3 separate draw routines to draw points, lines, and faces (each face is one or more triangles with a shared normal). When I turn the depth test off, I get every line being rendered, obviously. Here I have down scaled the resolution so we can see the pixels.

depth test off

When I turn the depth test on, some pixels of a line have a z-value further away than the edge of the triangle that it is attached to. Thus the line fragment is rewritten by a face fragment. And I get this dotted looking effect.

depth test on

I'm trying to write a draw routine that renders the full lines of edges that are only in front of the camera. Can I utilize the stencil or depth buffer? I was initially thinking of using the stencil buffer to count how many face fragments are in front of the edge fragment. If it is zero or one, then it draws the line fragment. But this still permits line fragments that are fully behind a face and not just on a corner. This also doesn't account for two faces that are concave to the camera.

EDIT: I learned that this method is called Hidden Line Removal. I'm currently seeing if there is a way to do this with just the stencil and depth buffers.


Solution

  • The problem you're confronted with is called: Z-fighting

    The workaround to mitigate the problem is either via z-buffer resolution (distance between near and far plane - the greater the distance the lower the resolution) or via polygon offset.

    Read the wiki article (section Mitigation) and follow up with the articles on LearnOpenGl - Depth testing and on the OpenGl Wiki - Depth Buffer Precision to learn more about the topic.

    Normally, polygon offset will do most of the times.