how to render lines on top of object.


I need a solution to render lines (GL_LINES) on top of some object (VBO) in my scene.
I have some object in the scene and inside some of them I create lines (like a line inside a cylinder or a bone inside a character arm). By default, the lines are not visibles because they are inside the object. My problem is I need the line to appear on top of the object they are in but not on top of other objects.

The solutions I tried was:

  • make the object semi-transparent so we can see inside and the line appear (if they are draw in the right order) but I dont like that the object become transparent.
  • using a custom shader to move the line closer to the camera (but the lines could appear on top of other objects if this offset is constant and too high)
    -projecting the line onto the object based on the camera position (not very efficient and the projection have to be redone each time the camera move (could be problematic with hundred of lines that needs to be projected onto thousands of polygons)
  • asking on the forum to have other ideas…

thank you for reading this.
Have a good day.

Stencil Buffer to the rescue:

step 0: Clear the stencil buffer to zero.
step 1: Draw your object with normal depth test, increment the stencil buffer for each fragment passing the depth test.
step 2: Draw the lines with depth test and depth write disabled, but Stencil test > 0.

The line will overwrite the object, as the depth test is disabled, but it will only draw on fragments where the object was visible, so it will not overwrite anything that occludes the object.

If you draw multiple objects you must clear the stencil buffer between them, otherwise you can just clear the stencil at the start of the frame together with the depth buffer.

If you simply want to draw the skeleton of an animated character (e.g. for debugging purposes), calling glDisable(GL_DEPTH_TEST) before drawing the lines should be sufficient.

If you desire proper depth order and/or occlusion of the lines by other objects, you’ll probably need to use the stencil buffer as mbentrup described.