Tldraw/packages/editor/src/lib/editor/shapes/shared/arrow/curved-arrow.ts

442 wiersze
13 KiB
TypeScript
Czysty Zwykły widok Historia

tldraw zero - package shuffle (#1710) This PR moves code between our packages so that: - @tldraw/editor is a “core” library with the engine and canvas but no shapes, tools, or other things - @tldraw/tldraw contains everything particular to the experience we’ve built for tldraw At first look, this might seem like a step away from customization and configuration, however I believe it greatly increases the configuration potential of the @tldraw/editor while also providing a more accurate reflection of what configuration options actually exist for @tldraw/tldraw. ## Library changes @tldraw/editor re-exports its dependencies and @tldraw/tldraw re-exports @tldraw/editor. - users of @tldraw/editor WITHOUT @tldraw/tldraw should almost always only import things from @tldraw/editor. - users of @tldraw/tldraw should almost always only import things from @tldraw/tldraw. - @tldraw/polyfills is merged into @tldraw/editor - @tldraw/indices is merged into @tldraw/editor - @tldraw/primitives is merged mostly into @tldraw/editor, partially into @tldraw/tldraw - @tldraw/file-format is merged into @tldraw/tldraw - @tldraw/ui is merged into @tldraw/tldraw Many (many) utils and other code is moved from the editor to tldraw. For example, embeds now are entirely an feature of @tldraw/tldraw. The only big chunk of code left in core is related to arrow handling. ## API Changes The editor can now be used without tldraw's assets. We load them in @tldraw/tldraw instead, so feel free to use whatever fonts or images or whatever that you like with the editor. All tools and shapes (except for the `Group` shape) are moved to @tldraw/tldraw. This includes the `select` tool. You should use the editor with at least one tool, however, so you now also need to send in an `initialState` prop to the Editor / <TldrawEditor> component indicating which state the editor should begin in. The `components` prop now also accepts `SelectionForeground`. The complex selection component that we use for tldraw is moved to @tldraw/tldraw. The default component is quite basic but can easily be replaced via the `components` prop. We pass down our tldraw-flavored SelectionFg via `components`. Likewise with the `Scribble` component: the `DefaultScribble` no longer uses our freehand tech and is a simple path instead. We pass down the tldraw-flavored scribble via `components`. The `ExternalContentManager` (`Editor.externalContentManager`) is removed and replaced with a mapping of types to handlers. - Register new content handlers with `Editor.registerExternalContentHandler`. - Register new asset creation handlers (for files and URLs) with `Editor.registerExternalAssetHandler` ### Change Type - [x] `major` — Breaking change ### Test Plan - [x] Unit Tests - [x] End to end tests ### Release Notes - [@tldraw/editor] lots, wip - [@tldraw/ui] gone, merged to tldraw/tldraw - [@tldraw/polyfills] gone, merged to tldraw/editor - [@tldraw/primitives] gone, merged to tldraw/editor / tldraw/tldraw - [@tldraw/indices] gone, merged to tldraw/editor - [@tldraw/file-format] gone, merged to tldraw/tldraw --------- Co-authored-by: alex <alex@dytry.ch>
2023-07-17 21:22:34 +00:00
import { TLArrowShape } from '@tldraw/tlschema'
import { Mat } from '../../../../primitives/Mat'
import { Vec, VecLike } from '../../../../primitives/Vec'
tldraw zero - package shuffle (#1710) This PR moves code between our packages so that: - @tldraw/editor is a “core” library with the engine and canvas but no shapes, tools, or other things - @tldraw/tldraw contains everything particular to the experience we’ve built for tldraw At first look, this might seem like a step away from customization and configuration, however I believe it greatly increases the configuration potential of the @tldraw/editor while also providing a more accurate reflection of what configuration options actually exist for @tldraw/tldraw. ## Library changes @tldraw/editor re-exports its dependencies and @tldraw/tldraw re-exports @tldraw/editor. - users of @tldraw/editor WITHOUT @tldraw/tldraw should almost always only import things from @tldraw/editor. - users of @tldraw/tldraw should almost always only import things from @tldraw/tldraw. - @tldraw/polyfills is merged into @tldraw/editor - @tldraw/indices is merged into @tldraw/editor - @tldraw/primitives is merged mostly into @tldraw/editor, partially into @tldraw/tldraw - @tldraw/file-format is merged into @tldraw/tldraw - @tldraw/ui is merged into @tldraw/tldraw Many (many) utils and other code is moved from the editor to tldraw. For example, embeds now are entirely an feature of @tldraw/tldraw. The only big chunk of code left in core is related to arrow handling. ## API Changes The editor can now be used without tldraw's assets. We load them in @tldraw/tldraw instead, so feel free to use whatever fonts or images or whatever that you like with the editor. All tools and shapes (except for the `Group` shape) are moved to @tldraw/tldraw. This includes the `select` tool. You should use the editor with at least one tool, however, so you now also need to send in an `initialState` prop to the Editor / <TldrawEditor> component indicating which state the editor should begin in. The `components` prop now also accepts `SelectionForeground`. The complex selection component that we use for tldraw is moved to @tldraw/tldraw. The default component is quite basic but can easily be replaced via the `components` prop. We pass down our tldraw-flavored SelectionFg via `components`. Likewise with the `Scribble` component: the `DefaultScribble` no longer uses our freehand tech and is a simple path instead. We pass down the tldraw-flavored scribble via `components`. The `ExternalContentManager` (`Editor.externalContentManager`) is removed and replaced with a mapping of types to handlers. - Register new content handlers with `Editor.registerExternalContentHandler`. - Register new asset creation handlers (for files and URLs) with `Editor.registerExternalAssetHandler` ### Change Type - [x] `major` — Breaking change ### Test Plan - [x] Unit Tests - [x] End to end tests ### Release Notes - [@tldraw/editor] lots, wip - [@tldraw/ui] gone, merged to tldraw/tldraw - [@tldraw/polyfills] gone, merged to tldraw/editor - [@tldraw/primitives] gone, merged to tldraw/editor / tldraw/tldraw - [@tldraw/indices] gone, merged to tldraw/editor - [@tldraw/file-format] gone, merged to tldraw/tldraw --------- Co-authored-by: alex <alex@dytry.ch>
2023-07-17 21:22:34 +00:00
import { intersectCirclePolygon, intersectCirclePolyline } from '../../../../primitives/intersect'
2023-04-25 11:01:25 +00:00
import {
tldraw zero - package shuffle (#1710) This PR moves code between our packages so that: - @tldraw/editor is a “core” library with the engine and canvas but no shapes, tools, or other things - @tldraw/tldraw contains everything particular to the experience we’ve built for tldraw At first look, this might seem like a step away from customization and configuration, however I believe it greatly increases the configuration potential of the @tldraw/editor while also providing a more accurate reflection of what configuration options actually exist for @tldraw/tldraw. ## Library changes @tldraw/editor re-exports its dependencies and @tldraw/tldraw re-exports @tldraw/editor. - users of @tldraw/editor WITHOUT @tldraw/tldraw should almost always only import things from @tldraw/editor. - users of @tldraw/tldraw should almost always only import things from @tldraw/tldraw. - @tldraw/polyfills is merged into @tldraw/editor - @tldraw/indices is merged into @tldraw/editor - @tldraw/primitives is merged mostly into @tldraw/editor, partially into @tldraw/tldraw - @tldraw/file-format is merged into @tldraw/tldraw - @tldraw/ui is merged into @tldraw/tldraw Many (many) utils and other code is moved from the editor to tldraw. For example, embeds now are entirely an feature of @tldraw/tldraw. The only big chunk of code left in core is related to arrow handling. ## API Changes The editor can now be used without tldraw's assets. We load them in @tldraw/tldraw instead, so feel free to use whatever fonts or images or whatever that you like with the editor. All tools and shapes (except for the `Group` shape) are moved to @tldraw/tldraw. This includes the `select` tool. You should use the editor with at least one tool, however, so you now also need to send in an `initialState` prop to the Editor / <TldrawEditor> component indicating which state the editor should begin in. The `components` prop now also accepts `SelectionForeground`. The complex selection component that we use for tldraw is moved to @tldraw/tldraw. The default component is quite basic but can easily be replaced via the `components` prop. We pass down our tldraw-flavored SelectionFg via `components`. Likewise with the `Scribble` component: the `DefaultScribble` no longer uses our freehand tech and is a simple path instead. We pass down the tldraw-flavored scribble via `components`. The `ExternalContentManager` (`Editor.externalContentManager`) is removed and replaced with a mapping of types to handlers. - Register new content handlers with `Editor.registerExternalContentHandler`. - Register new asset creation handlers (for files and URLs) with `Editor.registerExternalAssetHandler` ### Change Type - [x] `major` — Breaking change ### Test Plan - [x] Unit Tests - [x] End to end tests ### Release Notes - [@tldraw/editor] lots, wip - [@tldraw/ui] gone, merged to tldraw/tldraw - [@tldraw/polyfills] gone, merged to tldraw/editor - [@tldraw/primitives] gone, merged to tldraw/editor / tldraw/tldraw - [@tldraw/indices] gone, merged to tldraw/editor - [@tldraw/file-format] gone, merged to tldraw/tldraw --------- Co-authored-by: alex <alex@dytry.ch>
2023-07-17 21:22:34 +00:00
PI,
PI2,
clockwiseAngleDist,
counterClockwiseAngleDist,
isSafeFloat,
tldraw zero - package shuffle (#1710) This PR moves code between our packages so that: - @tldraw/editor is a “core” library with the engine and canvas but no shapes, tools, or other things - @tldraw/tldraw contains everything particular to the experience we’ve built for tldraw At first look, this might seem like a step away from customization and configuration, however I believe it greatly increases the configuration potential of the @tldraw/editor while also providing a more accurate reflection of what configuration options actually exist for @tldraw/tldraw. ## Library changes @tldraw/editor re-exports its dependencies and @tldraw/tldraw re-exports @tldraw/editor. - users of @tldraw/editor WITHOUT @tldraw/tldraw should almost always only import things from @tldraw/editor. - users of @tldraw/tldraw should almost always only import things from @tldraw/tldraw. - @tldraw/polyfills is merged into @tldraw/editor - @tldraw/indices is merged into @tldraw/editor - @tldraw/primitives is merged mostly into @tldraw/editor, partially into @tldraw/tldraw - @tldraw/file-format is merged into @tldraw/tldraw - @tldraw/ui is merged into @tldraw/tldraw Many (many) utils and other code is moved from the editor to tldraw. For example, embeds now are entirely an feature of @tldraw/tldraw. The only big chunk of code left in core is related to arrow handling. ## API Changes The editor can now be used without tldraw's assets. We load them in @tldraw/tldraw instead, so feel free to use whatever fonts or images or whatever that you like with the editor. All tools and shapes (except for the `Group` shape) are moved to @tldraw/tldraw. This includes the `select` tool. You should use the editor with at least one tool, however, so you now also need to send in an `initialState` prop to the Editor / <TldrawEditor> component indicating which state the editor should begin in. The `components` prop now also accepts `SelectionForeground`. The complex selection component that we use for tldraw is moved to @tldraw/tldraw. The default component is quite basic but can easily be replaced via the `components` prop. We pass down our tldraw-flavored SelectionFg via `components`. Likewise with the `Scribble` component: the `DefaultScribble` no longer uses our freehand tech and is a simple path instead. We pass down the tldraw-flavored scribble via `components`. The `ExternalContentManager` (`Editor.externalContentManager`) is removed and replaced with a mapping of types to handlers. - Register new content handlers with `Editor.registerExternalContentHandler`. - Register new asset creation handlers (for files and URLs) with `Editor.registerExternalAssetHandler` ### Change Type - [x] `major` — Breaking change ### Test Plan - [x] Unit Tests - [x] End to end tests ### Release Notes - [@tldraw/editor] lots, wip - [@tldraw/ui] gone, merged to tldraw/tldraw - [@tldraw/polyfills] gone, merged to tldraw/editor - [@tldraw/primitives] gone, merged to tldraw/editor / tldraw/tldraw - [@tldraw/indices] gone, merged to tldraw/editor - [@tldraw/file-format] gone, merged to tldraw/tldraw --------- Co-authored-by: alex <alex@dytry.ch>
2023-07-17 21:22:34 +00:00
} from '../../../../primitives/utils'
import type { Editor } from '../../../Editor'
import { TLArcInfo, TLArrowInfo } from './arrow-types'
2023-04-25 11:01:25 +00:00
import {
BOUND_ARROW_OFFSET,
MIN_ARROW_LENGTH,
tldraw zero - package shuffle (#1710) This PR moves code between our packages so that: - @tldraw/editor is a “core” library with the engine and canvas but no shapes, tools, or other things - @tldraw/tldraw contains everything particular to the experience we’ve built for tldraw At first look, this might seem like a step away from customization and configuration, however I believe it greatly increases the configuration potential of the @tldraw/editor while also providing a more accurate reflection of what configuration options actually exist for @tldraw/tldraw. ## Library changes @tldraw/editor re-exports its dependencies and @tldraw/tldraw re-exports @tldraw/editor. - users of @tldraw/editor WITHOUT @tldraw/tldraw should almost always only import things from @tldraw/editor. - users of @tldraw/tldraw should almost always only import things from @tldraw/tldraw. - @tldraw/polyfills is merged into @tldraw/editor - @tldraw/indices is merged into @tldraw/editor - @tldraw/primitives is merged mostly into @tldraw/editor, partially into @tldraw/tldraw - @tldraw/file-format is merged into @tldraw/tldraw - @tldraw/ui is merged into @tldraw/tldraw Many (many) utils and other code is moved from the editor to tldraw. For example, embeds now are entirely an feature of @tldraw/tldraw. The only big chunk of code left in core is related to arrow handling. ## API Changes The editor can now be used without tldraw's assets. We load them in @tldraw/tldraw instead, so feel free to use whatever fonts or images or whatever that you like with the editor. All tools and shapes (except for the `Group` shape) are moved to @tldraw/tldraw. This includes the `select` tool. You should use the editor with at least one tool, however, so you now also need to send in an `initialState` prop to the Editor / <TldrawEditor> component indicating which state the editor should begin in. The `components` prop now also accepts `SelectionForeground`. The complex selection component that we use for tldraw is moved to @tldraw/tldraw. The default component is quite basic but can easily be replaced via the `components` prop. We pass down our tldraw-flavored SelectionFg via `components`. Likewise with the `Scribble` component: the `DefaultScribble` no longer uses our freehand tech and is a simple path instead. We pass down the tldraw-flavored scribble via `components`. The `ExternalContentManager` (`Editor.externalContentManager`) is removed and replaced with a mapping of types to handlers. - Register new content handlers with `Editor.registerExternalContentHandler`. - Register new asset creation handlers (for files and URLs) with `Editor.registerExternalAssetHandler` ### Change Type - [x] `major` — Breaking change ### Test Plan - [x] Unit Tests - [x] End to end tests ### Release Notes - [@tldraw/editor] lots, wip - [@tldraw/ui] gone, merged to tldraw/tldraw - [@tldraw/polyfills] gone, merged to tldraw/editor - [@tldraw/primitives] gone, merged to tldraw/editor / tldraw/tldraw - [@tldraw/indices] gone, merged to tldraw/editor - [@tldraw/file-format] gone, merged to tldraw/tldraw --------- Co-authored-by: alex <alex@dytry.ch>
2023-07-17 21:22:34 +00:00
STROKE_SIZES,
2023-04-25 11:01:25 +00:00
WAY_TOO_BIG_ARROW_BEND_FACTOR,
tldraw zero - package shuffle (#1710) This PR moves code between our packages so that: - @tldraw/editor is a “core” library with the engine and canvas but no shapes, tools, or other things - @tldraw/tldraw contains everything particular to the experience we’ve built for tldraw At first look, this might seem like a step away from customization and configuration, however I believe it greatly increases the configuration potential of the @tldraw/editor while also providing a more accurate reflection of what configuration options actually exist for @tldraw/tldraw. ## Library changes @tldraw/editor re-exports its dependencies and @tldraw/tldraw re-exports @tldraw/editor. - users of @tldraw/editor WITHOUT @tldraw/tldraw should almost always only import things from @tldraw/editor. - users of @tldraw/tldraw should almost always only import things from @tldraw/tldraw. - @tldraw/polyfills is merged into @tldraw/editor - @tldraw/indices is merged into @tldraw/editor - @tldraw/primitives is merged mostly into @tldraw/editor, partially into @tldraw/tldraw - @tldraw/file-format is merged into @tldraw/tldraw - @tldraw/ui is merged into @tldraw/tldraw Many (many) utils and other code is moved from the editor to tldraw. For example, embeds now are entirely an feature of @tldraw/tldraw. The only big chunk of code left in core is related to arrow handling. ## API Changes The editor can now be used without tldraw's assets. We load them in @tldraw/tldraw instead, so feel free to use whatever fonts or images or whatever that you like with the editor. All tools and shapes (except for the `Group` shape) are moved to @tldraw/tldraw. This includes the `select` tool. You should use the editor with at least one tool, however, so you now also need to send in an `initialState` prop to the Editor / <TldrawEditor> component indicating which state the editor should begin in. The `components` prop now also accepts `SelectionForeground`. The complex selection component that we use for tldraw is moved to @tldraw/tldraw. The default component is quite basic but can easily be replaced via the `components` prop. We pass down our tldraw-flavored SelectionFg via `components`. Likewise with the `Scribble` component: the `DefaultScribble` no longer uses our freehand tech and is a simple path instead. We pass down the tldraw-flavored scribble via `components`. The `ExternalContentManager` (`Editor.externalContentManager`) is removed and replaced with a mapping of types to handlers. - Register new content handlers with `Editor.registerExternalContentHandler`. - Register new asset creation handlers (for files and URLs) with `Editor.registerExternalAssetHandler` ### Change Type - [x] `major` — Breaking change ### Test Plan - [x] Unit Tests - [x] End to end tests ### Release Notes - [@tldraw/editor] lots, wip - [@tldraw/ui] gone, merged to tldraw/tldraw - [@tldraw/polyfills] gone, merged to tldraw/editor - [@tldraw/primitives] gone, merged to tldraw/editor / tldraw/tldraw - [@tldraw/indices] gone, merged to tldraw/editor - [@tldraw/file-format] gone, merged to tldraw/tldraw --------- Co-authored-by: alex <alex@dytry.ch>
2023-07-17 21:22:34 +00:00
getArrowTerminalsInArrowSpace,
getBoundShapeInfoForTerminal,
[improvements] arrows x enclosing shapes x precision. (#2265) This PR makes several improvements to the behavior of arrows as they relate to precision and container relationships. - an arrow's terminals are always "true" and are never snapped to { x: .5, y: .5 } as they were previously when not precise - instead, a new `isPrecise` boolean is added to the arrow terminal - when an arrow terminal renders "imprecisely" it will be placed to the center of the bound shape - when an arrow terminal renders "precisely" it will be placed at the normalized location within the bound shape ![Kapture 2023-11-29 at 23 12 12](https://github.com/tldraw/tldraw/assets/23072548/e94e1594-75fa-4c94-86f3-7d911bf25f7f) The logic now is... - if the user has indicated precision by "pausing" while drawing the arrow, it will be precise - otherwise... - if both of an arrow's terminals are bound to the same shape, both will be precise - if a terminal is bound to a shape that contains the shape that its opposite terminal is bound to, it will be precise - if a terminal is bound to a shape that contains the shape that its opposite terminal is bound to, it will be precise - or else it will be imprecise If the spatial relationships change, the precision may change as well. Fixes https://github.com/tldraw/tldraw/issues/2204 Note: a previous version of this PR was based around ancestry but that's not actually important. ### Change Type - [x] `minor` — New feature ### Test Plan 1. Draw an arrow between a frame and its descendant 2. Draw an arrow inside of a shape to another shape contained within the bounds of the big shape 3. Vis versa 4. Vis versa - [x] Unit Tests ### Release Notes - Improves the logic about when to draw "precise" arrows between the center of bound shapes.
2023-12-01 21:34:12 +00:00
getBoundShapeRelationships,
} from './shared'
2023-04-25 11:01:25 +00:00
import { getStraightArrowInfo } from './straight-arrow'
export function getCurvedArrowInfo(
editor: Editor,
shape: TLArrowShape,
extraBend = 0
): TLArrowInfo {
2023-04-25 11:01:25 +00:00
const { arrowheadEnd, arrowheadStart } = shape.props
const bend = shape.props.bend + extraBend
if (Math.abs(bend) > Math.abs(shape.props.bend * WAY_TOO_BIG_ARROW_BEND_FACTOR)) {
return getStraightArrowInfo(editor, shape)
2023-04-25 11:01:25 +00:00
}
const terminalsInArrowSpace = getArrowTerminalsInArrowSpace(editor, shape)
2023-04-25 11:01:25 +00:00
const med = Vec.Med(terminalsInArrowSpace.start, terminalsInArrowSpace.end) // point between start and end
const distance = Vec.Sub(terminalsInArrowSpace.end, terminalsInArrowSpace.start)
// Check for divide-by-zero before we call uni()
const u = Vec.Len(distance) ? distance.uni() : Vec.From(distance) // unit vector between start and end
const middle = Vec.Add(med, u.per().mul(-bend)) // middle handle
2023-04-25 11:01:25 +00:00
const startShapeInfo = getBoundShapeInfoForTerminal(editor, shape.props.start)
const endShapeInfo = getBoundShapeInfoForTerminal(editor, shape.props.end)
2023-04-25 11:01:25 +00:00
// The positions of the body of the arrow, which may be different
// than the arrow's start / end points if the arrow is bound to shapes
const a = terminalsInArrowSpace.start.clone()
const b = terminalsInArrowSpace.end.clone()
const c = middle.clone()
if (Vec.Equals(a, b)) {
return {
isStraight: true,
start: {
handle: a,
point: a,
arrowhead: shape.props.arrowheadStart,
},
end: {
handle: b,
point: b,
arrowhead: shape.props.arrowheadEnd,
},
middle: c,
isValid: false,
length: 0,
}
}
const isClockwise = shape.props.bend < 0
const distFn = isClockwise ? clockwiseAngleDist : counterClockwiseAngleDist
2023-04-25 11:01:25 +00:00
const handleArc = getArcInfo(a, b, c)
const handle_aCA = Vec.Angle(handleArc.center, a)
const handle_aCB = Vec.Angle(handleArc.center, b)
const handle_dAB = distFn(handle_aCA, handle_aCB)
2023-04-25 11:01:25 +00:00
if (
handleArc.length === 0 ||
handleArc.size === 0 ||
!isSafeFloat(handleArc.length) ||
!isSafeFloat(handleArc.size)
) {
return getStraightArrowInfo(editor, shape)
}
const tempA = a.clone()
const tempB = b.clone()
const tempC = c.clone()
const arrowPageTransform = editor.getShapePageTransform(shape)!
2023-04-25 11:01:25 +00:00
let offsetA = 0
let offsetB = 0
[improvements] arrows x enclosing shapes x precision. (#2265) This PR makes several improvements to the behavior of arrows as they relate to precision and container relationships. - an arrow's terminals are always "true" and are never snapped to { x: .5, y: .5 } as they were previously when not precise - instead, a new `isPrecise` boolean is added to the arrow terminal - when an arrow terminal renders "imprecisely" it will be placed to the center of the bound shape - when an arrow terminal renders "precisely" it will be placed at the normalized location within the bound shape ![Kapture 2023-11-29 at 23 12 12](https://github.com/tldraw/tldraw/assets/23072548/e94e1594-75fa-4c94-86f3-7d911bf25f7f) The logic now is... - if the user has indicated precision by "pausing" while drawing the arrow, it will be precise - otherwise... - if both of an arrow's terminals are bound to the same shape, both will be precise - if a terminal is bound to a shape that contains the shape that its opposite terminal is bound to, it will be precise - if a terminal is bound to a shape that contains the shape that its opposite terminal is bound to, it will be precise - or else it will be imprecise If the spatial relationships change, the precision may change as well. Fixes https://github.com/tldraw/tldraw/issues/2204 Note: a previous version of this PR was based around ancestry but that's not actually important. ### Change Type - [x] `minor` — New feature ### Test Plan 1. Draw an arrow between a frame and its descendant 2. Draw an arrow inside of a shape to another shape contained within the bounds of the big shape 3. Vis versa 4. Vis versa - [x] Unit Tests ### Release Notes - Improves the logic about when to draw "precise" arrows between the center of bound shapes.
2023-12-01 21:34:12 +00:00
let minLength = MIN_ARROW_LENGTH
2023-04-25 11:01:25 +00:00
if (startShapeInfo && !startShapeInfo.isExact) {
const startInPageSpace = Mat.applyToPoint(arrowPageTransform, tempA)
const centerInPageSpace = Mat.applyToPoint(arrowPageTransform, handleArc.center)
const endInPageSpace = Mat.applyToPoint(arrowPageTransform, tempB)
const inverseTransform = Mat.Inverse(startShapeInfo.transform)
const startInStartShapeLocalSpace = Mat.applyToPoint(inverseTransform, startInPageSpace)
const centerInStartShapeLocalSpace = Mat.applyToPoint(inverseTransform, centerInPageSpace)
const endInStartShapeLocalSpace = Mat.applyToPoint(inverseTransform, endInPageSpace)
2023-04-25 11:01:25 +00:00
`ShapeUtil` refactor, `Editor` cleanup (#1611) This PR improves the ergonomics of `ShapeUtil` classes. ### Cached methods First, I've remove the cached methods (such as `bounds`) from the `ShapeUtil` class and lifted this to the `Editor` class. Previously, calling `ShapeUtil.getBounds` would return the un-cached bounds of a shape, while calling `ShapeUtil.bounds` would return the cached bounds of a shape. We also had `Editor.getBounds`, which would call `ShapeUtil.bounds`. It was confusing. The cached methods like `outline` were also marked with "please don't override", which suggested the architecture was just wrong. The only weirdness from this is that utils sometimes reach out to the editor for cached versions of data rather than calling their own cached methods. It's still an easier story to tell than what we had before. ### More defaults We now have three and only three `abstract` methods for a `ShapeUtil`: - `getDefaultProps` (renamed from `defaultProps`) - `getBounds`, - `component` - `indicator` Previously, we also had `getCenter` as an abstract method, though this was usually just the middle of the bounds anyway. ### Editing bounds This PR removes the concept of editingBounds. The viewport will no longer animate to editing shapes. ### Active area manager This PR also removes the active area manager, which was not being used in the way we expected it to be. ### Dpr manager This PR removes the dpr manager and uses a hook instead to update it from React. This is one less runtime browser dependency in the app, one less thing to document. ### Moving things around This PR also continues to try to organize related methods and properties in the editor. ### Change Type - [x] `major` — Breaking change ### Release Notes - [editor] renames `defaultProps` to `getDefaultProps` - [editor] removes `outline`, `outlineSegments`, `handles`, `bounds` - [editor] renames `renderBackground` to `backgroundComponent`
2023-06-19 14:01:18 +00:00
const { isClosed } = startShapeInfo
2023-04-25 11:01:25 +00:00
const fn = isClosed ? intersectCirclePolygon : intersectCirclePolyline
let point: VecLike | undefined
let intersections = fn(centerInStartShapeLocalSpace, handleArc.radius, startShapeInfo.outline)
2023-04-25 11:01:25 +00:00
if (intersections) {
const angleToStart = centerInStartShapeLocalSpace.angle(startInStartShapeLocalSpace)
const angleToEnd = centerInStartShapeLocalSpace.angle(endInStartShapeLocalSpace)
const dAB = distFn(angleToStart, angleToEnd)
// Filter out any intersections that aren't in the arc
2023-04-25 11:01:25 +00:00
intersections = intersections.filter(
(pt) => distFn(angleToStart, centerInStartShapeLocalSpace.angle(pt)) <= dAB
2023-04-25 11:01:25 +00:00
)
const targetDist = dAB * 0.25
2023-04-25 11:01:25 +00:00
intersections.sort(
isClosed
? (p0, p1) =>
Math.abs(distFn(angleToStart, centerInStartShapeLocalSpace.angle(p0)) - targetDist) <
Math.abs(distFn(angleToStart, centerInStartShapeLocalSpace.angle(p1)) - targetDist)
? -1
: 1
: (p0, p1) =>
distFn(angleToStart, centerInStartShapeLocalSpace.angle(p0)) <
distFn(angleToStart, centerInStartShapeLocalSpace.angle(p1))
? -1
: 1
2023-04-25 11:01:25 +00:00
)
point = intersections[0] ?? (isClosed ? undefined : startInStartShapeLocalSpace)
} else {
point = isClosed ? undefined : startInStartShapeLocalSpace
}
if (point) {
tempA.setTo(
editor.getPointInShapeSpace(shape, Mat.applyToPoint(startShapeInfo.transform, point))
2023-04-25 11:01:25 +00:00
)
startShapeInfo.didIntersect = true
if (arrowheadStart !== 'none') {
[improvements] arrows x enclosing shapes x precision. (#2265) This PR makes several improvements to the behavior of arrows as they relate to precision and container relationships. - an arrow's terminals are always "true" and are never snapped to { x: .5, y: .5 } as they were previously when not precise - instead, a new `isPrecise` boolean is added to the arrow terminal - when an arrow terminal renders "imprecisely" it will be placed to the center of the bound shape - when an arrow terminal renders "precisely" it will be placed at the normalized location within the bound shape ![Kapture 2023-11-29 at 23 12 12](https://github.com/tldraw/tldraw/assets/23072548/e94e1594-75fa-4c94-86f3-7d911bf25f7f) The logic now is... - if the user has indicated precision by "pausing" while drawing the arrow, it will be precise - otherwise... - if both of an arrow's terminals are bound to the same shape, both will be precise - if a terminal is bound to a shape that contains the shape that its opposite terminal is bound to, it will be precise - if a terminal is bound to a shape that contains the shape that its opposite terminal is bound to, it will be precise - or else it will be imprecise If the spatial relationships change, the precision may change as well. Fixes https://github.com/tldraw/tldraw/issues/2204 Note: a previous version of this PR was based around ancestry but that's not actually important. ### Change Type - [x] `minor` — New feature ### Test Plan 1. Draw an arrow between a frame and its descendant 2. Draw an arrow inside of a shape to another shape contained within the bounds of the big shape 3. Vis versa 4. Vis versa - [x] Unit Tests ### Release Notes - Improves the logic about when to draw "precise" arrows between the center of bound shapes.
2023-12-01 21:34:12 +00:00
const strokeOffset =
STROKE_SIZES[shape.props.size] / 2 +
('size' in startShapeInfo.shape.props
? STROKE_SIZES[startShapeInfo.shape.props.size] / 2
: 0)
[improvements] arrows x enclosing shapes x precision. (#2265) This PR makes several improvements to the behavior of arrows as they relate to precision and container relationships. - an arrow's terminals are always "true" and are never snapped to { x: .5, y: .5 } as they were previously when not precise - instead, a new `isPrecise` boolean is added to the arrow terminal - when an arrow terminal renders "imprecisely" it will be placed to the center of the bound shape - when an arrow terminal renders "precisely" it will be placed at the normalized location within the bound shape ![Kapture 2023-11-29 at 23 12 12](https://github.com/tldraw/tldraw/assets/23072548/e94e1594-75fa-4c94-86f3-7d911bf25f7f) The logic now is... - if the user has indicated precision by "pausing" while drawing the arrow, it will be precise - otherwise... - if both of an arrow's terminals are bound to the same shape, both will be precise - if a terminal is bound to a shape that contains the shape that its opposite terminal is bound to, it will be precise - if a terminal is bound to a shape that contains the shape that its opposite terminal is bound to, it will be precise - or else it will be imprecise If the spatial relationships change, the precision may change as well. Fixes https://github.com/tldraw/tldraw/issues/2204 Note: a previous version of this PR was based around ancestry but that's not actually important. ### Change Type - [x] `minor` — New feature ### Test Plan 1. Draw an arrow between a frame and its descendant 2. Draw an arrow inside of a shape to another shape contained within the bounds of the big shape 3. Vis versa 4. Vis versa - [x] Unit Tests ### Release Notes - Improves the logic about when to draw "precise" arrows between the center of bound shapes.
2023-12-01 21:34:12 +00:00
offsetA = BOUND_ARROW_OFFSET + strokeOffset
minLength += strokeOffset
2023-04-25 11:01:25 +00:00
}
}
}
if (endShapeInfo && !endShapeInfo.isExact) {
// get points in shape's coordinates?
const startInPageSpace = Mat.applyToPoint(arrowPageTransform, tempA)
const endInPageSpace = Mat.applyToPoint(arrowPageTransform, tempB)
const centerInPageSpace = Mat.applyToPoint(arrowPageTransform, handleArc.center)
const inverseTransform = Mat.Inverse(endShapeInfo.transform)
const startInEndShapeLocalSpace = Mat.applyToPoint(inverseTransform, startInPageSpace)
const centerInEndShapeLocalSpace = Mat.applyToPoint(inverseTransform, centerInPageSpace)
const endInEndShapeLocalSpace = Mat.applyToPoint(inverseTransform, endInPageSpace)
2023-04-25 11:01:25 +00:00
`ShapeUtil` refactor, `Editor` cleanup (#1611) This PR improves the ergonomics of `ShapeUtil` classes. ### Cached methods First, I've remove the cached methods (such as `bounds`) from the `ShapeUtil` class and lifted this to the `Editor` class. Previously, calling `ShapeUtil.getBounds` would return the un-cached bounds of a shape, while calling `ShapeUtil.bounds` would return the cached bounds of a shape. We also had `Editor.getBounds`, which would call `ShapeUtil.bounds`. It was confusing. The cached methods like `outline` were also marked with "please don't override", which suggested the architecture was just wrong. The only weirdness from this is that utils sometimes reach out to the editor for cached versions of data rather than calling their own cached methods. It's still an easier story to tell than what we had before. ### More defaults We now have three and only three `abstract` methods for a `ShapeUtil`: - `getDefaultProps` (renamed from `defaultProps`) - `getBounds`, - `component` - `indicator` Previously, we also had `getCenter` as an abstract method, though this was usually just the middle of the bounds anyway. ### Editing bounds This PR removes the concept of editingBounds. The viewport will no longer animate to editing shapes. ### Active area manager This PR also removes the active area manager, which was not being used in the way we expected it to be. ### Dpr manager This PR removes the dpr manager and uses a hook instead to update it from React. This is one less runtime browser dependency in the app, one less thing to document. ### Moving things around This PR also continues to try to organize related methods and properties in the editor. ### Change Type - [x] `major` — Breaking change ### Release Notes - [editor] renames `defaultProps` to `getDefaultProps` - [editor] removes `outline`, `outlineSegments`, `handles`, `bounds` - [editor] renames `renderBackground` to `backgroundComponent`
2023-06-19 14:01:18 +00:00
const isClosed = endShapeInfo.isClosed
2023-04-25 11:01:25 +00:00
const fn = isClosed ? intersectCirclePolygon : intersectCirclePolyline
let point: VecLike | undefined
let intersections = fn(centerInEndShapeLocalSpace, handleArc.radius, endShapeInfo.outline)
2023-04-25 11:01:25 +00:00
if (intersections) {
const angleToStart = centerInEndShapeLocalSpace.angle(startInEndShapeLocalSpace)
const angleToEnd = centerInEndShapeLocalSpace.angle(endInEndShapeLocalSpace)
const dAB = distFn(angleToStart, angleToEnd)
const targetDist = dAB * 0.75
// or simplified...
2023-04-25 11:01:25 +00:00
intersections = intersections.filter(
(pt) => distFn(angleToStart, centerInEndShapeLocalSpace.angle(pt)) <= dAB
2023-04-25 11:01:25 +00:00
)
intersections.sort(
isClosed
? (p0, p1) =>
Math.abs(distFn(angleToStart, centerInEndShapeLocalSpace.angle(p0)) - targetDist) <
Math.abs(distFn(angleToStart, centerInEndShapeLocalSpace.angle(p1)) - targetDist)
? -1
: 1
: (p0, p1) =>
distFn(angleToStart, centerInEndShapeLocalSpace.angle(p0)) <
distFn(angleToStart, centerInEndShapeLocalSpace.angle(p1))
? -1
: 1
2023-04-25 11:01:25 +00:00
)
if (intersections[0]) {
point = intersections[0]
} else {
point = isClosed ? undefined : endInEndShapeLocalSpace
}
2023-04-25 11:01:25 +00:00
} else {
point = isClosed ? undefined : endInEndShapeLocalSpace
}
if (point) {
// Set b to target local point -> page point -> shape local point
tempB.setTo(
editor.getPointInShapeSpace(shape, Mat.applyToPoint(endShapeInfo.transform, point))
)
2023-04-25 11:01:25 +00:00
endShapeInfo.didIntersect = true
if (arrowheadEnd !== 'none') {
[improvements] arrows x enclosing shapes x precision. (#2265) This PR makes several improvements to the behavior of arrows as they relate to precision and container relationships. - an arrow's terminals are always "true" and are never snapped to { x: .5, y: .5 } as they were previously when not precise - instead, a new `isPrecise` boolean is added to the arrow terminal - when an arrow terminal renders "imprecisely" it will be placed to the center of the bound shape - when an arrow terminal renders "precisely" it will be placed at the normalized location within the bound shape ![Kapture 2023-11-29 at 23 12 12](https://github.com/tldraw/tldraw/assets/23072548/e94e1594-75fa-4c94-86f3-7d911bf25f7f) The logic now is... - if the user has indicated precision by "pausing" while drawing the arrow, it will be precise - otherwise... - if both of an arrow's terminals are bound to the same shape, both will be precise - if a terminal is bound to a shape that contains the shape that its opposite terminal is bound to, it will be precise - if a terminal is bound to a shape that contains the shape that its opposite terminal is bound to, it will be precise - or else it will be imprecise If the spatial relationships change, the precision may change as well. Fixes https://github.com/tldraw/tldraw/issues/2204 Note: a previous version of this PR was based around ancestry but that's not actually important. ### Change Type - [x] `minor` — New feature ### Test Plan 1. Draw an arrow between a frame and its descendant 2. Draw an arrow inside of a shape to another shape contained within the bounds of the big shape 3. Vis versa 4. Vis versa - [x] Unit Tests ### Release Notes - Improves the logic about when to draw "precise" arrows between the center of bound shapes.
2023-12-01 21:34:12 +00:00
const strokeOffset =
STROKE_SIZES[shape.props.size] / 2 +
('size' in endShapeInfo.shape.props ? STROKE_SIZES[endShapeInfo.shape.props.size] / 2 : 0)
[improvements] arrows x enclosing shapes x precision. (#2265) This PR makes several improvements to the behavior of arrows as they relate to precision and container relationships. - an arrow's terminals are always "true" and are never snapped to { x: .5, y: .5 } as they were previously when not precise - instead, a new `isPrecise` boolean is added to the arrow terminal - when an arrow terminal renders "imprecisely" it will be placed to the center of the bound shape - when an arrow terminal renders "precisely" it will be placed at the normalized location within the bound shape ![Kapture 2023-11-29 at 23 12 12](https://github.com/tldraw/tldraw/assets/23072548/e94e1594-75fa-4c94-86f3-7d911bf25f7f) The logic now is... - if the user has indicated precision by "pausing" while drawing the arrow, it will be precise - otherwise... - if both of an arrow's terminals are bound to the same shape, both will be precise - if a terminal is bound to a shape that contains the shape that its opposite terminal is bound to, it will be precise - if a terminal is bound to a shape that contains the shape that its opposite terminal is bound to, it will be precise - or else it will be imprecise If the spatial relationships change, the precision may change as well. Fixes https://github.com/tldraw/tldraw/issues/2204 Note: a previous version of this PR was based around ancestry but that's not actually important. ### Change Type - [x] `minor` — New feature ### Test Plan 1. Draw an arrow between a frame and its descendant 2. Draw an arrow inside of a shape to another shape contained within the bounds of the big shape 3. Vis versa 4. Vis versa - [x] Unit Tests ### Release Notes - Improves the logic about when to draw "precise" arrows between the center of bound shapes.
2023-12-01 21:34:12 +00:00
offsetB = BOUND_ARROW_OFFSET + strokeOffset
minLength += strokeOffset
2023-04-25 11:01:25 +00:00
}
}
}
// Apply arrowhead offsets
let aCA = Vec.Angle(handleArc.center, tempA) // angle center -> a
let aCB = Vec.Angle(handleArc.center, tempB) // angle center -> b
let dAB = distFn(aCA, aCB) // angle distance between a and b
let lAB = dAB * handleArc.radius // length of arc between a and b
// Try the offsets first, then check whether the distance between the points is too small;
// if it is, flip the offsets and expand them. We need to do this using temporary points
// so that we can apply them both in a balanced way.
const tA = tempA.clone()
const tB = tempB.clone()
if (offsetA !== 0) {
const n = (offsetA / lAB) * (isClockwise ? 1 : -1)
const u = Vec.FromAngle(aCA + dAB * n)
tA.setTo(handleArc.center).add(u.mul(handleArc.radius))
}
if (offsetB !== 0) {
const n = (offsetB / lAB) * (isClockwise ? -1 : 1)
const u = Vec.FromAngle(aCB + dAB * n)
tB.setTo(handleArc.center).add(u.mul(handleArc.radius))
}
if (Vec.DistMin(tA, tB, minLength)) {
if (offsetA !== 0 && offsetB !== 0) {
offsetA *= -1.5
offsetB *= -1.5
} else if (offsetA !== 0) {
offsetA *= -2
} else if (offsetB !== 0) {
offsetB *= -2
} else {
[improvements] arrows x enclosing shapes x precision. (#2265) This PR makes several improvements to the behavior of arrows as they relate to precision and container relationships. - an arrow's terminals are always "true" and are never snapped to { x: .5, y: .5 } as they were previously when not precise - instead, a new `isPrecise` boolean is added to the arrow terminal - when an arrow terminal renders "imprecisely" it will be placed to the center of the bound shape - when an arrow terminal renders "precisely" it will be placed at the normalized location within the bound shape ![Kapture 2023-11-29 at 23 12 12](https://github.com/tldraw/tldraw/assets/23072548/e94e1594-75fa-4c94-86f3-7d911bf25f7f) The logic now is... - if the user has indicated precision by "pausing" while drawing the arrow, it will be precise - otherwise... - if both of an arrow's terminals are bound to the same shape, both will be precise - if a terminal is bound to a shape that contains the shape that its opposite terminal is bound to, it will be precise - if a terminal is bound to a shape that contains the shape that its opposite terminal is bound to, it will be precise - or else it will be imprecise If the spatial relationships change, the precision may change as well. Fixes https://github.com/tldraw/tldraw/issues/2204 Note: a previous version of this PR was based around ancestry but that's not actually important. ### Change Type - [x] `minor` — New feature ### Test Plan 1. Draw an arrow between a frame and its descendant 2. Draw an arrow inside of a shape to another shape contained within the bounds of the big shape 3. Vis versa 4. Vis versa - [x] Unit Tests ### Release Notes - Improves the logic about when to draw "precise" arrows between the center of bound shapes.
2023-12-01 21:34:12 +00:00
// noop
}
2023-04-25 11:01:25 +00:00
}
if (offsetA !== 0) {
const n = (offsetA / lAB) * (isClockwise ? 1 : -1)
const u = Vec.FromAngle(aCA + dAB * n)
tempA.setTo(handleArc.center).add(u.mul(handleArc.radius))
}
if (offsetB !== 0) {
const n = (offsetB / lAB) * (isClockwise ? -1 : 1)
const u = Vec.FromAngle(aCB + dAB * n)
tempB.setTo(handleArc.center).add(u.mul(handleArc.radius))
}
// Did we miss intersections? This happens when we have overlapping shapes.
if (startShapeInfo && endShapeInfo && !startShapeInfo.isExact && !endShapeInfo.isExact) {
aCA = Vec.Angle(handleArc.center, tempA) // angle center -> a
aCB = Vec.Angle(handleArc.center, tempB) // angle center -> b
dAB = distFn(aCA, aCB) // angle distance between a and b
lAB = dAB * handleArc.radius // length of arc between a and b
[improvements] arrows x enclosing shapes x precision. (#2265) This PR makes several improvements to the behavior of arrows as they relate to precision and container relationships. - an arrow's terminals are always "true" and are never snapped to { x: .5, y: .5 } as they were previously when not precise - instead, a new `isPrecise` boolean is added to the arrow terminal - when an arrow terminal renders "imprecisely" it will be placed to the center of the bound shape - when an arrow terminal renders "precisely" it will be placed at the normalized location within the bound shape ![Kapture 2023-11-29 at 23 12 12](https://github.com/tldraw/tldraw/assets/23072548/e94e1594-75fa-4c94-86f3-7d911bf25f7f) The logic now is... - if the user has indicated precision by "pausing" while drawing the arrow, it will be precise - otherwise... - if both of an arrow's terminals are bound to the same shape, both will be precise - if a terminal is bound to a shape that contains the shape that its opposite terminal is bound to, it will be precise - if a terminal is bound to a shape that contains the shape that its opposite terminal is bound to, it will be precise - or else it will be imprecise If the spatial relationships change, the precision may change as well. Fixes https://github.com/tldraw/tldraw/issues/2204 Note: a previous version of this PR was based around ancestry but that's not actually important. ### Change Type - [x] `minor` — New feature ### Test Plan 1. Draw an arrow between a frame and its descendant 2. Draw an arrow inside of a shape to another shape contained within the bounds of the big shape 3. Vis versa 4. Vis versa - [x] Unit Tests ### Release Notes - Improves the logic about when to draw "precise" arrows between the center of bound shapes.
2023-12-01 21:34:12 +00:00
const relationship = getBoundShapeRelationships(
editor,
startShapeInfo.shape.id,
endShapeInfo.shape.id
)
if (relationship === 'double-bound' && lAB < 30) {
tempA.setTo(a)
tempB.setTo(b)
tempC.setTo(c)
} else if (relationship === 'safe') {
if (startShapeInfo && !startShapeInfo.didIntersect) {
tempA.setTo(a)
}
if (
(endShapeInfo && !endShapeInfo.didIntersect) ||
distFn(handle_aCA, aCA) > distFn(handle_aCA, aCB)
) {
const n = Math.min(0.9, MIN_ARROW_LENGTH / lAB) * (isClockwise ? 1 : -1)
const u = Vec.FromAngle(aCA + dAB * n)
tempB.setTo(handleArc.center).add(u.mul(handleArc.radius))
}
2023-04-25 11:01:25 +00:00
}
}
placeCenterHandle(
handleArc.center,
handleArc.radius,
tempA,
tempB,
tempC,
handle_dAB,
isClockwise
2023-04-25 11:01:25 +00:00
)
if (tempA.equals(tempB)) {
tempA.setTo(tempC.clone().addXY(1, 1))
tempB.setTo(tempC.clone().subXY(1, 1))
}
2023-04-25 11:01:25 +00:00
a.setTo(tempA)
b.setTo(tempB)
c.setTo(tempC)
2023-04-25 11:01:25 +00:00
const bodyArc = getArcInfo(a, b, c)
return {
isStraight: false,
start: {
point: a,
handle: terminalsInArrowSpace.start,
arrowhead: shape.props.arrowheadStart,
},
end: {
point: b,
handle: terminalsInArrowSpace.end,
arrowhead: shape.props.arrowheadEnd,
},
middle: c,
handleArc,
bodyArc,
isValid: bodyArc.length !== 0 && isFinite(bodyArc.center.x) && isFinite(bodyArc.center.y),
}
}
/**
* Get info about an arc formed by three points.
*
* @param a - The start of the arc
* @param b - The end of the arc
* @param c - A point on the arc
*/
function getArcInfo(a: VecLike, b: VecLike, c: VecLike): TLArcInfo {
2023-04-25 11:01:25 +00:00
// find a circle from the three points
const u = -2 * (a.x * (b.y - c.y) - a.y * (b.x - c.x) + b.x * c.y - c.x * b.y)
const center = {
x:
((a.x * a.x + a.y * a.y) * (c.y - b.y) +
(b.x * b.x + b.y * b.y) * (a.y - c.y) +
(c.x * c.x + c.y * c.y) * (b.y - a.y)) /
u,
y:
((a.x * a.x + a.y * a.y) * (b.x - c.x) +
(b.x * b.x + b.y * b.y) * (c.x - a.x) +
(c.x * c.x + c.y * c.y) * (a.x - b.x)) /
u,
}
const radius = Vec.Dist(center, a)
2023-04-25 11:01:25 +00:00
// Whether to draw the arc clockwise or counter-clockwise (are the points clockwise?)
const sweepFlag = +Vec.Clockwise(a, c, b)
2023-04-25 11:01:25 +00:00
// The base angle of the arc in radians
perf: calculate hypoteneuse manually instead of using hypot (#3468) Something was bothering me a bit with the discussion around sqrt's being slow. Looks like `Math.hypot` has a performance cost associated with it. Looking at the Chromium source code: https://chromium.googlesource.com/v8/v8/+/4.3.21/src/math.js?autodive=0%2F%2F#19 and https://source.chromium.org/chromium/chromium/src/+/main:v8/src/builtins/math.tq;l=36?q=math&sq=&ss=chromium%2Fchromium%2Fsrc:v8%2Fsrc%2F it looks like maybe we'd be avoiding the multiple arguments that can be passed into Math.hypot which is maybe the source of the perf hit. Also, interestingly in `math.tq` you can see it doing this funky sqrt calculation: `Float64Sqrt((a / max) * (a / max) + (b / max) * (b / max)) * max` - I think that possibly is trying to avoid some overflow in some cases with bigger numbers, but also possibly with a perf hit. [edit]: OK, actually on Firefox, doing sqrt seems slower - but digging more into this, it looks like doing `** 0.5` instead of `sqrt` is much faster. More related articles: - https://stackoverflow.com/questions/71898044/why-is-math-hypot-so-slow - https://stackoverflow.com/questions/3764978/why-hypot-function-is-so-slow - https://www.reddit.com/r/javascript/comments/wk3e57/askjs_why_mathsqrt_is_so_slow_in_firefox/ [edit again!] looks like this is being fixed in the latest Chrome! https://blog.seokho.dev/development/2024/03/18/V8-optimize-MathHypot.html ``` ┌─────────┬───────┬─────────┬─────────┬─────────┬────────┐ │ (index) │ Cold │ Slowest │ Fastest │ Average │ Total │ ├─────────┼───────┼─────────┼─────────┼─────────┼────────┤ │ old │ 13.39 │ 10.07 │ 9.69 │ 9.98 │ 998.57 │ │ sqrt │ 8.19 │ 6.66 │ 6.61 │ 6.67 │ 667.6 │ │ pow 0.5 │ 1.89 │ 0.28 │ 0.28 │ 0.3 │ 29.79 │ │ new │ 1.64 │ 0.28 │ 0.28 │ 0.29 │ 28.95 │ └─────────┴───────┴─────────┴─────────┴─────────┴────────┘ ``` ### Change Type <!-- ❗ Please select a 'Scope' label ❗️ --> - [x] `sdk` — Changes the tldraw SDK - [ ] `dotcom` — Changes the tldraw.com web app - [ ] `docs` — Changes to the documentation, examples, or templates. - [ ] `vs code` — Changes to the vscode plugin - [ ] `internal` — Does not affect user-facing stuff <!-- ❗ Please select a 'Type' label ❗️ --> - [ ] `bugfix` — Bug fix - [ ] `feature` — New feature - [x] `improvement` — Improving existing features - [ ] `chore` — Updating dependencies, other boring stuff - [ ] `galaxy brain` — Architectural changes - [ ] `tests` — Changes to any test code - [ ] `tools` — Changes to infrastructure, CI, internal scripts, debugging tools, etc. - [ ] `dunno` — I don't know
2024-04-15 18:45:30 +00:00
const ab = ((a.y - b.y) ** 2 + (a.x - b.x) ** 2) ** 0.5
const bc = ((b.y - c.y) ** 2 + (b.x - c.x) ** 2) ** 0.5
const ca = ((c.y - a.y) ** 2 + (c.x - a.x) ** 2) ** 0.5
2023-04-25 11:01:25 +00:00
const theta = Math.acos((bc * bc + ca * ca - ab * ab) / (2 * bc * ca)) * 2
// Whether to draw the long arc or short arc
const largeArcFlag = +(PI > theta)
// The size of the arc to draw in radians
const size = (PI2 - theta) * (sweepFlag ? 1 : -1)
// The length of the arc to draw in distance units
const length = size * radius
return {
center,
radius,
size,
length,
largeArcFlag,
sweepFlag,
}
}
function placeCenterHandle(
center: VecLike,
radius: number,
tempA: Vec,
tempB: Vec,
tempC: Vec,
originalArcLength: number,
isClockwise: boolean
) {
const aCA = Vec.Angle(center, tempA) // angle center -> a
const aCB = Vec.Angle(center, tempB) // angle center -> b
let dAB = clockwiseAngleDist(aCA, aCB) // angle distance between a and b
if (!isClockwise) dAB = PI2 - dAB
const n = 0.5 * (isClockwise ? 1 : -1)
const u = Vec.FromAngle(aCA + dAB * n)
tempC.setTo(center).add(u.mul(radius))
if (dAB > originalArcLength) {
tempC.rotWith(center, PI)
const t = tempB.clone()
tempB.setTo(tempA)
tempA.setTo(t)
}
}