collision.ts 23 KB

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