UV coordinate on a 2D quadrilateral

Started by
9 comments, last by nullsquared 13 years, 1 month ago

Yeah, I though of looking at it the following way:

The approach of the bilinear interpolation
p[sub]1[/sub] := a + ( b - a ) * u
p[sub]2[/sub] := d + ( c - d ) * u
p := p[sub]1[/sub] + ( p[sub]2[/sub] - p[sub]1[/sub] ) * v
means that there is a line between p[sub]1[/sub] and p[sub]2[/sub] that passes through p. Expressing this line the other way, namely
p + l = p[sub]1[/sub]
p + k * l = p[sub]2[/sub]
so that l + k * l (where k is obviously need to be a negative number) is the said line. Considering that this is done in 2D, we have 4 equations with 4 unkowns (k, l[sub]x[/sub], l[sub]y[/sub], and u) where k * l[sub]x[/sub] and k * l[sub]y[/sub] are the problems. Fortunately, from the lower of the both equations, we can isolate
k * l[sub]x[/sub] = d[sub]x[/sub] - p[sub]x[/sub] + ( c[sub]x[/sub] - d[sub]x[/sub] ) * u
k * l[sub]y[/sub] = d[sub]y[/sub] - p[sub]y[/sub] + ( c[sub]y[/sub] - d[sub]y[/sub] ) * u
and divide both of these, so that
l[sub]x[/sub] / l[sub]y [/sub]= [ d[sub]x[/sub] - p[sub]x[/sub] + ( c[sub]x[/sub] - d[sub]x[/sub] ) * u ] / [ d[sub]y[/sub] - p[sub]y[/sub] + ( c[sub]y[/sub] - d[sub]y[/sub] ) * u ]

Now, using the upper of the equations to get
l[sub]x[/sub] = a[sub]x[/sub] - p[sub]x[/sub] + ( b[sub]x[/sub] - a[sub]x[/sub] ) * u
l[sub]y[/sub] = a[sub]y[/sub] - p[sub]y[/sub] + ( b[sub]y[/sub] - a[sub]y[/sub] ) * u
and setting these into the above l[sub]x[/sub] / l[sub]y[/sub], we get a quadratic equation solely in u which can be solved using the famous p,q-formula.

This gives, as luca-deltodesco has mentioned, 0 or 1 real solutions in general. But due to the fact that p always lies inside the quad, I expect 1 real solution. With that, v can be determined easily.


Thank you very, very much! This came out to be the easiest solution to implement and it works great!

In case anyone is interested in the same problem, here's some code:


double C = (double)(a.Y - p.Y) * (d.X - p.X) - (double)(a.X - p.X) * (d.Y - p.Y);
double B = (double)(a.Y - p.Y) * (c.X - d.X) + (double)(b.Y - a.Y) * (d.X - p.X) - (double)(a.X - p.X) * (c.Y - d.Y) - (double)(b.X - a.X) * (d.Y - p.Y);
double A = (double)(b.Y - a.Y) * (c.X - d.X) - (double)(b.X - a.X) * (c.Y - d.Y);

double D = B * B - 4 * A * C;

double u = (-B - Math.Sqrt(D)) / (2 * A);

double p1x = a.X + (b.X - a.X) * u;
double p2x = d.X + (c.X - d.X) * u;
double px = p.X;

double v = (px - p1x) / (p2x - p1x);

u and v are then [0,1] coordinates you can sample a texture from, etc.

Thanks again!

This topic is closed to new replies.

Advertisement