Fragment shader: how to get pixel position relative to bounding box of current primitive


Thanks to gl_FragCoord I can get the pixel-position of the currently calculated fragment relative to the framebuffer - however is there any built-in way to get the current offset to the bounding box of the current primitive?

E.g. when drawing a quad, is there any built-in operation to get the distance from the current fragment to uppermost / leftmost fragment of the quad?
The only way to achieve this I could imagine is to set a uniform before each primitive telling the shader the absolute position of the quad on screen (and subtract that from gl_FragCoord), but I am hoping I can get away without passing parameters manually to the shader for performance reasons.

Thanks, Clemens


That would require a separate draw call for each primitive, which would be horrendous for performance. It would be better to pass it as a vertex attribute; although if you’re sharing vertices between primitives, you may need to duplicate some vertices (you don’t need to duplicate everything; using the flat qualifier means that only the value for one vertex matters). Another option is to use a geometry shader to compute the primitive’s window-space bounding box (you’ll need to pass in the viewport bounds as a uniform).

1 Like

Thanks a lot - I went with your suggestion of using vertex attributes and it works like a charm :slight_smile: