I have a triangle in 2D space. I have screen space coordinates of each vertex, and I have attribute values of each vertex.
How can I calculate dFdx / dFdy for those attributes? In other words, how will change attribute from screen pixel to pixel.
//fragment shader
varrying vec2 myAttr;
void main(void)
{
vec2 px = dFdx(myAttr);
vec2 py = dFdy(myAttr);
}
I want to get px, py. I need to know delta(grow) of myAttr
from next pixel for x and y axis.
I need formula /algorithm how to calculate them manually (for example for cases when hardware does not support derivatives).
P.S. Attribute value linear interpolated between 3 vertices (according to OpenGL doc).
assuming your vertex are structured like this:
struct vertex
{
double x; // screenspace x coordinate
double y; // screenspace y coordinate
double a; // your attribute
};
The derivation you're looking for are calculated like this:
d = (v0.x - v2.x) * (v1.y - v2.y) -
(v1.x - v2.x) * (v0.y - v2.y);
dfdx = ((v0.a - v2.a) * (v1.y - v2.y) -
(v1.a - v2.a) * (v0.y - v2.y)) / d;
dfdy = ((v0.a - v2.a) * (v1.x - v2.x) -
(v1.a - v2.a) * (v0.x - v2.x)) / d;
Note that this equation becomes unstable as d
approaches zero. It will also cause a divide by zero if d
is exactly zero. This is not a problem in practice because in this case the triangle also has a area of zero and nothing needs to be rendered.