GLSL: Tell how close a fragment is to the center of the triangle

Is there any way that I could find out how close I am to the center of the current triangle in GLSL?

I render with GL_TRIANGLES

I’m trying to come up with a new estimation method for Phong lighting.

You could add an attribute for barycentric coordinates, which would be (1,0,0), (0,1,0) or (0,0,1) at the three vertices. The interpolated value will be (1/3,1/3,1/3) at the barycentre (centroid).

As it stands, that would typically reduce the ability to share vertices between triangles. However, if you add a fourth component, any planar graph can be four-coloured (i.e. it’s possible to assign each node one of four colours such that no edge has the same colour at both ends). That would result in 3 of the components being 1/3 at the barycentre with the fourth being uniformly zero. That only applies to planar graphs (i.e. surfaces with an edge, not closed surfaces), but you would only need to duplicate a small number of vertices to make a closed surface topologically planar.

Either way, this lets you determine the “distance” from the barycentre as a proportion of the triangle’s size. If you wanted an absolute distance (in world-space or screen-space units), you’d need to calculate the scale factors, e.g. in a geometry shader or using partial derivatives.