Triangle $z$-index interpolation between the vertices

630 Views Asked by At

I got a $2$D triangle, each vertex has a $2$D coordinate with a $z$-index value (NOT a $z$ coordinate!). The $z$-index value indicates whether a vertex lays on, in front of, or behind your screen (viewing plane). Negative value is behind, 0 is exactly on the plane and positive value is in front. It looks like: ($x_{\text{coord}},y_{\text{coord}},z_{\text{index}})$. Note that it always remains a $2$D triangle, the $z$-index is needed for my $z$-buffer. Now the question: how would I find the $z_{\text{index}}$ of a pixel on any given $2$d point on the triangle? I know that it has to do with interpolation between the $z$-indices respectively to the triangle's coordinates. I just don't know how to.

For example:

$A=(12,36)$; $z_{\text{index}}=5$, or $B=(12,36,5)$

$B=(50,80)$; $z_{\text{index}}=8$, or $B=(50,80,8)$.

$C=(5,24)$; $z_{\text{index}}=15$, or $C=(5,24,15)$.

This sketch should give a clearer idea (not to scale):

enter image description here

At any given point $Q(x,y)$ (for example $Q(60,40)$ ), what would be the $z$-index ($z$') at that pixel? Is there a small formula for it?

1

There are 1 best solutions below

0
On BEST ANSWER

After reading the theory behind "barycentric coordinates" and the term "weighted average", and with the help of the small answer to this question: Z-index of an arbitrary point on a flattened 3-dimensional triangle , I was able to construct a working pseudo code sample after many attempts: (v1, v2 and v3 are the triangle's vertices; p is a random point on or outside of the triangle; b contains the barycentric coordinates of p)

v1,v2,v3={x=2,y=4,z=10},{x=3,y=-1,z=18},{x=-3,y=3,z=5}
p={x=2/3,y=2}
b={
x=((v2.y-v3.y)*(p.x-v3.x)+(v3.x-v2.x)*(p.y-v3.y))/((v2.y-v3.y)*(v1.x-v3.x)+(v3.x-v2.x)*(v1.y-v3.y));
y=((v3.y-v1.y)*(p.x-v3.x)+(v1.x-v3.x)*(p.y-v3.y))/((v2.y-v3.y)*(v1.x-v3.x)+(v3.x-v2.x)*(v1.y-v3.y));
}

b.z=1-b.x-b.y
new_z_index=v1.z*b.x+v2.z*b.y+v3.z*b.z

In this example, point P is the triangle center. The new_z_index value gives the result 11, which when checked by averaging the sum of the vertices: (10+18+5)/3 also equals 11.