collision.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { Point, Polygon, GeometricShape } from "./geometry/shape";
  2. import {
  3. pointInEllipse,
  4. pointInPolygon,
  5. pointOnCurve,
  6. pointOnEllipse,
  7. pointOnLine,
  8. pointOnPolycurve,
  9. pointOnPolygon,
  10. pointOnPolyline,
  11. close,
  12. } from "./geometry/geometry";
  13. // check if the given point is considered on the given shape's border
  14. export const isPointOnShape = (
  15. point: Point,
  16. shape: GeometricShape,
  17. tolerance = 0,
  18. ) => {
  19. // get the distance from the given point to the given element
  20. // check if the distance is within the given epsilon range
  21. switch (shape.type) {
  22. case "polygon":
  23. return pointOnPolygon(point, shape.data, tolerance);
  24. case "ellipse":
  25. return pointOnEllipse(point, shape.data, tolerance);
  26. case "line":
  27. return pointOnLine(point, shape.data, tolerance);
  28. case "polyline":
  29. return pointOnPolyline(point, shape.data, tolerance);
  30. case "curve":
  31. return pointOnCurve(point, shape.data, tolerance);
  32. case "polycurve":
  33. return pointOnPolycurve(point, shape.data, tolerance);
  34. default:
  35. throw Error(`shape ${shape} is not implemented`);
  36. }
  37. };
  38. // check if the given point is considered inside the element's border
  39. export const isPointInShape = (point: Point, shape: GeometricShape) => {
  40. switch (shape.type) {
  41. case "polygon":
  42. return pointInPolygon(point, shape.data);
  43. case "line":
  44. return false;
  45. case "curve":
  46. return false;
  47. case "ellipse":
  48. return pointInEllipse(point, shape.data);
  49. case "polyline": {
  50. const polygon = close(shape.data.flat()) as Polygon;
  51. return pointInPolygon(point, polygon);
  52. }
  53. case "polycurve": {
  54. return false;
  55. }
  56. default:
  57. throw Error(`shape ${shape} is not implemented`);
  58. }
  59. };
  60. // check if the given element is in the given bounds
  61. export const isPointInBounds = (point: Point, bounds: Polygon) => {
  62. return pointInPolygon(point, bounds);
  63. };