collision.ts 27 KB

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