Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing barycentric coordinates inside fragment shader

In the fragment shader, values are naturally interpolated. For example, if I have three vertices, each with a color, red for the first vertex, green for the second and blue for the third. If I render a triangle with them, the expected result is the common triangle.

Obviously, OpenGL calculates the interpolation coefficients (a, b, c) for each point inside the triangle. Is there any way to explicitly access these values or would I need to calculate the fragment coordinates of the three vertices and find the barycentric coordinates of the point myself? I know this is perfectly feasible, but I thought OpenGL could have provided something.

like image 548
Daniel Pinto Coutinho Avatar asked Aug 20 '14 05:08

Daniel Pinto Coutinho


2 Answers

I'm not aware of any built-in for getting the barycentric coordinates. But you should't need any calculations in the fragment shader.

You can pass the barycentric coordinates of the triangle vertices as attributes into the vertex shader. The attribute values for the 3 vertices are simply (1, 0, 0), (0, 1, 0), and (0, 0, 1). Then pass the attribute value through to the fragment shader (using a varying variable in legacy OpenGL, out in vertex shader and in in fragment shader in core OpenGL). Then value of the variable received by the fragment shader are the barycentric coordinates of the fragment.

This is very similar to the way you would commonly pass texture coordinates into the vertex shader, and them pass them through to the fragment shader, which receives the interpolated values.

like image 122
Reto Koradi Avatar answered Oct 13 '22 01:10

Reto Koradi


NV_fragment_shader_barycentric

like image 29
Anton Duzenko Avatar answered Oct 13 '22 00:10

Anton Duzenko