Reading this very useful series about the graphics pipeline I realized I had never thought about what is the proper way to interpolate between vertex attributes (outputted by the vertex, domain or geometry shader to the pixel shader) using the vertices of the triangle after perspective divison. I spent some time thinking on that, and although it’s not hard to figure out and the result is described in the link above, I thought I describe one possible way to get the solution.
Let’s assume we have a triangle before perspective divison with vertices ,
,
with some corresponding vertex attributes
,
,
(e.g. texture coordinates, color, normal). After perspective divison we have
,
,
. Let’s have
. The question is, how should we compute the proper vertex attribute
corresponding to
?
Let’s think backward: assume we have . Then, of course, the vertex attribute corresponding to
is simply
. Now, what is the point
we get from
after perspective divison? Using the notation
we have
Well, it’s easy to check that the sum of the coefficients in the above interpolation between ,
and
is
. So by setting
and
, we can write
.
And basically, we are done: for a point , the corresponding vertex attribute is
, where
and
can be computed from the two equations
and
, where
.
Of course, we can solve for and
explicitly (it’s just a system a linear equations with two variable), and we get
, and
,
where . We can go further by substituting
and
into the equation for
Therefore, to do the interpolation in practice, we have two main choices:
- For given
and
values (that is, basically, for a given pixel inside the triangle) we calculate
and
, and use them to calculate all vertex attributes by a simple linear interpolation.
- For all vertex attributes
, we compute the corresponding
values, and use them to calculate the vertex attributes directly from given
and
.
Of course, in both cases we have to compute as well.