collision.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. import * as GA from "../ga";
  2. import * as GAPoint from "../gapoints";
  3. import * as GADirection from "../gadirections";
  4. import * as GALine from "../galines";
  5. import * as GATransform from "../gatransforms";
  6. import {
  7. distance2d,
  8. rotatePoint,
  9. isPathALoop,
  10. isPointInPolygon,
  11. rotate,
  12. } from "../math";
  13. import { pointsOnBezierCurves } from "points-on-curve";
  14. import {
  15. NonDeletedExcalidrawElement,
  16. ExcalidrawBindableElement,
  17. ExcalidrawElement,
  18. ExcalidrawRectangleElement,
  19. ExcalidrawDiamondElement,
  20. ExcalidrawTextElement,
  21. ExcalidrawEllipseElement,
  22. NonDeleted,
  23. ExcalidrawFreeDrawElement,
  24. ExcalidrawImageElement,
  25. } from "./types";
  26. import { getElementAbsoluteCoords, getCurvePathOps, Bounds } from "./bounds";
  27. import { Point } from "../types";
  28. import { Drawable } from "roughjs/bin/core";
  29. import { AppState } from "../types";
  30. import { getShapeForElement } from "../renderer/renderElement";
  31. import { hasBoundTextElement, isImageElement } from "./typeChecks";
  32. import { isTextElement } from ".";
  33. import { isTransparent } from "../utils";
  34. const isElementDraggableFromInside = (
  35. element: NonDeletedExcalidrawElement,
  36. ): boolean => {
  37. if (element.type === "arrow") {
  38. return false;
  39. }
  40. if (element.type === "freedraw") {
  41. return true;
  42. }
  43. const isDraggableFromInside =
  44. !isTransparent(element.backgroundColor) || hasBoundTextElement(element);
  45. if (element.type === "line") {
  46. return isDraggableFromInside && isPathALoop(element.points);
  47. }
  48. return isDraggableFromInside || isImageElement(element);
  49. };
  50. export const hitTest = (
  51. element: NonDeletedExcalidrawElement,
  52. appState: AppState,
  53. x: number,
  54. y: number,
  55. ): boolean => {
  56. // How many pixels off the shape boundary we still consider a hit
  57. const threshold = 10 / appState.zoom.value;
  58. const point: Point = [x, y];
  59. if (isElementSelected(appState, element)) {
  60. return isPointHittingElementBoundingBox(element, point, threshold);
  61. }
  62. return isHittingElementNotConsideringBoundingBox(element, appState, point);
  63. };
  64. export const isHittingElementBoundingBoxWithoutHittingElement = (
  65. element: NonDeletedExcalidrawElement,
  66. appState: AppState,
  67. x: number,
  68. y: number,
  69. ): boolean => {
  70. const threshold = 10 / appState.zoom.value;
  71. return (
  72. !isHittingElementNotConsideringBoundingBox(element, appState, [x, y]) &&
  73. isPointHittingElementBoundingBox(element, [x, y], threshold)
  74. );
  75. };
  76. export const isHittingElementNotConsideringBoundingBox = (
  77. element: NonDeletedExcalidrawElement,
  78. appState: AppState,
  79. point: Point,
  80. ): boolean => {
  81. const threshold = 10 / appState.zoom.value;
  82. const check = isTextElement(element)
  83. ? isStrictlyInside
  84. : isElementDraggableFromInside(element)
  85. ? isInsideCheck
  86. : isNearCheck;
  87. return hitTestPointAgainstElement({ element, point, threshold, check });
  88. };
  89. const isElementSelected = (
  90. appState: AppState,
  91. element: NonDeleted<ExcalidrawElement>,
  92. ) => appState.selectedElementIds[element.id];
  93. export const isPointHittingElementBoundingBox = (
  94. element: NonDeleted<ExcalidrawElement>,
  95. [x, y]: Point,
  96. threshold: number,
  97. ) => {
  98. const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
  99. const elementCenterX = (x1 + x2) / 2;
  100. const elementCenterY = (y1 + y2) / 2;
  101. // reverse rotate to take element's angle into account.
  102. const [rotatedX, rotatedY] = rotate(
  103. x,
  104. y,
  105. elementCenterX,
  106. elementCenterY,
  107. -element.angle,
  108. );
  109. return (
  110. rotatedX > x1 - threshold &&
  111. rotatedX < x2 + threshold &&
  112. rotatedY > y1 - threshold &&
  113. rotatedY < y2 + threshold
  114. );
  115. };
  116. export const bindingBorderTest = (
  117. element: NonDeleted<ExcalidrawBindableElement>,
  118. { x, y }: { x: number; y: number },
  119. ): boolean => {
  120. const threshold = maxBindingGap(element, element.width, element.height);
  121. const check = isOutsideCheck;
  122. const point: Point = [x, y];
  123. return hitTestPointAgainstElement({ element, point, threshold, check });
  124. };
  125. export const maxBindingGap = (
  126. element: ExcalidrawElement,
  127. elementWidth: number,
  128. elementHeight: number,
  129. ): number => {
  130. // Aligns diamonds with rectangles
  131. const shapeRatio = element.type === "diamond" ? 1 / Math.sqrt(2) : 1;
  132. const smallerDimension = shapeRatio * Math.min(elementWidth, elementHeight);
  133. // We make the bindable boundary bigger for bigger elements
  134. return Math.max(16, Math.min(0.25 * smallerDimension, 32));
  135. };
  136. type HitTestArgs = {
  137. element: NonDeletedExcalidrawElement;
  138. point: Point;
  139. threshold: number;
  140. check: (distance: number, threshold: number) => boolean;
  141. };
  142. const hitTestPointAgainstElement = (args: HitTestArgs): boolean => {
  143. switch (args.element.type) {
  144. case "rectangle":
  145. case "image":
  146. case "text":
  147. case "diamond":
  148. case "ellipse":
  149. const distance = distanceToBindableElement(args.element, args.point);
  150. return args.check(distance, args.threshold);
  151. case "freedraw": {
  152. if (
  153. !args.check(
  154. distanceToRectangle(args.element, args.point),
  155. args.threshold,
  156. )
  157. ) {
  158. return false;
  159. }
  160. return hitTestFreeDrawElement(args.element, args.point, args.threshold);
  161. }
  162. case "arrow":
  163. case "line":
  164. return hitTestLinear(args);
  165. case "selection":
  166. console.warn(
  167. "This should not happen, we need to investigate why it does.",
  168. );
  169. return false;
  170. }
  171. };
  172. export const distanceToBindableElement = (
  173. element: ExcalidrawBindableElement,
  174. point: Point,
  175. ): number => {
  176. switch (element.type) {
  177. case "rectangle":
  178. case "image":
  179. case "text":
  180. return distanceToRectangle(element, point);
  181. case "diamond":
  182. return distanceToDiamond(element, point);
  183. case "ellipse":
  184. return distanceToEllipse(element, point);
  185. }
  186. };
  187. const isStrictlyInside = (distance: number, threshold: number): boolean => {
  188. return distance < 0;
  189. };
  190. const isInsideCheck = (distance: number, threshold: number): boolean => {
  191. return distance < threshold;
  192. };
  193. const isNearCheck = (distance: number, threshold: number): boolean => {
  194. return Math.abs(distance) < threshold;
  195. };
  196. const isOutsideCheck = (distance: number, threshold: number): boolean => {
  197. return 0 <= distance && distance < threshold;
  198. };
  199. const distanceToRectangle = (
  200. element:
  201. | ExcalidrawRectangleElement
  202. | ExcalidrawTextElement
  203. | ExcalidrawFreeDrawElement
  204. | ExcalidrawImageElement,
  205. point: Point,
  206. ): number => {
  207. const [, pointRel, hwidth, hheight] = pointRelativeToElement(element, point);
  208. return Math.max(
  209. GAPoint.distanceToLine(pointRel, GALine.equation(0, 1, -hheight)),
  210. GAPoint.distanceToLine(pointRel, GALine.equation(1, 0, -hwidth)),
  211. );
  212. };
  213. const distanceToDiamond = (
  214. element: ExcalidrawDiamondElement,
  215. point: Point,
  216. ): number => {
  217. const [, pointRel, hwidth, hheight] = pointRelativeToElement(element, point);
  218. const side = GALine.equation(hheight, hwidth, -hheight * hwidth);
  219. return GAPoint.distanceToLine(pointRel, side);
  220. };
  221. const distanceToEllipse = (
  222. element: ExcalidrawEllipseElement,
  223. point: Point,
  224. ): number => {
  225. const [pointRel, tangent] = ellipseParamsForTest(element, point);
  226. return -GALine.sign(tangent) * GAPoint.distanceToLine(pointRel, tangent);
  227. };
  228. const ellipseParamsForTest = (
  229. element: ExcalidrawEllipseElement,
  230. point: Point,
  231. ): [GA.Point, GA.Line] => {
  232. const [, pointRel, hwidth, hheight] = pointRelativeToElement(element, point);
  233. const [px, py] = GAPoint.toTuple(pointRel);
  234. // We're working in positive quadrant, so start with `t = 45deg`, `tx=cos(t)`
  235. let tx = 0.707;
  236. let ty = 0.707;
  237. const a = hwidth;
  238. const b = hheight;
  239. // This is a numerical method to find the params tx, ty at which
  240. // the ellipse has the closest point to the given point
  241. [0, 1, 2, 3].forEach((_) => {
  242. const xx = a * tx;
  243. const yy = b * ty;
  244. const ex = ((a * a - b * b) * tx ** 3) / a;
  245. const ey = ((b * b - a * a) * ty ** 3) / b;
  246. const rx = xx - ex;
  247. const ry = yy - ey;
  248. const qx = px - ex;
  249. const qy = py - ey;
  250. const r = Math.hypot(ry, rx);
  251. const q = Math.hypot(qy, qx);
  252. tx = Math.min(1, Math.max(0, ((qx * r) / q + ex) / a));
  253. ty = Math.min(1, Math.max(0, ((qy * r) / q + ey) / b));
  254. const t = Math.hypot(ty, tx);
  255. tx /= t;
  256. ty /= t;
  257. });
  258. const closestPoint = GA.point(a * tx, b * ty);
  259. const tangent = GALine.orthogonalThrough(pointRel, closestPoint);
  260. return [pointRel, tangent];
  261. };
  262. const hitTestFreeDrawElement = (
  263. element: ExcalidrawFreeDrawElement,
  264. point: Point,
  265. threshold: number,
  266. ): boolean => {
  267. // Check point-distance-to-line-segment for every segment in the
  268. // element's points (its input points, not its outline points).
  269. // This is... okay? It's plenty fast, but the GA library may
  270. // have a faster option.
  271. let x: number;
  272. let y: number;
  273. if (element.angle === 0) {
  274. x = point[0] - element.x;
  275. y = point[1] - element.y;
  276. } else {
  277. // Counter-rotate the point around center before testing
  278. const [minX, minY, maxX, maxY] = getElementAbsoluteCoords(element);
  279. const rotatedPoint = rotatePoint(
  280. point,
  281. [minX + (maxX - minX) / 2, minY + (maxY - minY) / 2],
  282. -element.angle,
  283. );
  284. x = rotatedPoint[0] - element.x;
  285. y = rotatedPoint[1] - element.y;
  286. }
  287. let [A, B] = element.points;
  288. let P: readonly [number, number];
  289. // For freedraw dots
  290. if (
  291. distance2d(A[0], A[1], x, y) < threshold ||
  292. distance2d(B[0], B[1], x, y) < threshold
  293. ) {
  294. return true;
  295. }
  296. // For freedraw lines
  297. for (let i = 0; i < element.points.length; i++) {
  298. const delta = [B[0] - A[0], B[1] - A[1]];
  299. const length = Math.hypot(delta[1], delta[0]);
  300. const U = [delta[0] / length, delta[1] / length];
  301. const C = [x - A[0], y - A[1]];
  302. const d = (C[0] * U[0] + C[1] * U[1]) / Math.hypot(U[1], U[0]);
  303. P = [A[0] + U[0] * d, A[1] + U[1] * d];
  304. const da = distance2d(P[0], P[1], A[0], A[1]);
  305. const db = distance2d(P[0], P[1], B[0], B[1]);
  306. P = db < da && da > length ? B : da < db && db > length ? A : P;
  307. if (Math.hypot(y - P[1], x - P[0]) < threshold) {
  308. return true;
  309. }
  310. A = B;
  311. B = element.points[i + 1];
  312. }
  313. return false;
  314. };
  315. const hitTestLinear = (args: HitTestArgs): boolean => {
  316. const { element, threshold } = args;
  317. if (!getShapeForElement(element)) {
  318. return false;
  319. }
  320. const [point, pointAbs, hwidth, hheight] = pointRelativeToElement(
  321. args.element,
  322. args.point,
  323. );
  324. const side1 = GALine.equation(0, 1, -hheight);
  325. const side2 = GALine.equation(1, 0, -hwidth);
  326. if (
  327. !isInsideCheck(GAPoint.distanceToLine(pointAbs, side1), threshold) ||
  328. !isInsideCheck(GAPoint.distanceToLine(pointAbs, side2), threshold)
  329. ) {
  330. return false;
  331. }
  332. const [relX, relY] = GAPoint.toTuple(point);
  333. const shape = getShapeForElement(element) as Drawable[];
  334. if (args.check === isInsideCheck) {
  335. const hit = shape.some((subshape) =>
  336. hitTestCurveInside(subshape, relX, relY, element.strokeSharpness),
  337. );
  338. if (hit) {
  339. return true;
  340. }
  341. }
  342. // hit test all "subshapes" of the linear element
  343. return shape.some((subshape) =>
  344. hitTestRoughShape(subshape, relX, relY, threshold),
  345. );
  346. };
  347. // Returns:
  348. // 1. the point relative to the elements (x, y) position
  349. // 2. the point relative to the element's center with positive (x, y)
  350. // 3. half element width
  351. // 4. half element height
  352. //
  353. // Note that for linear elements the (x, y) position is not at the
  354. // top right corner of their boundary.
  355. //
  356. // Rectangles, diamonds and ellipses are symmetrical over axes,
  357. // and other elements have a rectangular boundary,
  358. // so we only need to perform hit tests for the positive quadrant.
  359. const pointRelativeToElement = (
  360. element: ExcalidrawElement,
  361. pointTuple: Point,
  362. ): [GA.Point, GA.Point, number, number] => {
  363. const point = GAPoint.from(pointTuple);
  364. const elementCoords = getElementAbsoluteCoords(element);
  365. const center = coordsCenter(elementCoords);
  366. // GA has angle orientation opposite to `rotate`
  367. const rotate = GATransform.rotation(center, element.angle);
  368. const pointRotated = GATransform.apply(rotate, point);
  369. const pointRelToCenter = GA.sub(pointRotated, GADirection.from(center));
  370. const pointRelToCenterAbs = GAPoint.abs(pointRelToCenter);
  371. const elementPos = GA.offset(element.x, element.y);
  372. const pointRelToPos = GA.sub(pointRotated, elementPos);
  373. const [ax, ay, bx, by] = elementCoords;
  374. const halfWidth = (bx - ax) / 2;
  375. const halfHeight = (by - ay) / 2;
  376. return [pointRelToPos, pointRelToCenterAbs, halfWidth, halfHeight];
  377. };
  378. // Returns point in absolute coordinates
  379. export const pointInAbsoluteCoords = (
  380. element: ExcalidrawElement,
  381. // Point relative to the element position
  382. point: Point,
  383. ): Point => {
  384. const [x, y] = point;
  385. const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
  386. const cx = (x2 - x1) / 2;
  387. const cy = (y2 - y1) / 2;
  388. const [rotatedX, rotatedY] = rotate(x, y, cx, cy, element.angle);
  389. return [element.x + rotatedX, element.y + rotatedY];
  390. };
  391. const relativizationToElementCenter = (
  392. element: ExcalidrawElement,
  393. ): GA.Transform => {
  394. const elementCoords = getElementAbsoluteCoords(element);
  395. const center = coordsCenter(elementCoords);
  396. // GA has angle orientation opposite to `rotate`
  397. const rotate = GATransform.rotation(center, element.angle);
  398. const translate = GA.reverse(
  399. GATransform.translation(GADirection.from(center)),
  400. );
  401. return GATransform.compose(rotate, translate);
  402. };
  403. const coordsCenter = ([ax, ay, bx, by]: Bounds): GA.Point => {
  404. return GA.point((ax + bx) / 2, (ay + by) / 2);
  405. };
  406. // The focus distance is the oriented ratio between the size of
  407. // the `element` and the "focus image" of the element on which
  408. // all focus points lie, so it's a number between -1 and 1.
  409. // The line going through `a` and `b` is a tangent to the "focus image"
  410. // of the element.
  411. export const determineFocusDistance = (
  412. element: ExcalidrawBindableElement,
  413. // Point on the line, in absolute coordinates
  414. a: Point,
  415. // Another point on the line, in absolute coordinates (closer to element)
  416. b: Point,
  417. ): number => {
  418. const relateToCenter = relativizationToElementCenter(element);
  419. const aRel = GATransform.apply(relateToCenter, GAPoint.from(a));
  420. const bRel = GATransform.apply(relateToCenter, GAPoint.from(b));
  421. const line = GALine.through(aRel, bRel);
  422. const q = element.height / element.width;
  423. const hwidth = element.width / 2;
  424. const hheight = element.height / 2;
  425. const n = line[2];
  426. const m = line[3];
  427. const c = line[1];
  428. const mabs = Math.abs(m);
  429. const nabs = Math.abs(n);
  430. switch (element.type) {
  431. case "rectangle":
  432. case "image":
  433. case "text":
  434. return c / (hwidth * (nabs + q * mabs));
  435. case "diamond":
  436. return mabs < nabs ? c / (nabs * hwidth) : c / (mabs * hheight);
  437. case "ellipse":
  438. return c / (hwidth * Math.sqrt(n ** 2 + q ** 2 * m ** 2));
  439. }
  440. };
  441. export const determineFocusPoint = (
  442. element: ExcalidrawBindableElement,
  443. // The oriented, relative distance from the center of `element` of the
  444. // returned focusPoint
  445. focus: number,
  446. adjecentPoint: Point,
  447. ): Point => {
  448. if (focus === 0) {
  449. const elementCoords = getElementAbsoluteCoords(element);
  450. const center = coordsCenter(elementCoords);
  451. return GAPoint.toTuple(center);
  452. }
  453. const relateToCenter = relativizationToElementCenter(element);
  454. const adjecentPointRel = GATransform.apply(
  455. relateToCenter,
  456. GAPoint.from(adjecentPoint),
  457. );
  458. const reverseRelateToCenter = GA.reverse(relateToCenter);
  459. let point;
  460. switch (element.type) {
  461. case "rectangle":
  462. case "image":
  463. case "text":
  464. case "diamond":
  465. point = findFocusPointForRectangulars(element, focus, adjecentPointRel);
  466. break;
  467. case "ellipse":
  468. point = findFocusPointForEllipse(element, focus, adjecentPointRel);
  469. break;
  470. }
  471. return GAPoint.toTuple(GATransform.apply(reverseRelateToCenter, point));
  472. };
  473. // Returns 2 or 0 intersection points between line going through `a` and `b`
  474. // and the `element`, in ascending order of distance from `a`.
  475. export const intersectElementWithLine = (
  476. element: ExcalidrawBindableElement,
  477. // Point on the line, in absolute coordinates
  478. a: Point,
  479. // Another point on the line, in absolute coordinates
  480. b: Point,
  481. // If given, the element is inflated by this value
  482. gap: number = 0,
  483. ): Point[] => {
  484. const relateToCenter = relativizationToElementCenter(element);
  485. const aRel = GATransform.apply(relateToCenter, GAPoint.from(a));
  486. const bRel = GATransform.apply(relateToCenter, GAPoint.from(b));
  487. const line = GALine.through(aRel, bRel);
  488. const reverseRelateToCenter = GA.reverse(relateToCenter);
  489. const intersections = getSortedElementLineIntersections(
  490. element,
  491. line,
  492. aRel,
  493. gap,
  494. );
  495. return intersections.map((point) =>
  496. GAPoint.toTuple(GATransform.apply(reverseRelateToCenter, point)),
  497. );
  498. };
  499. const getSortedElementLineIntersections = (
  500. element: ExcalidrawBindableElement,
  501. // Relative to element center
  502. line: GA.Line,
  503. // Relative to element center
  504. nearPoint: GA.Point,
  505. gap: number = 0,
  506. ): GA.Point[] => {
  507. let intersections: GA.Point[];
  508. switch (element.type) {
  509. case "rectangle":
  510. case "image":
  511. case "text":
  512. case "diamond":
  513. const corners = getCorners(element);
  514. intersections = corners
  515. .flatMap((point, i) => {
  516. const edge: [GA.Point, GA.Point] = [point, corners[(i + 1) % 4]];
  517. return intersectSegment(line, offsetSegment(edge, gap));
  518. })
  519. .concat(
  520. corners.flatMap((point) => getCircleIntersections(point, gap, line)),
  521. );
  522. break;
  523. case "ellipse":
  524. intersections = getEllipseIntersections(element, gap, line);
  525. break;
  526. }
  527. if (intersections.length < 2) {
  528. // Ignore the "edge" case of only intersecting with a single corner
  529. return [];
  530. }
  531. const sortedIntersections = intersections.sort(
  532. (i1, i2) =>
  533. GAPoint.distance(i1, nearPoint) - GAPoint.distance(i2, nearPoint),
  534. );
  535. return [
  536. sortedIntersections[0],
  537. sortedIntersections[sortedIntersections.length - 1],
  538. ];
  539. };
  540. const getCorners = (
  541. element:
  542. | ExcalidrawRectangleElement
  543. | ExcalidrawImageElement
  544. | ExcalidrawDiamondElement
  545. | ExcalidrawTextElement,
  546. scale: number = 1,
  547. ): GA.Point[] => {
  548. const hx = (scale * element.width) / 2;
  549. const hy = (scale * element.height) / 2;
  550. switch (element.type) {
  551. case "rectangle":
  552. case "image":
  553. case "text":
  554. return [
  555. GA.point(hx, hy),
  556. GA.point(hx, -hy),
  557. GA.point(-hx, -hy),
  558. GA.point(-hx, hy),
  559. ];
  560. case "diamond":
  561. return [
  562. GA.point(0, hy),
  563. GA.point(hx, 0),
  564. GA.point(0, -hy),
  565. GA.point(-hx, 0),
  566. ];
  567. }
  568. };
  569. // Returns intersection of `line` with `segment`, with `segment` moved by
  570. // `gap` in its polar direction.
  571. // If intersection conincides with second segment point returns empty array.
  572. const intersectSegment = (
  573. line: GA.Line,
  574. segment: [GA.Point, GA.Point],
  575. ): GA.Point[] => {
  576. const [a, b] = segment;
  577. const aDist = GAPoint.distanceToLine(a, line);
  578. const bDist = GAPoint.distanceToLine(b, line);
  579. if (aDist * bDist >= 0) {
  580. // The intersection is outside segment `(a, b)`
  581. return [];
  582. }
  583. return [GAPoint.intersect(line, GALine.through(a, b))];
  584. };
  585. const offsetSegment = (
  586. segment: [GA.Point, GA.Point],
  587. distance: number,
  588. ): [GA.Point, GA.Point] => {
  589. const [a, b] = segment;
  590. const offset = GATransform.translationOrthogonal(
  591. GADirection.fromTo(a, b),
  592. distance,
  593. );
  594. return [GATransform.apply(offset, a), GATransform.apply(offset, b)];
  595. };
  596. const getEllipseIntersections = (
  597. element: ExcalidrawEllipseElement,
  598. gap: number,
  599. line: GA.Line,
  600. ): GA.Point[] => {
  601. const a = element.width / 2 + gap;
  602. const b = element.height / 2 + gap;
  603. const m = line[2];
  604. const n = line[3];
  605. const c = line[1];
  606. const squares = a * a * m * m + b * b * n * n;
  607. const discr = squares - c * c;
  608. if (squares === 0 || discr <= 0) {
  609. return [];
  610. }
  611. const discrRoot = Math.sqrt(discr);
  612. const xn = -a * a * m * c;
  613. const yn = -b * b * n * c;
  614. return [
  615. GA.point(
  616. (xn + a * b * n * discrRoot) / squares,
  617. (yn - a * b * m * discrRoot) / squares,
  618. ),
  619. GA.point(
  620. (xn - a * b * n * discrRoot) / squares,
  621. (yn + a * b * m * discrRoot) / squares,
  622. ),
  623. ];
  624. };
  625. export const getCircleIntersections = (
  626. center: GA.Point,
  627. radius: number,
  628. line: GA.Line,
  629. ): GA.Point[] => {
  630. if (radius === 0) {
  631. return GAPoint.distanceToLine(line, center) === 0 ? [center] : [];
  632. }
  633. const m = line[2];
  634. const n = line[3];
  635. const c = line[1];
  636. const [a, b] = GAPoint.toTuple(center);
  637. const r = radius;
  638. const squares = m * m + n * n;
  639. const discr = r * r * squares - (m * a + n * b + c) ** 2;
  640. if (squares === 0 || discr <= 0) {
  641. return [];
  642. }
  643. const discrRoot = Math.sqrt(discr);
  644. const xn = a * n * n - b * m * n - m * c;
  645. const yn = b * m * m - a * m * n - n * c;
  646. return [
  647. GA.point((xn + n * discrRoot) / squares, (yn - m * discrRoot) / squares),
  648. GA.point((xn - n * discrRoot) / squares, (yn + m * discrRoot) / squares),
  649. ];
  650. };
  651. // The focus point is the tangent point of the "focus image" of the
  652. // `element`, where the tangent goes through `point`.
  653. export const findFocusPointForEllipse = (
  654. ellipse: ExcalidrawEllipseElement,
  655. // Between -1 and 1 (not 0) the relative size of the "focus image" of
  656. // the element on which the focus point lies
  657. relativeDistance: number,
  658. // The point for which we're trying to find the focus point, relative
  659. // to the ellipse center.
  660. point: GA.Point,
  661. ): GA.Point => {
  662. const relativeDistanceAbs = Math.abs(relativeDistance);
  663. const a = (ellipse.width * relativeDistanceAbs) / 2;
  664. const b = (ellipse.height * relativeDistanceAbs) / 2;
  665. const orientation = Math.sign(relativeDistance);
  666. const [px, pyo] = GAPoint.toTuple(point);
  667. // The calculation below can't handle py = 0
  668. const py = pyo === 0 ? 0.0001 : pyo;
  669. const squares = px ** 2 * b ** 2 + py ** 2 * a ** 2;
  670. // Tangent mx + ny + 1 = 0
  671. const m =
  672. (-px * b ** 2 +
  673. orientation * py * Math.sqrt(Math.max(0, squares - a ** 2 * b ** 2))) /
  674. squares;
  675. const n = (-m * px - 1) / py;
  676. const x = -(a ** 2 * m) / (n ** 2 * b ** 2 + m ** 2 * a ** 2);
  677. return GA.point(x, (-m * x - 1) / n);
  678. };
  679. export const findFocusPointForRectangulars = (
  680. element:
  681. | ExcalidrawRectangleElement
  682. | ExcalidrawImageElement
  683. | ExcalidrawDiamondElement
  684. | ExcalidrawTextElement,
  685. // Between -1 and 1 for how far away should the focus point be relative
  686. // to the size of the element. Sign determines orientation.
  687. relativeDistance: number,
  688. // The point for which we're trying to find the focus point, relative
  689. // to the element center.
  690. point: GA.Point,
  691. ): GA.Point => {
  692. const relativeDistanceAbs = Math.abs(relativeDistance);
  693. const orientation = Math.sign(relativeDistance);
  694. const corners = getCorners(element, relativeDistanceAbs);
  695. let maxDistance = 0;
  696. let tangentPoint: null | GA.Point = null;
  697. corners.forEach((corner) => {
  698. const distance = orientation * GALine.through(point, corner)[1];
  699. if (distance > maxDistance) {
  700. maxDistance = distance;
  701. tangentPoint = corner;
  702. }
  703. });
  704. return tangentPoint!;
  705. };
  706. const pointInBezierEquation = (
  707. p0: Point,
  708. p1: Point,
  709. p2: Point,
  710. p3: Point,
  711. [mx, my]: Point,
  712. lineThreshold: number,
  713. ) => {
  714. // B(t) = p0 * (1-t)^3 + 3p1 * t * (1-t)^2 + 3p2 * t^2 * (1-t) + p3 * t^3
  715. const equation = (t: number, idx: number) =>
  716. Math.pow(1 - t, 3) * p3[idx] +
  717. 3 * t * Math.pow(1 - t, 2) * p2[idx] +
  718. 3 * Math.pow(t, 2) * (1 - t) * p1[idx] +
  719. p0[idx] * Math.pow(t, 3);
  720. // go through t in increments of 0.01
  721. let t = 0;
  722. while (t <= 1.0) {
  723. const tx = equation(t, 0);
  724. const ty = equation(t, 1);
  725. const diff = Math.sqrt(Math.pow(tx - mx, 2) + Math.pow(ty - my, 2));
  726. if (diff < lineThreshold) {
  727. return true;
  728. }
  729. t += 0.01;
  730. }
  731. return false;
  732. };
  733. const hitTestCurveInside = (
  734. drawable: Drawable,
  735. x: number,
  736. y: number,
  737. sharpness: ExcalidrawElement["strokeSharpness"],
  738. ) => {
  739. const ops = getCurvePathOps(drawable);
  740. const points: Point[] = [];
  741. let odd = false; // select one line out of double lines
  742. for (const operation of ops) {
  743. if (operation.op === "move") {
  744. odd = !odd;
  745. if (odd) {
  746. points.push([operation.data[0], operation.data[1]]);
  747. }
  748. } else if (operation.op === "bcurveTo") {
  749. if (odd) {
  750. points.push([operation.data[0], operation.data[1]]);
  751. points.push([operation.data[2], operation.data[3]]);
  752. points.push([operation.data[4], operation.data[5]]);
  753. }
  754. }
  755. }
  756. if (points.length >= 4) {
  757. if (sharpness === "sharp") {
  758. return isPointInPolygon(points, x, y);
  759. }
  760. const polygonPoints = pointsOnBezierCurves(points as any, 10, 5);
  761. return isPointInPolygon(polygonPoints, x, y);
  762. }
  763. return false;
  764. };
  765. const hitTestRoughShape = (
  766. drawable: Drawable,
  767. x: number,
  768. y: number,
  769. lineThreshold: number,
  770. ) => {
  771. // read operations from first opSet
  772. const ops = getCurvePathOps(drawable);
  773. // set start position as (0,0) just in case
  774. // move operation does not exist (unlikely but it is worth safekeeping it)
  775. let currentP: Point = [0, 0];
  776. return ops.some(({ op, data }, idx) => {
  777. // There are only four operation types:
  778. // move, bcurveTo, lineTo, and curveTo
  779. if (op === "move") {
  780. // change starting point
  781. currentP = data as unknown as Point;
  782. // move operation does not draw anything; so, it always
  783. // returns false
  784. } else if (op === "bcurveTo") {
  785. // create points from bezier curve
  786. // bezier curve stores data as a flattened array of three positions
  787. // [x1, y1, x2, y2, x3, y3]
  788. const p1 = [data[0], data[1]] as Point;
  789. const p2 = [data[2], data[3]] as Point;
  790. const p3 = [data[4], data[5]] as Point;
  791. const p0 = currentP;
  792. currentP = p3;
  793. // check if points are on the curve
  794. // cubic bezier curves require four parameters
  795. // the first parameter is the last stored position (p0)
  796. const retVal = pointInBezierEquation(
  797. p0,
  798. p1,
  799. p2,
  800. p3,
  801. [x, y],
  802. lineThreshold,
  803. );
  804. // set end point of bezier curve as the new starting point for
  805. // upcoming operations as each operation is based on the last drawn
  806. // position of the previous operation
  807. return retVal;
  808. } else if (op === "lineTo") {
  809. // TODO: Implement this
  810. } else if (op === "qcurveTo") {
  811. // TODO: Implement this
  812. }
  813. return false;
  814. });
  815. };