Search code examples
performanceopenglgeometrytriangle-count

Fragment or geometry shaders: Count rendered triangles?


gl_PrimitiveID seems to count the number of primitives rendered. This seems to be available via both fragment and geometry shaders.

Would this be an accurate count of rendered triangles in the view frustum (assuming only tris, since the primitive ID also applies to lines and points) as opposed to the whole scene?


Solution

  • The gl_PrimitiveID variable is output from a geometry shader and fed to the fragment shader. If no geometry shader is present, then the fragment shader's gl_PrimitiveID is the number of primitives that have been processed in the current rendering call. That is, it's the number of points/lines/triangles that are sent through the vertex processing pipeline. If you call glDrawArrays(GL_TRIANGLES, 0, 33); you will get a gl_PrimitiveID on the half-open range [0, 11).

    If a geometry shader is present, then gl_PrimitiveID takes on whatever value you output from your GS. If a GS is present and you don't write to the value, then the fragment shader gets an undefined value. Note that you could just copy gl_PrimitiveIDIn into gl_PrimitiveID for each vertex you write to get the standard OpenGL behavior.

    In short, no, it does not take into account view frustum culling. Not unless your GS actually does view frustum culling per-triangle (and I would advise it).