Depth sorting element buffer.

I am attempting to implement depth sorting on the triangles within a semi-transparent mesh by sorting the indices in my element buffer. I do this by filling an array with structures representing each triangle in the mesh. I sort the triangles far to near, then re-order the indices in the element buffer so the triangles are drawn in the appropriate order. My problem is that the mesh almost always draws as if back face culling is on. I can only see the front facing triangles, as if the mesh were not translucent. Occasionally I see triangles through the front of the mesh, but this is uncommon. To test my render settings, I tried rendering the mesh without any sorting. as I would expect, If I don’t sort the triangles the mesh sometimes renders with the far back facing triangles visible through he front of the mesh, depending on view angle. I can only assume that there is something wrong with my sorting approach but I’ve tried sorting back to front and front to back but always get similar results. I tried randomly shuffling the indices and this results in a scrambled mesh, so I know my updates are getting to the GPU. Any idea what I am doing wrong?

Here are my OpenGL state settings.



My shaders are pretty basic. They just implement the minimum to render the geometry with the Phong lighting model.

I’ve tried updating my element buffer with glBufferData() and glBufferSubData(). I’m drawing with glDrawElements()

My first guess would be that you aren’t sorting the triangles correctly. The only correct way to depth-sort triangles is to use a topological sort, splitting triangles where necessary to break cycles. As this can be computationally expensive, a total order using some measure of depth (nearest vertex, farthest vertex, centroid) is sometimes used, but this will produce incorrect results occasionally. It shouldn’t be affected by the orientation, though. Note that a total sort (qsort() etc) has to order all triangles regardless of whether they overlap. The comparison function must define a total order or the result will be garbage.

Find a view which looks wrong. Save a screenshot along with the geometry (in eye space or screen space) and the sort order.

Why are you enabling depth tests? If the triangles are sorted correctly, the test should always pass.