math.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. import { NormalizedZoomValue, Point, Zoom } from "./types";
  2. import { LINE_CONFIRM_THRESHOLD } from "./constants";
  3. import { ExcalidrawLinearElement } from "./element/types";
  4. export const rotate = (
  5. x1: number,
  6. y1: number,
  7. x2: number,
  8. y2: number,
  9. angle: number,
  10. ): [number, number] =>
  11. // 𝑎′𝑥=(𝑎𝑥−𝑐𝑥)cos𝜃−(𝑎𝑦−𝑐𝑦)sin𝜃+𝑐𝑥
  12. // 𝑎′𝑦=(𝑎𝑥−𝑐𝑥)sin𝜃+(𝑎𝑦−𝑐𝑦)cos𝜃+𝑐𝑦.
  13. // https://math.stackexchange.com/questions/2204520/how-do-i-rotate-a-line-segment-in-a-specific-point-on-the-line
  14. [
  15. (x1 - x2) * Math.cos(angle) - (y1 - y2) * Math.sin(angle) + x2,
  16. (x1 - x2) * Math.sin(angle) + (y1 - y2) * Math.cos(angle) + y2,
  17. ];
  18. export const rotatePoint = (
  19. point: Point,
  20. center: Point,
  21. angle: number,
  22. ): [number, number] => rotate(point[0], point[1], center[0], center[1], angle);
  23. export const adjustXYWithRotation = (
  24. sides: {
  25. n?: boolean;
  26. e?: boolean;
  27. s?: boolean;
  28. w?: boolean;
  29. },
  30. x: number,
  31. y: number,
  32. angle: number,
  33. deltaX1: number,
  34. deltaY1: number,
  35. deltaX2: number,
  36. deltaY2: number,
  37. ): [number, number] => {
  38. const cos = Math.cos(angle);
  39. const sin = Math.sin(angle);
  40. if (sides.e && sides.w) {
  41. x += deltaX1 + deltaX2;
  42. } else if (sides.e) {
  43. x += deltaX1 * (1 + cos);
  44. y += deltaX1 * sin;
  45. x += deltaX2 * (1 - cos);
  46. y += deltaX2 * -sin;
  47. } else if (sides.w) {
  48. x += deltaX1 * (1 - cos);
  49. y += deltaX1 * -sin;
  50. x += deltaX2 * (1 + cos);
  51. y += deltaX2 * sin;
  52. }
  53. if (sides.n && sides.s) {
  54. y += deltaY1 + deltaY2;
  55. } else if (sides.n) {
  56. x += deltaY1 * sin;
  57. y += deltaY1 * (1 - cos);
  58. x += deltaY2 * -sin;
  59. y += deltaY2 * (1 + cos);
  60. } else if (sides.s) {
  61. x += deltaY1 * -sin;
  62. y += deltaY1 * (1 + cos);
  63. x += deltaY2 * sin;
  64. y += deltaY2 * (1 - cos);
  65. }
  66. return [x, y];
  67. };
  68. export const getPointOnAPath = (point: Point, path: Point[]) => {
  69. const [px, py] = point;
  70. const [start, ...other] = path;
  71. let [lastX, lastY] = start;
  72. let kLine: number = 0;
  73. let idx: number = 0;
  74. // if any item in the array is true, it means that a point is
  75. // on some segment of a line based path
  76. const retVal = other.some(([x2, y2], i) => {
  77. // we always take a line when dealing with line segments
  78. const x1 = lastX;
  79. const y1 = lastY;
  80. lastX = x2;
  81. lastY = y2;
  82. // if a point is not within the domain of the line segment
  83. // it is not on the line segment
  84. if (px < x1 || px > x2) {
  85. return false;
  86. }
  87. // check if all points lie on the same line
  88. // y1 = kx1 + b, y2 = kx2 + b
  89. // y2 - y1 = k(x2 - x2) -> k = (y2 - y1) / (x2 - x1)
  90. // coefficient for the line (p0, p1)
  91. const kL = (y2 - y1) / (x2 - x1);
  92. // coefficient for the line segment (p0, point)
  93. const kP1 = (py - y1) / (px - x1);
  94. // coefficient for the line segment (point, p1)
  95. const kP2 = (py - y2) / (px - x2);
  96. // because we are basing both lines from the same starting point
  97. // the only option for collinearity is having same coefficients
  98. // using it for floating point comparisons
  99. const epsilon = 0.3;
  100. // if coefficient is more than an arbitrary epsilon,
  101. // these lines are nor collinear
  102. if (Math.abs(kP1 - kL) > epsilon && Math.abs(kP2 - kL) > epsilon) {
  103. return false;
  104. }
  105. // store the coefficient because we are goint to need it
  106. kLine = kL;
  107. idx = i;
  108. return true;
  109. });
  110. // Return a coordinate that is always on the line segment
  111. if (retVal === true) {
  112. return { x: point[0], y: kLine * point[0], segment: idx };
  113. }
  114. return null;
  115. };
  116. export const distance2d = (x1: number, y1: number, x2: number, y2: number) => {
  117. const xd = x2 - x1;
  118. const yd = y2 - y1;
  119. return Math.hypot(xd, yd);
  120. };
  121. export const centerPoint = (a: Point, b: Point): Point => {
  122. return [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
  123. };
  124. // Checks if the first and last point are close enough
  125. // to be considered a loop
  126. export const isPathALoop = (
  127. points: ExcalidrawLinearElement["points"],
  128. /** supply if you want the loop detection to account for current zoom */
  129. zoomValue: Zoom["value"] = 1 as NormalizedZoomValue,
  130. ): boolean => {
  131. if (points.length >= 3) {
  132. const [first, last] = [points[0], points[points.length - 1]];
  133. const distance = distance2d(first[0], first[1], last[0], last[1]);
  134. // Adjusting LINE_CONFIRM_THRESHOLD to current zoom so that when zoomed in
  135. // really close we make the threshold smaller, and vice versa.
  136. return distance <= LINE_CONFIRM_THRESHOLD / zoomValue;
  137. }
  138. return false;
  139. };
  140. // Draw a line from the point to the right till infiinty
  141. // Check how many lines of the polygon does this infinite line intersects with
  142. // If the number of intersections is odd, point is in the polygon
  143. export const isPointInPolygon = (
  144. points: Point[],
  145. x: number,
  146. y: number,
  147. ): boolean => {
  148. const vertices = points.length;
  149. // There must be at least 3 vertices in polygon
  150. if (vertices < 3) {
  151. return false;
  152. }
  153. const extreme: Point = [Number.MAX_SAFE_INTEGER, y];
  154. const p: Point = [x, y];
  155. let count = 0;
  156. for (let i = 0; i < vertices; i++) {
  157. const current = points[i];
  158. const next = points[(i + 1) % vertices];
  159. if (doSegmentsIntersect(current, next, p, extreme)) {
  160. if (orderedColinearOrientation(current, p, next) === 0) {
  161. return isPointWithinBounds(current, p, next);
  162. }
  163. count++;
  164. }
  165. }
  166. // true if count is off
  167. return count % 2 === 1;
  168. };
  169. // Returns whether `q` lies inside the segment/rectangle defined by `p` and `r`.
  170. // This is an approximation to "does `q` lie on a segment `pr`" check.
  171. const isPointWithinBounds = (p: Point, q: Point, r: Point) => {
  172. return (
  173. q[0] <= Math.max(p[0], r[0]) &&
  174. q[0] >= Math.min(p[0], r[0]) &&
  175. q[1] <= Math.max(p[1], r[1]) &&
  176. q[1] >= Math.min(p[1], r[1])
  177. );
  178. };
  179. // For the ordered points p, q, r, return
  180. // 0 if p, q, r are colinear
  181. // 1 if Clockwise
  182. // 2 if counterclickwise
  183. const orderedColinearOrientation = (p: Point, q: Point, r: Point) => {
  184. const val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]);
  185. if (val === 0) {
  186. return 0;
  187. }
  188. return val > 0 ? 1 : 2;
  189. };
  190. // Check is p1q1 intersects with p2q2
  191. const doSegmentsIntersect = (p1: Point, q1: Point, p2: Point, q2: Point) => {
  192. const o1 = orderedColinearOrientation(p1, q1, p2);
  193. const o2 = orderedColinearOrientation(p1, q1, q2);
  194. const o3 = orderedColinearOrientation(p2, q2, p1);
  195. const o4 = orderedColinearOrientation(p2, q2, q1);
  196. if (o1 !== o2 && o3 !== o4) {
  197. return true;
  198. }
  199. // p1, q1 and p2 are colinear and p2 lies on segment p1q1
  200. if (o1 === 0 && isPointWithinBounds(p1, p2, q1)) {
  201. return true;
  202. }
  203. // p1, q1 and p2 are colinear and q2 lies on segment p1q1
  204. if (o2 === 0 && isPointWithinBounds(p1, q2, q1)) {
  205. return true;
  206. }
  207. // p2, q2 and p1 are colinear and p1 lies on segment p2q2
  208. if (o3 === 0 && isPointWithinBounds(p2, p1, q2)) {
  209. return true;
  210. }
  211. // p2, q2 and q1 are colinear and q1 lies on segment p2q2
  212. if (o4 === 0 && isPointWithinBounds(p2, q1, q2)) {
  213. return true;
  214. }
  215. return false;
  216. };
  217. // TODO: Rounding this point causes some shake when free drawing
  218. export const getGridPoint = (
  219. x: number,
  220. y: number,
  221. gridSize: number | null,
  222. ): [number, number] => {
  223. if (gridSize) {
  224. return [
  225. Math.round(x / gridSize) * gridSize,
  226. Math.round(y / gridSize) * gridSize,
  227. ];
  228. }
  229. return [x, y];
  230. };