triangle.ts 874 B

12345678910111213141516171819202122232425262728
  1. import type { GlobalPoint, LocalPoint, Triangle } from "./types";
  2. // Types
  3. /**
  4. * Tests if a point lies inside a triangle. This function
  5. * will return FALSE if the point lies exactly on the sides
  6. * of the triangle.
  7. *
  8. * @param triangle The triangle to test the point for
  9. * @param p The point to test whether is in the triangle
  10. * @returns TRUE if the point is inside of the triangle
  11. */
  12. export function triangleIncludesPoint<P extends GlobalPoint | LocalPoint>(
  13. [a, b, c]: Triangle<P>,
  14. p: P,
  15. ): boolean {
  16. const triangleSign = (p1: P, p2: P, p3: P) =>
  17. (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1]);
  18. const d1 = triangleSign(p, a, b);
  19. const d2 = triangleSign(p, b, c);
  20. const d3 = triangleSign(p, c, a);
  21. const has_neg = d1 < 0 || d2 < 0 || d3 < 0;
  22. const has_pos = d1 > 0 || d2 > 0 || d3 > 0;
  23. return !(has_neg && has_pos);
  24. }