Graphics Reference
In-Depth Information
// Make sure plane normals for pab and pbc point in the same direction
if (bc * ac - cc * ab < 0.0f) return 0;
// Make sure plane normals for pab and pca point in the same direction
float bb = Dot(b, b);
if (ab * bc - ac * bb < 0.0f) return 0;
// Otherwise P must be in (or on) the triangle
return 1;
}
Note the strong similarities between this function and the function Barycentric()
of Section 3.4.
In 2D, this test becomes even simpler. Without loss of generality, assume the
triangle ABC is defined counterclockwise. Then, the point P lies inside the triangle
if and only if P lies to the left of the directed line segments AB , BC , and CA . These
tests are easily performed with the help of the 2D pseudo cross product, as defined
in Chapter 3. That is, given the function
// Compute the 2D pseudo cross product Dot(Perp(u), v)
float Cross2D(Vector2D u, Vector2D v)
{
return u.y * v.x - u.x * v.y;
}
the test of P lying to the left of the segment AB becomes a call to this function with
the arguments P
A and B
A , followed by a test to see if the result is positive. The
entire test then becomes:
// Test if 2D point P lies inside the counterclockwise 2D triangle ABC
int PointInTriangle(Point2D p, Point2D a, Point2D b, Point2D c)
{
// If P to the right of AB then outside triangle
if (Cross2D(p - a,b-a)<0.0f) return 0;
// If P to the right of BC then outside triangle
if (Cross2D(p - b,c-b)<0.0f) return 0;
// If P to the right of CA then outside triangle
if (Cross2D(p - c,a-c)<0.0f) return 0;
// Otherwise P must be in (or on) the triangle
return 1;
}
 
Search WWH ::




Custom Search