diff --git a/packages/element/src/elbowArrowRouting.ts b/packages/element/src/elbowArrowRouting.ts index 1f92776204..6947bdbda5 100644 --- a/packages/element/src/elbowArrowRouting.ts +++ b/packages/element/src/elbowArrowRouting.ts @@ -2,22 +2,41 @@ * Elbow arrow routing: given an arrow's endpoints and the elements they are * bound to (or hovering over), finds the orthogonal route between them. * - * The route is the "simple" one with one or two corners when that fits - * (see {@link getSimpleRoute}), or else found by A* on a sparse grid built - * from the bounding boxes around the endpoints (see {@link getGridRoute}). + * The route is the cheapest path on a sparse orthogonal grid (much like the + * orthogonal visibility graph of Wybrow, Marriott and Stuckey, "Orthogonal + * Connector Routing", GD 2009; see {@link buildGrid} and + * {@link cheapestPath}), where the cost of a path is its length, a fixed cost + * per bend, a cost for running close to, or through, the elements it + * connects (see {@link CLEARANCE_COST}), and for turning back too tightly + * (see {@link SHORT_HAIRPIN_COST}). + * + * Its segments run on the grid's lines, which are where segments belong (a + * padding away from the elements, halfway between them, through the + * endpoints...), so they're placed exactly there, and move along with the + * elements, rather than settling wherever some cost is least, which where + * the costs are about flat, small differences can change from one frame to + * the next. + * + * The elements are soft obstacles (much like yFiles' node crossing penalty) + * rather than hard ones, and every cost changes continuously as the elements + * move, so the route only changes its shape where another shape becomes as + * cheap. The one exception is two elements overlapping, which here means an + * endpoint within the padding around the element the other end is bound to: + * the route then doesn't avoid either of them at all (see {@link findRoute}). + * + * The route only depends on the endpoints, their headings and elements, and + * the arrowheads (never on where the route was before), so the same arrow + * always gets the same route. * * Editing an existing route (moving and fixing segments, dragging endpoints of * an arrow with fixed segments) lives in `elbowArrow.ts`. */ import { - pointDistance, + clamp, pointFrom, - pointScaleFromOrigin, pointTranslate, vector, - vectorCross, - vectorFromPoint, type GlobalPoint, type LocalPoint, } from "@excalidraw/math"; @@ -31,7 +50,6 @@ import { getHeadingForElbowArrowSnap, getGlobalFixedPointForBindableElement, getBindingGap, - BASE_BINDING_GAP, } from "./binding"; import { distanceToElement } from "./distance"; import { @@ -42,15 +60,9 @@ import { HEADING_RIGHT, HEADING_UP, headingIsHorizontal, - vectorToHeading, } from "./heading"; import { isBindableElement } from "./typeChecks"; -import { - aabbForElement, - doBoundsIntersect, - getArrowheadSize, - pointInsideBounds, -} from "./bounds"; +import { aabbForElement, getArrowheadSize } from "./bounds"; import { getHoveredElementForBinding } from "./collision"; import { ELBOW_ARROW_CORNER_RADIUS } from "./shape"; @@ -70,6 +82,88 @@ export const BASE_PADDING = 40; /** Segments shorter than this are considered degenerate and get removed */ export const DEDUP_THRESHOLD = 1; +// ----------------------------------------------------------------------------- +// Routing costs, in px of route length +// ----------------------------------------------------------------------------- + +/** Each bend costs as much as this much more length */ +const BEND_COST = 4 * BASE_PADDING; + +/** + * The cost per px of route running within the padding around an element: it + * grows from nothing at the padding's edge to this at the element's (see + * {@link closeness}). Between two elements closer than twice the padding, the + * padding shrinks to half the distance between them, so a route through the + * gap runs halfway between them at no cost (see {@link clearanceCost}). + */ +const CLEARANCE_COST = 3; + +/** + * How the clearance cost grows from the padding's edge (0) to the element's + * (1): half linearly, so with room to spare, a segment of any length stays + * out of the padding (moving it in costs more than the length it saves), and + * half quadratically, so where two elements' paddings overlap, a segment + * between them settles halfway + */ +const closeness = (depth: number) => (depth + depth * depth) / 2; + +/** + * The cost per px a first or last leg is shorter than it needs to be: so + * steep that it's all but a limit, as a leg too short for its corner or + * arrowhead looks broken however much shorter it is + */ +const SHORT_LEG_COST = 200; + +/** + * The additional cost per px of route running inside an element (and the + * binding gap around it), ramped in over {@link CROSSING_RAMP} px past its + * edge (to keep costs continuous) + */ +const CROSSING_COST = 10; +const CROSSING_RAMP = 2; + +/** + * The cost per px a leg on an element is shorter than the padding, so it + * gets the room it looks best with if there's any to spare (nothing else + * makes it longer, where the elements aren't avoided): never as much as a + * bend, and more than the route gets longer by for it, where it doubles back + * past the leg. A leg with an arrowhead costs twice that, so where there's no + * room for both, the arrowhead gets it. + */ +const PADDING_LEG_COST = 4; + +/** + * The cost per px the segments either side of a hairpin (two corners turning + * the same way, where the route turns back) are closer together than they + * need to be (see {@link minHairpin}), which looks like the route folding + * back onto itself: between two elements it avoids, so steep that it's all + * but a limit, as it can always go around them instead. Otherwise, short of + * making it go much further around: in all, less than the two more bends + * going around would take. + */ +const SHORT_HAIRPIN_COST = SHORT_LEG_COST; +const SHORT_FORCED_HAIRPIN_COST = 16; + +/** + * How much more a left (counterclockwise) turn costs than a right one: only + * to settle ties between route shapes (like going around either side of two + * elements of the same size) the same way throughout, rather than by whichever + * small differences in cost there are between them flipping back and forth + */ +const TURN_BIAS = 0.5; + +/** + * A tiny cost per segment of the route on the grid lines other than the ones + * halfway between elements and through the endpoints, only to break ties + * between otherwise equally good routes in the same way every time. (Per + * segment, rather than per px, so it never weighs against length.) + */ +const LINE_COSTS = { preferred: 0, padding: 1e-3, step: 2e-3 } as const; + +// ----------------------------------------------------------------------------- +// Types +// ----------------------------------------------------------------------------- + /** What routing needs to know about the arrow */ export type ElbowArrowState = { x: number; @@ -87,7 +181,7 @@ export type ElbowArrowRoutingOptions = { isMidpointSnappingEnabled?: boolean; }; -/** The endpoints of an elbow arrow and the space around them, for routing */ +/** The endpoints of an elbow arrow, for routing */ export type ElbowArrowData = { /** The endpoints in scene coordinates, snapped to their elements if bound */ startGlobalPoint: GlobalPoint; @@ -98,43 +192,8 @@ export type ElbowArrowData = { /** The elements the endpoints are bound to, or hover over while dragging */ hoveredStartElement: ExcalidrawBindableElement | null; hoveredEndElement: ExcalidrawBindableElement | null; - /** - * The boxes the route has to go around: the space claimed by each endpoint - * (its element and padding), grown until the two boxes touch - */ - dynamicAABBs: Bounds[]; - /** The bounds of both endpoints' boxes before they were grown */ - commonBounds: Bounds; - /** - * Where the route leaves the start's box (and enters the end's), straight - * out from the endpoint along its heading - */ - startDonglePosition: GlobalPoint; - endDonglePosition: GlobalPoint; }; -type GridAddress = [col: number, row: number] & { _brand: "gridaddress" }; - -/** A* node at a grid line intersection */ -type Node = { - f: number; - g: number; - h: number; - closed: boolean; - visited: boolean; - parent: Node | null; - pos: GlobalPoint; - addr: GridAddress; -}; - -type Grid = { - row: number; - col: number; - data: Node[]; -}; - -type BoundsOffset = [up: number, right: number, down: number, left: number]; - // ----------------------------------------------------------------------------- // Endpoint analysis // ----------------------------------------------------------------------------- @@ -151,12 +210,9 @@ export const getBindableElementForId = ( return null; }; -/** An arrowhead needs a bigger gap from the element than a bare line end */ -const arrowheadGapFactor = (arrowhead: Arrowhead | null) => (arrowhead ? 6 : 2); - /** * Works out where the arrow's (moved) endpoints are, which elements they - * connect, which way they face, and the boxes the route goes around. + * connect, and which way they face. * * While dragging, the endpoints bind to (and snap onto) the elements under * them; otherwise they stay on the elements of the arrow's bindings. @@ -234,131 +290,23 @@ export const getElbowArrowData = ( options, ); - const startHeading = getBindPointHeading( - startGlobalPoint, - endGlobalPoint, - hoveredStartElement, - origStartGlobalPoint, - elementsMap, - zoom, - ); - const endHeading = getBindPointHeading( - endGlobalPoint, - startGlobalPoint, - hoveredEndElement, - origEndGlobalPoint, - elementsMap, - zoom, - ); - - const startPointBounds = pointBounds(startGlobalPoint); - const endPointBounds = pointBounds(endGlobalPoint); - - // The element and the gap the arrow keeps from it, wider on the side the - // arrow leaves from if there's an arrowhead to fit - const elementBounds = ( - element: ExcalidrawBindableElement | null, - heading: Heading, - arrowhead: Arrowhead | null, - fallback: Bounds, - ) => - element - ? aabbForElement( - element, - elementsMap, - offsetFromHeading( - heading, - getBindingGap(element) * arrowheadGapFactor(arrowhead), - 1, - ), - ) - : fallback; - const startElementBounds = elementBounds( - hoveredStartElement, - startHeading, - arrow.startArrowhead, - startPointBounds, - ); - const endElementBounds = elementBounds( - hoveredEndElement, - endHeading, - arrow.endArrowhead, - endPointBounds, - ); - - // If either endpoint is within the padding of the other's element, there's - // no room to route around the elements, so route between the bare points - const paddedElementBounds = ( - element: ExcalidrawBindableElement | null, - heading: Heading, - fallback: Bounds, - ) => - element - ? aabbForElement( - element, - elementsMap, - offsetFromHeading(heading, BASE_PADDING, BASE_PADDING), - ) - : fallback; - const boundsOverlap = - pointInsideBounds( - startGlobalPoint, - paddedElementBounds(hoveredEndElement, endHeading, endPointBounds), - ) || - pointInsideBounds( - endGlobalPoint, - paddedElementBounds(hoveredStartElement, startHeading, startPointBounds), - ); - - const [startBounds, endBounds] = boundsOverlap - ? [startPointBounds, endPointBounds] - : [startElementBounds, endElementBounds]; - const commonBounds = commonAABB([startBounds, endBounds]); - - const isBound = !!hoveredStartElement || !!hoveredEndElement; - const boundsPadding = (heading: Heading, arrowhead: Arrowhead | null) => { - if (boundsOverlap) { - return offsetFromHeading(heading, isBound ? BASE_PADDING : 0, 0); - } - - return offsetFromHeading( - heading, - isBound - ? BASE_PADDING - BASE_BINDING_GAP * arrowheadGapFactor(arrowhead) - : 0, - BASE_PADDING, - ); - }; - const dynamicAABBs = generateDynamicAABBs( - startBounds, - endBounds, - commonBounds, - boundsPadding(startHeading, arrow.startArrowhead), - boundsPadding(endHeading, arrow.endArrowhead), - boundsOverlap, - hoveredStartElement - ? aabbForElement(hoveredStartElement, elementsMap) - : null, - hoveredEndElement ? aabbForElement(hoveredEndElement, elementsMap) : null, - ); - return { - dynamicAABBs, - startDonglePosition: getDonglePosition( - dynamicAABBs[0], - startHeading, - startGlobalPoint, - ), startGlobalPoint, - startHeading, - endDonglePosition: getDonglePosition( - dynamicAABBs[1], - endHeading, + startHeading: getBindPointHeading( + startGlobalPoint, endGlobalPoint, + hoveredStartElement, + elementsMap, + zoom, ), endGlobalPoint, - endHeading, - commonBounds, + endHeading: getBindPointHeading( + endGlobalPoint, + startGlobalPoint, + hoveredEndElement, + elementsMap, + zoom, + ), hoveredStartElement, hoveredEndElement, }; @@ -403,11 +351,16 @@ const getEndpointGlobalPoint = ( ); }; +/** + * The way the arrow leaves (or enters) an endpoint: out of the side of its + * element it's on, or, if it's inside the element, away from its center. + * (Where the endpoint is, rather than the pointer dragging it: snapped onto + * the outline from inside, it's on the side it's on, as it is once bound.) + */ const getBindPointHeading = ( p: GlobalPoint, otherPoint: GlobalPoint, hoveredElement: ExcalidrawBindableElement | null, - origPoint: GlobalPoint, elementsMap: ElementsMap, zoom: AppState["zoom"], ): Heading => { @@ -427,420 +380,874 @@ const getBindPointHeading = ( otherPoint, hoveredElement, aabb, - origPoint, + p, elementsMap, zoom, ); }; -const pointBounds = (p: GlobalPoint): Bounds => [ - p[0] - 2, - p[1] - 2, - p[0] + 2, - p[1] + 2, -]; - -/** - * Bounds offsets with `head` on the side the heading points to and `side` - * on the others - */ -const offsetFromHeading = ( - heading: Heading, - head: number, - side: number, -): BoundsOffset => { - switch (heading) { - case HEADING_UP: - return [head, side, side, side]; - case HEADING_RIGHT: - return [side, head, side, side]; - case HEADING_DOWN: - return [side, side, head, side]; - } - - return [side, side, side, head]; -}; - -/** The point where the ray from `p` along `heading` leaves `bounds` */ -const getDonglePosition = ( - bounds: Bounds, - heading: Heading, - p: GlobalPoint, -): GlobalPoint => { - switch (heading) { - case HEADING_UP: - return pointFrom(p[0], bounds[1]); - case HEADING_RIGHT: - return pointFrom(bounds[2], p[1]); - case HEADING_DOWN: - return pointFrom(p[0], bounds[3]); - } - - return pointFrom(bounds[0], p[1]); -}; - -const commonAABB = (aabbs: Bounds[]): Bounds => [ - Math.min(...aabbs.map((aabb) => aabb[0])), - Math.min(...aabbs.map((aabb) => aabb[1])), - Math.max(...aabbs.map((aabb) => aabb[2])), - Math.max(...aabbs.map((aabb) => aabb[3])), -]; - -/** - * Grows the boxes `a` (around the start) and `b` (around the end) by their - * paddings, and towards each other until they touch halfway between their - * elements, so the route between them stays clear of both. - * - * When the grown boxes would overlap on both axes (the elements are - * diagonal to each other and close), they're split along whichever axis - * keeps the route closest to the end (the "side hack"), unless disabled. - */ -const generateDynamicAABBs = ( - a: Bounds, - b: Bounds, - common: Bounds, - startPadding: BoundsOffset, - endPadding: BoundsOffset, - disableSideHack: boolean, - startElementBounds: Bounds | null, - endElementBounds: Bounds | null, -): Bounds[] => { - const startEl = startElementBounds ?? a; - const endEl = endElementBounds ?? b; - const first = growBounds(a, b, startEl, endEl, common, startPadding); - const second = growBounds(b, a, endEl, startEl, common, endPadding); - - // NOTE: the expressions are kept as they are, as the comparison is - // sensitive to floating point rounding - const c = commonAABB([first, second]); - const overlapsBothAxes = - first[2] - first[0] + second[2] - second[0] > c[2] - c[0] + 0.00000000001 && - first[3] - first[1] + second[3] - second[1] > c[3] - c[1] + 0.00000000001; - if (disableSideHack || !overlapsBothAxes) { - return [first, second]; - } - - const aIsLeft = a[2] < b[0]; - const aIsRight = a[0] > b[2]; - const aIsAbove = a[3] < b[1]; - const aIsBelow = a[1] > b[3]; - if (!(aIsLeft || aIsRight) || !(aIsAbove || aIsBelow)) { - return [first, second]; - } - - // halfway across the gaps between the boxes - const splitX = aIsLeft - ? first[2] + (second[0] - first[2]) / 2 - : second[2] + (first[0] - second[2]) / 2; - const splitY = aIsAbove - ? first[3] + (second[1] - first[3]) / 2 - : second[3] + (first[1] - second[3]) / 2; - - // Split at x when the end is further off to the side of `a` than above or - // below it (relative to the shape of `a`), i.e. depending on which side of - // the diagonal of `a` pointing towards the end the end's center is on - const endCenterX = (second[0] + second[2]) / 2; - const endCenterY = (second[1] + second[3]) / 2; - const diagonalCross = (x1: number, y1: number, x2: number, y2: number) => - vectorCross( - vector(x1 - endCenterX, y1 - endCenterY), - vector(x2 - endCenterX, y2 - endCenterY), - ); - const cross = - aIsLeft === aIsBelow - ? // bottom-left or top-right: the diagonal from top-right to bottom-left - diagonalCross(a[2], a[1], a[0], a[3]) - : // top-left or bottom-right: the diagonal from top-left to bottom-right - diagonalCross(a[0], a[1], a[2], a[3]); - const splitAtX = aIsLeft ? !(cross > 0) : cross > 0; - - if (splitAtX) { - return aIsLeft - ? [ - [first[0], first[1], splitX, first[3]], - [splitX, second[1], second[2], second[3]], - ] - : [ - [splitX, first[1], first[2], first[3]], - [second[0], second[1], splitX, second[3]], - ]; - } - - return aIsAbove - ? [ - [first[0], first[1], first[2], splitY], - [second[0], splitY, second[2], second[3]], - ] - : [ - [first[0], splitY, first[2], first[3]], - [second[0], second[1], second[2], splitY], - ]; -}; - -/** - * One side of {@link generateDynamicAABBs}: grows `self` by its padding, or - * (on the sides facing `other`, if they're apart) to halfway between their - * elements. Sides not facing `other` reach out to the common bounds. - */ -const growBounds = ( - self: Bounds, - other: Bounds, - selfEl: Bounds, - otherEl: Bounds, - common: Bounds, - [up, right, down, left]: BoundsOffset, -): Bounds => { - const apartHorizontally = self[0] > other[2] || self[2] < other[0]; - const apartVertically = self[1] > other[3] || self[3] < other[1]; - - const leftMid = (selfEl[0] + otherEl[2]) / 2; - const topMid = (selfEl[1] + otherEl[3]) / 2; - const rightMid = (selfEl[2] + otherEl[0]) / 2; - const bottomMid = (selfEl[3] + otherEl[1]) / 2; - - return [ - self[0] > other[2] - ? apartVertically - ? Math.min(leftMid, self[0] - left) - : leftMid - : self[0] > other[0] - ? self[0] - left - : common[0] - left, - self[1] > other[3] - ? apartHorizontally - ? Math.min(topMid, self[1] - up) - : topMid - : self[1] > other[1] - ? self[1] - up - : common[1] - up, - self[2] < other[0] - ? apartVertically - ? Math.max(rightMid, self[2] + right) - : rightMid - : self[2] < other[2] - ? self[2] + right - : common[2] + right, - self[3] < other[1] - ? apartHorizontally - ? Math.max(bottomMid, self[3] + down) - : bottomMid - : self[3] < other[3] - ? self[3] + down - : common[3] + down, - ]; -}; - // ----------------------------------------------------------------------------- // Routing // ----------------------------------------------------------------------------- +/** One end of the route */ +type Endpoint = { + point: GlobalPoint; + /** Which way the route leaves the start, or the end is entered from */ + heading: Heading; + /** The obstacle of the element it's bound to, if any */ + obstacle: number | null; + /** The length the leg at this end needs, for its corner and arrowhead */ + minLeg: number; + /** + * The cost per px the leg at this end is shorter than the padding (see + * {@link PADDING_LEG_COST}) + */ + paddingLegCost: number; +}; + +/** The cost of the first or last leg being as long as it is */ +const legCost = ({ minLeg, paddingLegCost }: Endpoint, length: number) => + SHORT_LEG_COST * Math.max(0, minLeg - length) + + paddingLegCost * Math.max(0, BASE_PADDING - length); + /** - * The elbow arrow's route: with one or two corners if that fits, or on the - * grid otherwise, without short segments and the points between collinear - * ones + * How far apart the segments either side of a hairpin need to be: between + * two elements it avoids, far enough apart to round both its corners fully, + * as there's room to go around them instead. Otherwise (where they overlap, + * or an end is unbound, and wherever it is the route may have to turn back + * to get to it), only far enough apart to round both corners at all (as + * halfway between endpoints just as far apart, see {@link buildGrid}). + */ +const minHairpin = (betweenElements: boolean) => + betweenElements ? 2 * ELBOW_ARROW_CORNER_RADIUS : ELBOW_ARROW_CORNER_RADIUS; + +/** The cost of a hairpin's middle segment being as long as it is */ +const hairpinCost = (length: number, betweenElements: boolean) => + (betweenElements ? SHORT_HAIRPIN_COST : SHORT_FORCED_HAIRPIN_COST) * + Math.max(0, minHairpin(betweenElements) - length); + +/** + * The elbow arrow's route: the cheapest one leaving its start along the start + * heading and entering its end against the end heading, as its corner points */ export const getElbowArrowRoute = ( - arrow: ElbowArrowState, - elbowArrowData: ElbowArrowData, - elementsMap: ElementsMap, -): GlobalPoint[] => - getCornerPoints( - removeShortSegments( - getSimpleRoute(arrow, elbowArrowData, elementsMap) ?? - getGridRoute(elbowArrowData) ?? - [], - ), - ); - -/** Whether an axis-aligned segment passes through `bounds` */ -const segmentCrossesBounds = (a: GlobalPoint, b: GlobalPoint, bounds: Bounds) => - doBoundsIntersect( - [ - Math.min(a[0], b[0]), - Math.min(a[1], b[1]), - Math.max(a[0], b[0]), - Math.max(a[1], b[1]), - ], - bounds, - ); - -/** - * The route between two bound elements with one corner (when the arrow - * leaves one and enters the other at a right angle) or two (when it leaves - * and enters them heading the same way), if it fits: leaving the start - * element and entering the end one the way their headings tell, clear of - * both. Routed on the grid, the arrow keeps a fixed padding to the elements - * instead, and steps aside to reach it when they're closer than that (e.g. - * when the end element is just below the start's side, or just below the - * start). - */ -const getSimpleRoute = ( arrow: ElbowArrowState, { - startHeading, - endHeading, startGlobalPoint, endGlobalPoint, + startHeading, + endHeading: boundEndHeading, hoveredStartElement, hoveredEndElement, }: ElbowArrowData, elementsMap: ElementsMap, -): GlobalPoint[] | null => { - const oneCorner = - headingIsHorizontal(startHeading) !== headingIsHorizontal(endHeading); - if ( - !hoveredStartElement || - !hoveredEndElement || - hoveredStartElement.id === hoveredEndElement.id || - (!oneCorner && !compareHeading(startHeading, flipHeading(endHeading))) - ) { - return null; - } +): GlobalPoint[] => { + // An arrow from a point of an element back to the same point would have to + // run back over itself to enter it the way it left: it loops around the + // corner instead, entering it from the next side around (clockwise), as a + // self-loop between two sides next to each other does + const endHeading = + hoveredStartElement && + hoveredStartElement.id === hoveredEndElement?.id && + manhattanDistance(startGlobalPoint, endGlobalPoint) < DEDUP_THRESHOLD && + compareHeading(startHeading, boundEndHeading) + ? DIRECTIONS[(directionIndex(boundEndHeading) + 1) % 4] + : boundEndHeading; - // with one corner, the legs are as long as the end is ahead of the start - // along the start's heading, and the start ahead of the end along the - // end's (headings point away from their element), and with two, they - // share the former - const ahead = - (endGlobalPoint[0] - startGlobalPoint[0]) * startHeading[0] + - (endGlobalPoint[1] - startGlobalPoint[1]) * startHeading[1]; - let firstLeg: number; - let lastLeg: number; - if (oneCorner) { - firstLeg = ahead; - lastLeg = - (startGlobalPoint[0] - endGlobalPoint[0]) * endHeading[0] + - (startGlobalPoint[1] - endGlobalPoint[1]) * endHeading[1]; - } else { - // halfway, as the grid routing turns when there's room, unless that - // leaves an arrowhead a shorter leg than the padding, and the other end, - // without one, can spare some of its own (keeping enough to round its - // corner) - firstLeg = ahead / 2; - if (!arrow.startArrowhead !== !arrow.endArrowhead) { - const arrowheadLeg = Math.max( - ahead / 2, - Math.min(BASE_PADDING, ahead - ELBOW_ARROW_CORNER_RADIUS * 2), - ); - firstLeg = arrow.startArrowhead ? arrowheadLeg : ahead - arrowheadLeg; + // The space the route keeps out of: the elements and their binding gap + // (an element bound at both ends is a single obstacle) + const elements = [hoveredStartElement, hoveredEndElement]; + const obstacles: Bounds[] = []; + const gaps: number[] = []; + const obstacleIndex = elements.map((element, i) => { + if (!element) { + return null; } - lastLeg = ahead - firstLeg; - } + if (i === 1 && hoveredStartElement?.id === element.id) { + return 0; + } + const gap = getBindingGap(element); + obstacles.push(aabbForElement(element, elementsMap, [gap, gap, gap, gap])); + gaps.push(gap); + return obstacles.length - 1; + }); - // a leg is to keep its corner rounded (at least a quarter of the radius, - // rather than a stub hugging the element), and one with an arrowhead to - // fit it too (not to have it reach around the corner) - if ( - firstLeg <= - Math.max( - ELBOW_ARROW_CORNER_RADIUS / 2, - arrow.startArrowhead ? getArrowheadSize(arrow.startArrowhead) : 0, - ) || - lastLeg <= - Math.max( - ELBOW_ARROW_CORNER_RADIUS / 2, - arrow.endArrowhead ? getArrowheadSize(arrow.endArrowhead) : 0, - ) - ) { - return null; - } + // room to round the corner, or for an arrowhead and some of the rounding + const minLeg = (arrowhead: Arrowhead | null) => + arrowhead + ? getArrowheadSize(arrowhead) + ELBOW_ARROW_CORNER_RADIUS / 4 + : ELBOW_ARROW_CORNER_RADIUS / 2; + const paddingLegCost = ( + arrowhead: Arrowhead | null, + obstacle: number | null, + ) => + obstacle === null ? 0 : arrowhead ? 2 * PADDING_LEG_COST : PADDING_LEG_COST; - const firstTurn = pointFrom( - startGlobalPoint[0] + startHeading[0] * firstLeg, - startGlobalPoint[1] + startHeading[1] * firstLeg, - ); - const lastTurn = pointFrom( - endGlobalPoint[0] + endHeading[0] * lastLeg, - endGlobalPoint[1] + endHeading[1] * lastLeg, - ); - - const [startBounds, endBounds] = [hoveredStartElement, hoveredEndElement].map( - (element) => { - const gap = getBindingGap(element); - return aabbForElement(element, elementsMap, [gap, gap, gap, gap]); + return findRoute( + { + point: startGlobalPoint, + heading: startHeading, + obstacle: obstacleIndex[0], + minLeg: minLeg(arrow.startArrowhead), + paddingLegCost: paddingLegCost(arrow.startArrowhead, obstacleIndex[0]), }, + { + point: endGlobalPoint, + heading: endHeading, + obstacle: obstacleIndex[1], + minLeg: minLeg(arrow.endArrowhead), + paddingLegCost: paddingLegCost(arrow.endArrowhead, obstacleIndex[1]), + }, + obstacles, + gaps, ); - // (the first leg leaves the start, and the last enters the end) - if ( - segmentCrossesBounds(startGlobalPoint, firstTurn, endBounds) || - segmentCrossesBounds(firstTurn, lastTurn, startBounds) || - segmentCrossesBounds(firstTurn, lastTurn, endBounds) || - segmentCrossesBounds(lastTurn, endGlobalPoint, startBounds) - ) { - return null; - } - - // (with one corner, both turns are at it, and merged later) - return [startGlobalPoint, firstTurn, lastTurn, endGlobalPoint]; }; /** - * The elbow arrow's route on the grid, keeping a padding around the elements - * it connects, or null if there's none + * The obstacles with their binding gaps cut back where they overlap, to meet + * halfway between the elements, as the paddings around them do (see + * {@link clearanceCost}): so a route between them runs in the middle, rather + * than counting as running through both. (Only between sides facing each + * other, and fading out as the elements are further apart along them, or + * overlap more, so the obstacles change continuously.) */ -const getGridRoute = ({ - dynamicAABBs, - startDonglePosition, - startGlobalPoint, - startHeading, - endDonglePosition, - endGlobalPoint, - endHeading, - commonBounds, - hoveredStartElement, - hoveredEndElement, -}: ElbowArrowData): GlobalPoint[] | null => { - const grid = calculateGrid( - dynamicAABBs, - startDonglePosition, - startHeading, - endDonglePosition, - endHeading, - commonBounds, - ); - - const startDongle = pointToGridNode(startDonglePosition, grid); - const endDongle = pointToGridNode(endDonglePosition, grid); - - // Do not allow stepping on the true end or true start points of bound - // endpoints (if they're on the grid at all, as usually only their dongles - // are) - const endNode = pointToGridNode(endGlobalPoint, grid); - if (endNode && hoveredEndElement) { - endNode.closed = true; +const shareGaps = (obstacles: Bounds[], gaps: number[]): Bounds[] => { + if (obstacles.length !== 2) { + return obstacles; } - const startNode = pointToGridNode(startGlobalPoint, grid); - if (startNode && hoveredStartElement) { - startNode.closed = true; + const [a, b] = obstacles.map((bounds) => [...bounds]); + for (const [lo, hi] of [ + [0, 2], + [1, 3], + ] as const) { + // the one before the other along the axis, the sides facing each other + // and how far they're apart along the other axis + const [first, second, firstGap, secondGap] = + a[lo] + a[hi] <= b[lo] + b[hi] + ? [a, b, gaps[0], gaps[1]] + : [b, a, gaps[1], gaps[0]]; + const overlap = first[hi] - second[lo]; + if (overlap <= 0) { + continue; + } + const [across, acrossHi] = lo === 0 ? [1, 3] : [0, 2]; + const apart = Math.max(a[across] - b[acrossHi], b[across] - a[acrossHi], 0); + const share = + clamp((BASE_PADDING - apart) / (BASE_PADDING / 2), 0, 1) * + clamp( + 1 - + (overlap - firstGap - secondGap - BASE_PADDING / 4) / + (BASE_PADDING / 2), + 0, + 1, + ); + // halfway between the elements' sides (or across where they overlap a + // little, which a route between them has to cross anyway) + const middle = (first[hi] - firstGap + second[lo] + secondGap) / 2; + first[hi] -= share * Math.max(0, first[hi] - middle); + second[lo] += share * Math.max(0, middle - second[lo]); } - // If the dongles are inside each other's boxes, there's no way around the - // boxes, so ignore them - const dongleOverlap = - startDongle && - endDongle && - (pointInsideBounds(startDongle.pos, dynamicAABBs[1]) || - pointInsideBounds(endDongle.pos, dynamicAABBs[0])); + return [a, b] as unknown as Bounds[]; +}; - const path = astar( - startDongle ?? startNode!, - endDongle ?? endNode!, - grid, - startHeading, - endHeading, - dongleOverlap ? [] : dynamicAABBs, +const findRoute = ( + start: Endpoint, + end: Endpoint, + elementObstacles: Bounds[], + gaps: number[], +): GlobalPoint[] => { + const obstacles = shareGaps(elementObstacles, gaps); + // With an endpoint within the padding around the element the other end is + // bound to, there's no room for the route to keep its padding around both + // (and going around them gets more and more contrived as they get closer), + // so the elements overlap, and aren't avoided at all + const overlapping = + start.obstacle !== null && + end.obstacle !== null && + start.obstacle !== end.obstacle && + [start, end].some(({ point, obstacle }) => + elementObstacles.some( + (bounds, i) => + i !== obstacle && + signedDistance(point[0], point[1], bounds) < BASE_PADDING, + ), + ); + // Otherwise, an (unbound) endpoint inside an element has to leave it + // anyway, so the element is an obstacle the less, the deeper the endpoint + // is in it (and not at all a padding deep), rather than every way out of it + // being about as expensive + const weights = obstacles.map((obstacle, i) => + overlapping + ? 0 + : Math.min( + ...[start, end] + .filter((endpoint) => endpoint.obstacle !== i) + .map(({ point }) => + clamp( + 1 + signedDistance(point[0], point[1], obstacle) / BASE_PADDING, + 0, + 1, + ), + ), + 1, + ), ); - if (!path) { + const grid = buildGrid(start, end, obstacles, overlapping); + const path = cheapestPath(grid, start, end, obstacles, weights, overlapping); + if (!path || path.length < 2) { + return [start.point, end.point]; + } + + return simplifyRoute(getCornerPoints(path)); +}; + +// ----------------------------------------------------------------------------- +// Grid +// ----------------------------------------------------------------------------- + +type LineKind = keyof typeof LINE_COSTS; +type Line = { at: number; kind: LineKind; exact: boolean }; + +/** + * The grid the route runs on: the lines through the endpoints, the lines a + * padding (and the shortest leg) away from them along their headings, the + * edges of the padding + * around each element, and the lines halfway between the ends (their elements, + * or the points themselves if unbound). All of + * them are there whatever the elements' arrangement (and move with the + * elements), so a route never loses the line it runs on. + */ +type Grid = { + xs: Line[]; + ys: Line[]; +}; + +const buildGrid = ( + start: Endpoint, + end: Endpoint, + obstacles: Bounds[], + overlapping: boolean, +): Grid => { + const xs: Line[] = []; + const ys: Line[] = []; + + for (const { point, heading, minLeg } of [start, end]) { + xs.push({ at: point[0], kind: "preferred", exact: true }); + ys.push({ at: point[1], kind: "preferred", exact: true }); + // where the leg would be a padding long, or as short as it can be + const axis = headingIsHorizontal(heading) ? 0 : 1; + for (const length of [BASE_PADDING, minLeg]) { + (axis === 0 ? xs : ys).push({ + at: point[axis] + heading[axis] * length, + kind: "step", + exact: false, + }); + } + } + + for (const [left, top, right, bottom] of obstacles) { + xs.push( + { at: left - BASE_PADDING, kind: "padding", exact: false }, + { at: right + BASE_PADDING, kind: "padding", exact: false }, + ); + ys.push( + { at: top - BASE_PADDING, kind: "padding", exact: false }, + { at: bottom + BASE_PADDING, kind: "padding", exact: false }, + ); + } + + // halfway between the ends: their elements, or the points themselves if + // they're unbound, or the elements overlap (and aren't avoided) + const [a, b] = [start, end].map(({ point, obstacle }) => + obstacle === null || overlapping + ? ([point[0], point[1], point[0], point[1]] as Bounds) + : obstacles[obstacle], + ); + // (the one across the gap between them preferred, rather than the one + // between their far sides, which only ties with it) + const gap = (lo: 0 | 1, hi: 2 | 3) => Math.max(b[lo] - a[hi], a[lo] - b[hi]); + const boundsOverlap = gap(0, 2) < 0 && gap(1, 3) < 0; + const pointsOnly = + overlapping || (start.obstacle === null && end.obstacle === null); + if (start.obstacle === null || start.obstacle !== end.obstacle) { + for (const [lines, lo, hi] of [ + [xs, 0, 2], + [ys, 1, 3], + ] as const) { + // (none where they overlap, so far that the lines are well inside both, + // or between points too close together for the route to turn back + // halfway between them, rounding its corners: they'd only let the + // route double back on itself) + if ( + (boundsOverlap && gap(lo, hi) < -2 * BASE_PADDING) || + (pointsOnly && gap(lo, hi) < 2 * ELBOW_ARROW_CORNER_RADIUS) + ) { + continue; + } + const aFirst = b[lo] - a[hi] >= a[lo] - b[hi]; + lines.push( + { + at: (a[hi] + b[lo]) / 2, + kind: aFirst ? "preferred" : "padding", + exact: false, + }, + { + at: (b[hi] + a[lo]) / 2, + kind: aFirst ? "padding" : "preferred", + exact: false, + }, + ); + } + } + + return { xs: mergeLines(xs), ys: mergeLines(ys) }; +}; + +/** + * The lines sorted, with the ones at the same place merged into one (the one + * preferred). Ones merely close together are kept apart: which of them would + * be kept would change as they pass each other, and the one kept might be a + * px inside an element's padding, as the other one wouldn't. + */ +const mergeLines = (lines: Line[]): Line[] => { + const rank = (line: Line) => + (line.exact ? 0 : 10) + Object.keys(LINE_COSTS).indexOf(line.kind); + const sorted = [...lines].sort((a, b) => a.at - b.at || rank(a) - rank(b)); + + return sorted.filter((line, i) => i === 0 || line.at !== sorted[i - 1].at); +}; + +// ----------------------------------------------------------------------------- +// Costs +// ----------------------------------------------------------------------------- + +/** + * The (Chebyshev) distance of a point from the bounds: positive outside, + * negative inside + */ +const signedDistance = (x: number, y: number, [l, t, r, b]: Bounds) => { + const dx = Math.max(l - x, x - r); + const dy = Math.max(t - y, y - b); + + return dx > 0 || dy > 0 ? Math.max(dx, dy, 0) : Math.max(dx, dy); +}; + +/** + * Across how many px around an obstacle's corner the room around it turns + * from being measured horizontally to vertically (see {@link clearanceCost}) + */ +const CORNER_BLEND = BASE_PADDING / 2; + +/** + * How much further away than it is an obstacle counts, per px its near side + * is short of being ahead of a point, for the room around another obstacle + * (see {@link clearanceCost}) + */ +const BEHIND_FACTOR = 10; + +/** + * How far past its end another obstacle still counts as across from an + * obstacle, for the room around it (see {@link clearanceCost}): so a segment + * through a gap a little past where one of them ends still runs halfway + * between them. Any further, and the padding would shrink where there's room + * for it. + */ +const REACH_ACROSS = BASE_PADDING; + +/** + * The cost per px of route at a point, for running close to, or through, the + * obstacles (but the ones at `exclude`, while still keeping their share of + * the room between them) + * + * The padding around an obstacle is the smaller of the base padding and half + * the room between it and the other obstacle at that point, so the middle of + * a gap between them is always free, however narrow. The room is measured + * along the axis the point is off the obstacle on (blended around its + * corners), and counts the other obstacle as reaching a padding further + * across that axis, so a gap is between the elements even a little past where + * one of them ends. Everything here varies continuously with the point and + * the obstacles. + */ +const clearanceCost = ( + x: number, + y: number, + obstacles: Bounds[], + weights: readonly number[], + allowance: readonly number[], + exclude: number, + crossingOnly: boolean, +) => { + // (this runs a lot, so it doesn't allocate) + const count = obstacles.length; + for (let i = 0; i < count; i++) { + const [l, t, r, b] = obstacles[i]; + const dx = Math.max(l - x, x - r); + const dy = Math.max(t - y, y - b); + scratch.distance[i] = + dx > 0 || dy > 0 ? Math.max(dx, dy, 0) : Math.max(dx, dy); + scratch.outsideX[i] = Math.max(dx, 0); + scratch.outsideY[i] = Math.max(dy, 0); + } + + let cost = 0; + for (let i = 0; i < count; i++) { + const distance = scratch.distance[i]; + if (exclude & (1 << i) || distance >= BASE_PADDING) { + continue; + } + if (distance < 0) { + // as close as it gets, and running through it past the allowance + const depth = -distance - allowance[i]; + cost += + weights[i] * + ((crossingOnly ? 0 : CLEARANCE_COST) + + (depth > 0 ? CROSSING_COST * Math.min(depth / CROSSING_RAMP, 1) : 0)); + continue; + } + if (crossingOnly) { + continue; + } + + // half the way to the other obstacle, measured along the axis the point + // is off this one on, with the other reaching further across it (see + // REACH_ACROSS), if it's all ahead of the point (further away from this + // one along that axis): one that isn't (beside the point, or behind it) + // doesn't leave less room along that axis, so it's counted as the + // further away, the further its near side is from being ahead. Off a + // corner, the point is off it along both axes, and the room is the less + // of the two (along an axis it's not off it on, the room counts as the + // further away, the further it's from being off it, so a point by a side + // but well along it isn't taken to be by its corner) + const [il, it, ir, ib] = obstacles[i]; + const dxi = scratch.outsideX[i]; + const dyi = scratch.outsideY[i]; + const besideX = Math.max(0, -Math.max(il - x, x - ir)); + const besideY = Math.max(0, -Math.max(it - y, y - ib)); + let halfway = Infinity; + for (let j = 0; j < count; j++) { + if (j === i) { + continue; + } + let reach = scratch.distance[j]; + if (reach > 0) { + const [jl, jt, jr, jb] = obstacles[j]; + const dxj = scratch.outsideX[j]; + const dyj = scratch.outsideY[j]; + // how far the other's near side is short of being ahead of the point + const behindX = x > ir ? x - jl : x < il ? jr - x : 0; + const behindY = y > ib ? y - jt : y < it ? jb - y : 0; + reach = Math.min( + Math.max(dyj, dxj - REACH_ACROSS) + + BEHIND_FACTOR * + (Math.max(0, behindY) * Math.min(1, dyi / CORNER_BLEND) + + besideY), + Math.max(dxj, dyj - REACH_ACROSS) + + BEHIND_FACTOR * + (Math.max(0, behindX) * Math.min(1, dxi / CORNER_BLEND) + + besideX), + ); + } + halfway = Math.min(halfway, Math.max(0, (distance + reach) / 2)); + } + + const padding = Math.min(BASE_PADDING, halfway); + if (distance < padding) { + cost += weights[i] * CLEARANCE_COST * closeness(1 - distance / padding); + } + } + + return cost; +}; + +/** Scratch space for {@link clearanceCost}, for up to two obstacles */ +const scratch = { + distance: new Float64Array(2), + outsideX: new Float64Array(2), + outsideY: new Float64Array(2), +}; + +/** + * The clearance cost of an axis-aligned segment: the integral of + * {@link clearanceCost} along it, by Simpson's rule on the pieces between + * where it changes the most (the obstacles' edges, their paddings', and where + * the nearest side of an obstacle changes), skipping where no obstacle is + * within reach. `exclude` is a bitmask of the obstacles not to count. + */ +const segmentClearanceCost = ( + a: GlobalPoint, + b: GlobalPoint, + obstacles: Bounds[], + weights: readonly number[], + allowance: readonly number[], + exclude: number, + crossingOnly: boolean, +) => { + const horizontal = a[1] === b[1]; + const axis = horizontal ? 0 : 1; + const across = horizontal ? a[1] : a[0]; + let from = Math.min(a[axis], b[axis]); + let to = Math.max(a[axis], b[axis]); + + // only along where some obstacle is within reach + let reachFrom = Infinity; + let reachTo = -Infinity; + const breakpoints: number[] = []; + obstacles.forEach((obstacle, i) => { + const lo = obstacle[axis]; + const hi = obstacle[axis + 2]; + // how far outside (positive) or inside (negative) the obstacle the line + // the segment is on is, across it + const acrossDistance = Math.max( + obstacle[1 - axis] - across, + across - obstacle[3 - axis], + ); + if (acrossDistance < BASE_PADDING) { + reachFrom = Math.min(reachFrom, lo - BASE_PADDING); + reachTo = Math.max(reachTo, hi + BASE_PADDING); + } + for (const offset of [ + BASE_PADDING, + 0, + -allowance[i], + -allowance[i] - CROSSING_RAMP, + acrossDistance, + -acrossDistance, + ]) { + breakpoints.push(lo - offset, hi + offset); + } + }); + from = Math.max(from, reachFrom); + to = Math.min(to, reachTo); + if (to <= from) { + return 0; + } + + const cuts = breakpoints.filter((p) => p > from && p < to); + cuts.push(from, to); + cuts.sort((p, q) => p - q); + const at = (t: number) => + horizontal + ? clearanceCost( + t, + across, + obstacles, + weights, + allowance, + exclude, + crossingOnly, + ) + : clearanceCost( + across, + t, + obstacles, + weights, + allowance, + exclude, + crossingOnly, + ); + + let cost = 0; + let atP = at(cuts[0]); + for (let i = 1; i < cuts.length; i++) { + const p = cuts[i - 1]; + const q = cuts[i]; + if (q - p > 0) { + const atQ = at(q); + cost += ((q - p) / 6) * (atP + 4 * at((p + q) / 2) + atQ); + atP = atQ; + } + } + + return cost; +}; + +// ----------------------------------------------------------------------------- +// Search +// ----------------------------------------------------------------------------- + +/** Indexed as the directions of the search states */ +const DIRECTIONS = [HEADING_UP, HEADING_RIGHT, HEADING_DOWN, HEADING_LEFT]; + +const directionIndex = (heading: Heading) => + DIRECTIONS.findIndex((direction) => compareHeading(direction, heading)); + +/** Whether `p` is on the ray from `origin` along `heading` */ +const isOnRay = (p: GlobalPoint, origin: GlobalPoint, heading: Heading) => + headingIsHorizontal(heading) + ? p[1] === origin[1] && (p[0] - origin[0]) * heading[0] >= 0 + : p[0] === origin[0] && (p[1] - origin[1]) * heading[1] >= 0; + +const manhattanDistance = (a: GlobalPoint, b: GlobalPoint) => + Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]); + +type SearchState = { state: number; cost: number }; + +/** Which way the last corner turned, if there was one */ +const NO_TURN = 0; +const RIGHT_TURN = 1; +const LEFT_TURN = 2; + +/** + * The cheapest path on the grid (Dijkstra's algorithm on the grid's nodes + * combined with the direction they're arrived at in, so the bends are costed + * exactly), leaving the start along its heading and entering the end against + * its heading + */ +const cheapestPath = ( + { xs, ys }: Grid, + start: Endpoint, + end: Endpoint, + obstacles: Bounds[], + weights: readonly number[], + overlapping: boolean, +): GlobalPoint[] | null => { + // (see minHairpin) + const betweenElements = + !overlapping && + start.obstacle !== null && + end.obstacle !== null && + start.obstacle !== end.obstacle; + const cols = xs.length; + const rows = ys.length; + const nodeCount = cols * rows; + const pos = (node: number) => + pointFrom(xs[node % cols].at, ys[Math.floor(node / cols)].at); + const nodeAt = (p: GlobalPoint) => { + const col = xs.findIndex((line) => line.at === p[0]); + const row = ys.findIndex((line) => line.at === p[1]); + return col === -1 || row === -1 ? -1 : row * cols + col; + }; + const neighbor = (node: number, direction: number) => { + const col = node % cols; + const row = Math.floor(node / cols); + switch (direction) { + case 0: + return row > 0 ? node - cols : -1; + case 1: + return col < cols - 1 ? node + 1 : -1; + case 2: + return row < rows - 1 ? node + cols : -1; + } + return col > 0 ? node - 1 : -1; + }; + + const startNode = nodeAt(start.point); + const endNode = nodeAt(end.point); + if (startNode === -1 || endNode === -1) { return null; } + // A search state is the node, the direction it's arrived at in, which way + // the last corner turned, and where the current segment started (its row + // moving vertically, or column horizontally), so hairpins are costed by + // how long they are + const lineCount = Math.max(cols, rows); + const stateOf = ( + node: number, + direction: number, + turn: number, + segmentStart: number, + ) => ((node * 4 + direction) * 3 + turn) * lineCount + segmentStart; + const nodeOf = (state: number) => Math.floor(state / (12 * lineCount)); + const indexAlong = (node: number, direction: number) => + direction % 2 === 0 ? Math.floor(node / cols) : node % cols; + const startDirection = directionIndex(start.heading); + const arrivalHeading = flipHeading(end.heading); + const arrivalDirection = directionIndex(arrivalHeading); - const points = path.map((node) => - pointFrom(node.pos[0], node.pos[1]), + // The cost of the step from a node in a direction, by the edge (the lower + // or left node and whether it's vertical), and whether it's on the leg + // leaving the start or entering the end. A leg runs where its endpoint is, + // so it's free to run as far into another element as its endpoint is + // (only not any further), and for the padding it needs to be long, to be + // as close to other elements as it is: otherwise, it would be as short as + // it can be whenever the endpoint is close to another element. (Past that, + // it costs as any other segment, so it's no longer than it needs to be.) + const depthIn = (point: GlobalPoint) => + obstacles.map((obstacle) => + Math.max(0, -signedDistance(point[0], point[1], obstacle)), + ); + const noAllowance = obstacles.map(() => 0); + const startAllowance = depthIn(start.point); + const endAllowance = depthIn(end.point); + const edgeCosts = new Map(); + const edgeCost = (from: number, to: number, direction: number) => { + const a = pos(from); + const b = pos(to); + const exemptStart = + direction === startDirection && + isOnRay(a, start.point, start.heading) && + isOnRay(b, start.point, start.heading); + const exemptEnd = + direction === arrivalDirection && + isOnRay(a, end.point, end.heading) && + isOnRay(b, end.point, end.heading); + // (the padding nearest the endpoint, which the leg needs anyway) + const withinPadding = (endpoint: GlobalPoint) => + Math.max( + manhattanDistance(a, endpoint), + manhattanDistance(b, endpoint), + ) <= + BASE_PADDING + DEDUP_THRESHOLD; + const nearEndpoint = + (exemptStart && withinPadding(start.point)) || + (exemptEnd && withinPadding(end.point)); + const vertical = direction % 2 === 0; + const key = + (Math.min(from, to) * 2 + (vertical ? 1 : 0)) * 8 + + (exemptStart ? 1 : 0) + + (exemptEnd ? 2 : 0) + + (nearEndpoint ? 4 : 0); + let cost = edgeCosts.get(key); + if (cost === undefined) { + const length = manhattanDistance(a, b); + cost = + length + + segmentClearanceCost( + a, + b, + obstacles, + weights, + exemptStart && exemptEnd + ? startAllowance.map((depth, i) => Math.max(depth, endAllowance[i])) + : exemptStart + ? startAllowance + : exemptEnd + ? endAllowance + : noAllowance, + (exemptStart && start.obstacle !== null ? 1 << start.obstacle : 0) | + (exemptEnd && end.obstacle !== null ? 1 << end.obstacle : 0), + nearEndpoint, + ); + edgeCosts.set(key, cost); + } + return cost; + }; + const stateCount = nodeCount * 12 * lineCount; + const best = new Float64Array(stateCount).fill(Infinity); + const parent = new Int32Array(stateCount).fill(-1); + const open = new BinaryHeap((s) => s.cost); + + const initial = stateOf( + startNode, + startDirection, + NO_TURN, + indexAlong(startNode, startDirection), ); - startDongle && points.unshift(startGlobalPoint); - endDongle && points.push(endGlobalPoint); + best[initial] = 0; + open.push({ state: initial, cost: 0 }); - return points; + while (open.size() > 0) { + const { state, cost } = open.pop()!; + if (cost > best[state]) { + continue; + } + const segmentStart = state % lineCount; + const lastTurn = Math.floor(state / lineCount) % 3; + const arrivedIn = Math.floor(state / (3 * lineCount)) % 4; + const node = nodeOf(state); + if (node === endNode && arrivedIn === arrivalDirection) { + return tracePath(state, parent, (s) => pos(nodeOf(s))); + } + + for (let direction = 0; direction < 4; direction++) { + // no turning back, and no turning before leaving the start + if ( + direction === (arrivedIn + 2) % 4 || + (node === startNode && direction !== startDirection) + ) { + continue; + } + const next = neighbor(node, direction); + if (next === -1) { + continue; + } + + let nextCost = cost + edgeCost(node, next, direction); + let nextTurn = lastTurn; + let nextSegmentStart = segmentStart; + if (direction !== arrivedIn) { + nextTurn = direction === (arrivedIn + 1) % 4 ? RIGHT_TURN : LEFT_TURN; + nextSegmentStart = indexAlong(node, direction); + // turning back, too close to where it came from (unless only + // stepping from one endpoint's line to the other's, as the + // endpoints may need it to) + if (nextTurn === lastTurn) { + const [from, to] = + arrivedIn % 2 === 0 + ? [ys[segmentStart], ys[Math.floor(node / cols)]] + : [xs[segmentStart], xs[node % cols]]; + if (!from.exact || !to.exact) { + nextCost += hairpinCost(Math.abs(to.at - from.at), betweenElements); + } + } + // (and onto the line the next segment runs on) + const line = + direction % 2 === 0 ? xs[node % cols] : ys[Math.floor(node / cols)]; + nextCost += + BEND_COST + + (nextTurn === LEFT_TURN ? TURN_BIAS : 0) + + LINE_COSTS[line.kind]; + + // a leg too short for its corner or arrowhead + const p = pos(node); + if ( + arrivedIn === startDirection && + isOnRay(p, start.point, start.heading) + ) { + nextCost += legCost(start, manhattanDistance(p, start.point)); + } + if ( + direction === arrivalDirection && + isOnRay(p, end.point, end.heading) + ) { + nextCost += legCost(end, manhattanDistance(p, end.point)); + } + } + + const nextState = stateOf(next, direction, nextTurn, nextSegmentStart); + if (nextCost < best[nextState]) { + best[nextState] = nextCost; + parent[nextState] = state; + open.push({ state: nextState, cost: nextCost }); + } + } + } + + return null; +}; + +const tracePath = ( + state: number, + parent: Int32Array, + pos: (state: number) => GlobalPoint, +): GlobalPoint[] => { + const path: GlobalPoint[] = []; + for (let s = state; s !== -1; s = parent[s]) { + path.unshift(pos(s)); + } + + return path; +}; + +/** + * Only the corners of the path, with any step too short to see (between + * endpoints nearly, but not exactly, in line) taken out: only where the route + * carries on the same way after it, so it's never left doubling back + */ +const simplifyRoute = (path: GlobalPoint[]): GlobalPoint[] => { + const corners = getCornerPoints(path); + const isStep = (i: number) => + i >= 1 && + i + 2 < corners.length && + manhattanDistance(corners[i], corners[i + 1]) < DEDUP_THRESHOLD && + Math.sign(corners[i][0] - corners[i - 1][0]) === + Math.sign(corners[i + 2][0] - corners[i + 1][0]) && + Math.sign(corners[i][1] - corners[i - 1][1]) === + Math.sign(corners[i + 2][1] - corners[i + 1][1]); + + return corners.filter((_, i) => !isStep(i) && !isStep(i - 1)); }; /** Drops the points between collinear segments */ @@ -866,278 +1273,3 @@ const getCornerPoints = (points: GlobalPoint[]): GlobalPoint[] => { return isCorner; }); }; - -/** Drops the points ending degenerate (too short) segments */ -const removeShortSegments = (points: GlobalPoint[]): GlobalPoint[] => { - if (points.length < 4) { - return points; - } - - return points.filter( - (p, idx) => - idx === 0 || - idx === points.length - 1 || - pointDistance(points[idx - 1], p) > DEDUP_THRESHOLD, - ); -}; - -// ----------------------------------------------------------------------------- -// A* grid search -// ----------------------------------------------------------------------------- - -/** - * Builds the grid the A* search walks: its nodes are where the lines along - * the edges of the boxes, and through the endpoints along their headings, - * cross. - * - * NOTE: This is not a uniform grid. It is built at - * various intersections of bounding boxes. - */ -const calculateGrid = ( - aabbs: Bounds[], - start: GlobalPoint, - startHeading: Heading, - end: GlobalPoint, - endHeading: Heading, - common: Bounds, -): Grid => { - const xs = new Set(); - const ys = new Set(); - - for (const [point, heading] of [ - [start, startHeading], - [end, endHeading], - ] as const) { - if (headingIsHorizontal(heading)) { - ys.add(point[1]); - } else { - xs.add(point[0]); - } - } - - for (const aabb of [...aabbs, common]) { - xs.add(aabb[0]); - xs.add(aabb[2]); - ys.add(aabb[1]); - ys.add(aabb[3]); - } - - const sortedXs = Array.from(xs).sort((a, b) => a - b); - const sortedYs = Array.from(ys).sort((a, b) => a - b); - - return { - row: sortedYs.length, - col: sortedXs.length, - data: sortedYs.flatMap((y, row) => - sortedXs.map( - (x, col): Node => ({ - f: 0, - g: 0, - h: 0, - closed: false, - visited: false, - parent: null, - addr: [col, row] as GridAddress, - pos: [x, y] as GlobalPoint, - }), - ), - ), - }; -}; - -const gridNodeFromAddr = ( - [col, row]: [col: number, row: number], - grid: Grid, -): Node | null => { - if (col < 0 || col >= grid.col || row < 0 || row >= grid.row) { - return null; - } - - return grid.data[row * grid.col + col] ?? null; -}; - -/** The grid node at the given point, if there's one */ -const pointToGridNode = (point: GlobalPoint, grid: Grid): Node | null => - grid.data.find( - (node) => node.pos[0] === point[0] && node.pos[1] === point[1], - ) ?? null; - -/** The headings of the neighbors returned by {@link getNeighbors} */ -const NEIGHBOR_HEADINGS = [ - HEADING_UP, - HEADING_RIGHT, - HEADING_DOWN, - HEADING_LEFT, -] as const; - -/** The neighboring nodes up, right, down and left of a grid address */ -const getNeighbors = ([col, row]: GridAddress, grid: Grid) => - [ - gridNodeFromAddr([col, row - 1], grid), - gridNodeFromAddr([col + 1, row], grid), - gridNodeFromAddr([col, row + 1], grid), - gridNodeFromAddr([col - 1, row], grid), - ] as const; - -const manhattanDistance = (a: GlobalPoint, b: GlobalPoint) => - Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]); - -/** - * Routing algorithm based on the A* path search algorithm. - * @see https://www.geeksforgeeks.org/a-search-algorithm/ - * - * Binary heap is used to optimize node lookup. - * See {@link calculateGrid} for the grid calculation details. - * - * Additional modifications added due to aesthetic route reasons: - * 1) Arrow segment direction change is penalized by specific linear constant (bendMultiplier) - * 2) Arrow segments are not allowed to go "backwards", overlapping with the previous segment - */ -const astar = ( - start: Node, - end: Node, - grid: Grid, - startHeading: Heading, - endHeading: Heading, - aabbs: Bounds[], -) => { - const bendMultiplier = manhattanDistance(start.pos, end.pos); - const open = new BinaryHeap((node) => node.f); - - open.push(start); - - while (open.size() > 0) { - // Grab the lowest f(x) to process next. Heap keeps this sorted for us. - const current = open.pop(); - - if (!current || current.closed) { - // Current is not passable, continue with next element - continue; - } - - // End case -- result has been found, return the traced path. - if (current === end) { - return pathTo(start, current); - } - - // Normal case -- move current from open to closed, process each of its neighbors. - current.closed = true; - - const neighbors = getNeighbors(current.addr, grid); - for (let i = 0; i < 4; i++) { - const neighbor = neighbors[i]; - - if (!neighbor || neighbor.closed) { - // Not a valid node to process, skip to next neighbor. - continue; - } - - // Don't cut through any of the boxes - const halfPoint = pointScaleFromOrigin(neighbor.pos, current.pos, 0.5); - if (aabbs.some((aabb) => pointInsideBounds(halfPoint, aabb))) { - continue; - } - - const neighborHeading = NEIGHBOR_HEADINGS[i]; - const previousDirection = current.parent - ? vectorToHeading(vectorFromPoint(current.pos, current.parent.pos)) - : startHeading; - - // Do not allow going in reverse, nor stepping back onto the start or - // into the end against their headings - if ( - compareHeading(flipHeading(previousDirection), neighborHeading) || - (neighbor === start && compareHeading(neighborHeading, startHeading)) || - (neighbor === end && compareHeading(neighborHeading, endHeading)) - ) { - continue; - } - - // The g score is the shortest distance from start to current node. - // We need to check if the path we have arrived at this neighbor is the shortest one we have seen yet. - const directionChange = !compareHeading( - previousDirection, - neighborHeading, - ); - const gScore = - current.g + - manhattanDistance(neighbor.pos, current.pos) + - (directionChange ? Math.pow(bendMultiplier, 3) : 0); - - const beenVisited = neighbor.visited; - - if (!beenVisited || gScore < neighbor.g) { - // (the end node is the end dongle, which is arrived at heading - // towards the end element, i.e. against the end heading) - const estBendCount = estimateBendCount( - neighbor, - end, - neighborHeading, - flipHeading(endHeading), - ); - // Found an optimal (so far) path to this node. Take score for node to see how good it is. - neighbor.visited = true; - neighbor.parent = current; - neighbor.h = - manhattanDistance(end.pos, neighbor.pos) + - estBendCount * Math.pow(bendMultiplier, 2); - neighbor.g = gScore; - neighbor.f = neighbor.g + neighbor.h; - if (!beenVisited) { - // Pushing to heap will put it in proper place based on the 'f' value. - open.push(neighbor); - } else { - // Already seen the node, but since it has been rescored we need to reorder it in the heap - open.rescoreElement(neighbor); - } - } - } - } - - return null; -}; - -const pathTo = (start: Node, node: Node) => { - let curr = node; - const path = []; - while (curr.parent) { - path.unshift(curr); - curr = curr.parent; - } - path.unshift(start); - - return path; -}; - -/** - * The A* heuristic's estimate of the bends left for a path at `start`, moving - * along `heading`, to arrive at `end` moving along `arrivalHeading` - */ -const estimateBendCount = ( - start: Node, - end: Node, - heading: Heading, - arrivalHeading: Heading, -) => { - const dx = end.pos[0] - start.pos[0]; - const dy = end.pos[1] - start.pos[1]; - // How far `end` is ahead along the arrival heading, and whether it's on - // the line through `start` along it - const ahead = dx * arrivalHeading[0] + dy * arrivalHeading[1]; - const inLine = dx * arrivalHeading[1] - dy * arrivalHeading[0] === 0; - - if (compareHeading(heading, arrivalHeading)) { - // straight on, or a step to the side, or turning around if past `end` - return ahead <= 0 ? 4 : inLine ? 0 : 2; - } - - if (compareHeading(heading, flipHeading(arrivalHeading))) { - // turning around (and stepping aside first if in line) - return inLine ? 4 : 2; - } - - // heading across: one turn if heading towards the line `end` is arrived - // along, and still before `end` on it - const towards = dx * heading[0] + dy * heading[1]; - return towards > 0 && ahead > 0 ? 1 : 3; -}; diff --git a/packages/element/tests/elbowArrow.test.tsx b/packages/element/tests/elbowArrow.test.tsx index d07395c3ef..1714afa974 100644 --- a/packages/element/tests/elbowArrow.test.tsx +++ b/packages/element/tests/elbowArrow.test.tsx @@ -299,6 +299,32 @@ describe("elbow arrow ui", () => { ]); }); + it("enters a side its end is dragged onto from inside its element by that side", () => { + // a loop from the right of a wide rectangle, with the end dragged inside + // it towards the top, near its right: the end snaps onto the top (much + // further from the center sideways than up), and the arrow enters it + // from above, as it does once bound, rather than along it + UI.createElement("rectangle", { x: 0, y: 0, width: 200, height: 100 }); + UI.clickTool("arrow"); + UI.clickOnTestId("elbow-arrow"); + mouse.reset(); + mouse.moveTo(200, 50); + mouse.down(); + for (let i = 1; i <= 4; i++) { + mouse.moveTo(200 - (50 * i) / 6, 50 - (50 * i) / 6); + } + + const arrow = h.elements.find( + (element) => element.type === "arrow", + ) as ExcalidrawElbowArrowElement; + const [corner, end] = arrow.points.slice(-2); + expect(arrow.y + end[1]).toBeLessThan(0); + expect(end[0]).toBeCloseTo(corner[0]); + expect(end[1]).toBeGreaterThan(corner[1]); + + mouse.up(); + }); + it("can follow bound rotated shapes", async () => { UI.createElement("rectangle", { x: -150, @@ -333,12 +359,17 @@ describe("elbow arrow ui", () => { ) as HTMLInputElement; UI.updateInput(inputAngle, String("40")); - expect(arrow.points.map((point) => point.map(Math.round))).toEqual([ - [0, 0], - [51, 0], - [51, 164], - [101, 164], - ]); + // turning halfway between the elements' bounds (the rotated one's + // bounding box) + expect(arrow.points).toCloselyEqualPoints( + [ + [0, 0], + [40, 0], + [40, 164], + [101, 164], + ], + 0, + ); }); it("keeps arrow shape when the whole set of arrow and bindables are duplicated", async () => { @@ -953,3 +984,702 @@ describe("elbow arrow endpoints exactly on the bound element's outline", () => { expect(points![1][1]).toBeLessThan(points![0][1]); }); }); + +describe("elbow arrow routing between overlapping elements", () => { + it("doesn't avoid them once an endpoint is within the padding around the other one", () => { + // an arrow from the right of the lower element to the left of the upper + // one, with the lower one dragged up through the upper one + const upper = API.createElement({ + type: "rectangle", + x: 770.35, + y: 366.07, + width: 224.54, + height: 112, + }); + let lower = API.createElement({ + type: "rectangle", + x: 777.3, + y: 552.24, + width: 224.54, + height: 112, + }); + let arrow = API.createElement({ + type: "arrow", + elbowed: true, + x: 1007.84, + y: 608.25, + points: [pointFrom(0, 0), pointFrom(-243, -186)], + startBinding: { + elementId: lower.id, + fixedPoint: [1.0267, 0.5001], + mode: "orbit", + }, + endBinding: { + elementId: upper.id, + fixedPoint: [-0.0267, 0.5001], + mode: "orbit", + }, + endArrowhead: "arrow", + }) as unknown as ExcalidrawElbowArrowElement; + + const globalPoints = (element: ExcalidrawElbowArrowElement) => + element.points.map( + ([px, py]) => [element.x + px, element.y + py] as [number, number], + ); + + /** The arrow's route with the lower element moved to `y` */ + const routeWithLowerAt = (y: number) => { + lower = { ...lower, y }; + const elementsMap = arrayToMap([ + upper, + lower, + ]) as NonDeletedSceneElementsMap; + const routed = { + ...arrow, + ...updateElbowArrowRoute(arrow, elementsMap), + } as ExcalidrawElbowArrowElement; + arrow = routed; + + // the same as for the arrow made anew between the same endpoints: + // where it was routed before doesn't matter + const fresh = { + ...arrow, + x: 0, + y: 0, + points: [pointFrom(0, 0), pointFrom(1, 1)], + } as ExcalidrawElbowArrowElement; + expect(globalPoints(routed)).toCloselyEqualPoints( + globalPoints({ + ...fresh, + ...updateElbowArrowRoute(fresh, elementsMap), + } as ExcalidrawElbowArrowElement), + ); + + return globalPoints(routed); + }; + + // in 1px steps, from the end being within the padding above the lower + // one, until the start is no longer within the padding below the upper + // one, but where the endpoints are too close in height to turn back + // between them + for (let y = 466; y > 266; y -= 1) { + const points = routeWithLowerAt(y); + const [start, end] = [points[0], points[points.length - 1]]; + if (Math.abs(start[1] - end[1]) < 34) { + continue; + } + + // straight through the elements: right a padding, turning back + // halfway between the endpoints, and right a padding into the end + expect(points).toCloselyEqualPoints([ + start, + [start[0] + 40, start[1]], + [start[0] + 40, (start[1] + end[1]) / 2], + [end[0] - 40, (start[1] + end[1]) / 2], + [end[0] - 40, end[1]], + end, + ]); + } + }); +}); + +describe("elbow arrow clearance", () => { + it.each([740, 760, 770.35, 773.75, 776, 778.32, 790])( + "keeps the padding around an element where nothing is in front of it (the element above at x = %d)", + (upperX) => { + // the start leaves the right side of the lower element, which nothing + // is in front of: the upper element is above it, ending to the left of + // its right side, level with it or a little past it + const upper = API.createElement({ + type: "rectangle", + x: upperX, + y: 366.07, + width: 224.54, + height: 112, + }); + const lower = API.createElement({ + type: "rectangle", + x: 773.75, + y: 502.38, + width: 224.54, + height: 112, + }); + const arrow = API.createElement({ + type: "arrow", + elbowed: true, + x: 1004.29, + y: 558.4, + points: [ + pointFrom(0, 0), + pointFrom(-240, -136), + ], + startBinding: { + elementId: lower.id, + fixedPoint: [1.0267, 0.5001], + mode: "orbit", + }, + endBinding: { + elementId: upper.id, + fixedPoint: [-0.0267, 0.5001], + mode: "orbit", + }, + endArrowhead: "arrow", + }) as unknown as ExcalidrawElbowArrowElement; + + const { points } = updateElbowArrowRoute( + arrow, + arrayToMap([upper, lower]) as NonDeletedSceneElementsMap, + ); + + // between the elements, with the first and last legs (out of the + // binding gap) a padding long + expect(points).toHaveLength(6); + expect(points![1][0] - points![0][0]).toBeCloseTo(40, 0); + expect(points![5][0] - points![4][0]).toBeCloseTo(40, 0); + }, + ); +}); + +describe("elbow arrow legs next to another element", () => { + it("gives the legs their padding when their endpoints are right by the other element", () => { + // overlapping elements, with the start on the right of the upper one + // just above the lower one, and the end on the left of the lower one + // just below the upper one: the elements aren't avoided, but the legs + // still get their padding + const lower = API.createElement({ + type: "rectangle", + x: 856.95, + y: 621.29, + width: 224.54, + height: 112, + }); + const upper = API.createElement({ + type: "rectangle", + x: 781.08, + y: 561.2, + width: 224.54, + height: 112, + }); + const arrow = API.createElement({ + type: "arrow", + elbowed: true, + x: 0, + y: 0, + points: [pointFrom(0, 0), pointFrom(1, 1)], + startBinding: { + elementId: upper.id, + fixedPoint: [1.0267, 0.5001], + mode: "orbit", + }, + endBinding: { + elementId: lower.id, + fixedPoint: [-0.0267, 0.5001], + mode: "orbit", + }, + endArrowhead: "arrow", + }) as unknown as ExcalidrawElbowArrowElement; + + const { points } = updateElbowArrowRoute( + arrow, + arrayToMap([lower, upper]) as NonDeletedSceneElementsMap, + ); + const length = (a: LocalPoint, b: LocalPoint) => + Math.abs(b[0] - a[0]) + Math.abs(b[1] - a[1]); + + // around them, without hooking back to keep a leg short + expect(points!.length).toBeLessThanOrEqual(6); + expect(length(points![0], points![1])).toBeGreaterThanOrEqual(39.5); + expect( + length(points![points!.length - 2], points![points!.length - 1]), + ).toBeGreaterThanOrEqual(39.5); + }); + + it("turns back halfway between the endpoints when they're right by the other element", () => { + // partly overlapping elements, with the start on the right of the upper + // one just above the lower one, and the end on the left of the lower one + // just below the upper one + const lower = API.createElement({ + type: "rectangle", + x: 854.11, + y: 628.21, + width: 224.54, + height: 112, + }); + const upper = API.createElement({ + type: "rectangle", + x: 642.92, + y: 560.95, + width: 224.54, + height: 112, + }); + const arrow = API.createElement({ + type: "arrow", + elbowed: true, + x: 0, + y: 0, + points: [pointFrom(0, 0), pointFrom(1, 1)], + startBinding: { + elementId: upper.id, + fixedPoint: [1.0267, 0.5001], + mode: "orbit", + }, + endBinding: { + elementId: lower.id, + fixedPoint: [-0.0267, 0.5001], + mode: "orbit", + }, + endArrowhead: "arrow", + }) as unknown as ExcalidrawElbowArrowElement; + + const { points } = updateElbowArrowRoute( + arrow, + arrayToMap([lower, upper]) as NonDeletedSceneElementsMap, + ); + + // right a padding, back halfway between the endpoints through both + // elements, and right a padding into the end + const start = points![0]; + const end = points![points!.length - 1]; + expect(points).toCloselyEqualPoints([ + start, + [start[0] + 40, start[1]], + [start[0] + 40, (start[1] + end[1]) / 2], + [end[0] - 40, (start[1] + end[1]) / 2], + [end[0] - 40, end[1]], + end, + ]); + }); + + it.each([ + [604.32, 517.29], + [604.32, 520], + [604.32, 525], + [608.24, 520], + ])( + "gives both legs their padding where the elements' corners nearly touch (the upper one at %d, %d)", + (upperX, upperY) => { + // the upper element's bottom right corner is just above and left of the + // lower one's top left corner (their binding gaps overlapping, and even + // their sides a little), and the route turns back between them + const lower = API.createElement({ + type: "rectangle", + x: 848.21, + y: 630.52, + width: 224.54, + height: 112, + }); + const upper = API.createElement({ + type: "rectangle", + x: upperX, + y: upperY, + width: 224.54, + height: 112, + }); + const arrow = API.createElement({ + type: "arrow", + elbowed: true, + x: 0, + y: 0, + points: [pointFrom(0, 0), pointFrom(1, 1)], + startBinding: { + elementId: upper.id, + fixedPoint: [1.0267, 0.5001], + mode: "orbit", + }, + endBinding: { + elementId: lower.id, + fixedPoint: [-0.0267, 0.5001], + mode: "orbit", + }, + endArrowhead: "arrow", + }) as unknown as ExcalidrawElbowArrowElement; + + const { points } = updateElbowArrowRoute( + arrow, + arrayToMap([lower, upper]) as NonDeletedSceneElementsMap, + ); + + expect(points).toHaveLength(6); + expect(points![1][0] - points![0][0]).toBeCloseTo(40); + expect(points![5][0] - points![4][0]).toBeCloseTo(40); + }, + ); + + it("gives the start leg its padding along the top of the other element", () => { + // the upper element's bottom right corner is above and left of the lower + // one's top left corner, and the route turns back through the gap + // between them: its middle runs along the top of the lower one by the + // start leg (but well along it, rather than by its corner) + const lower = API.createElement({ + type: "rectangle", + x: 848.21, + y: 630.52, + width: 224.54, + height: 112, + }); + const upper = API.createElement({ + type: "rectangle", + x: 607.42, + y: 506.33, + width: 224.54, + height: 112, + }); + const arrow = API.createElement({ + type: "arrow", + elbowed: true, + x: 0, + y: 0, + points: [pointFrom(0, 0), pointFrom(1, 1)], + startBinding: { + elementId: upper.id, + fixedPoint: [1.0267, 0.5001], + mode: "orbit", + }, + endBinding: { + elementId: lower.id, + fixedPoint: [-0.0267, 0.5001], + mode: "orbit", + }, + endArrowhead: "arrow", + }) as unknown as ExcalidrawElbowArrowElement; + + const { points } = updateElbowArrowRoute( + arrow, + arrayToMap([lower, upper]) as NonDeletedSceneElementsMap, + ); + + expect(points).toHaveLength(6); + expect(points![1][0] - points![0][0]).toBeCloseTo(40); + expect(points![5][0] - points![4][0]).toBeCloseTo(40); + }); + + it.each([ + [609.52, 521], + [608.24, 516.83], + [608.24, 510], + [608.24, 505], + ])( + "doesn't turn back too tightly to thread between elements with corners nearly touching (the upper one at %d, %d)", + (upperX, upperY) => { + // the upper element's bottom right corner is just above and left of the + // lower one's top left corner, and the endpoints are just past the + // padding around the other element + const lower = API.createElement({ + type: "rectangle", + x: 848.21, + y: 630.52, + width: 224.54, + height: 112, + }); + const upper = API.createElement({ + type: "rectangle", + x: upperX, + y: upperY, + width: 224.54, + height: 112, + }); + const arrow = API.createElement({ + type: "arrow", + elbowed: true, + x: 0, + y: 0, + points: [pointFrom(0, 0), pointFrom(1, 1)], + startBinding: { + elementId: upper.id, + fixedPoint: [1.0267, 0.5001], + mode: "orbit", + }, + endBinding: { + elementId: lower.id, + fixedPoint: [-0.0267, 0.5001], + mode: "orbit", + }, + endArrowhead: "arrow", + }) as unknown as ExcalidrawElbowArrowElement; + + const { points } = updateElbowArrowRoute( + arrow, + arrayToMap([lower, upper]) as NonDeletedSceneElementsMap, + ); + + // wherever it turns back, with room to round both corners fully + for (let i = 1; i + 2 < points!.length; i++) { + const [a, b, c, d] = points!.slice(i - 1, i + 3); + const turnsBack = + Math.sign(b[0] - a[0]) === -Math.sign(d[0] - c[0]) && + Math.sign(b[1] - a[1]) === -Math.sign(d[1] - c[1]); + if (turnsBack) { + expect( + Math.abs(c[0] - b[0]) + Math.abs(c[1] - b[1]), + ).toBeGreaterThanOrEqual(32); + } + } + expect(points!.length).toBeLessThanOrEqual(6); + }, + ); +}); + +describe("elbow arrow routing between elements overlapping each other's endpoints", () => { + it.each([664.89, 700, 740, 780])( + "stays orthogonal, without doubling back on itself, with the start element at x=%d", + (x) => { + // the start on the right of the left element is inside the right one, + // and the end on the left of the right element inside the left one + const right = API.createElement({ + type: "rectangle", + x: 856.95, + y: 621.29, + width: 224.54, + height: 112, + }); + const left = API.createElement({ + type: "rectangle", + x, + y: 622.43, + width: 224.54, + height: 112, + }); + const arrow = API.createElement({ + type: "arrow", + elbowed: true, + x: 0, + y: 0, + points: [pointFrom(0, 0), pointFrom(1, 1)], + startBinding: { + elementId: left.id, + fixedPoint: [1.0267, 0.5001], + mode: "orbit", + }, + endBinding: { + elementId: right.id, + fixedPoint: [-0.0267, 0.5001], + mode: "orbit", + }, + endArrowhead: "arrow", + }) as unknown as ExcalidrawElbowArrowElement; + + const { points } = updateElbowArrowRoute( + arrow, + arrayToMap([right, left]) as NonDeletedSceneElementsMap, + ); + + // around the elements: right, down, left, up, right + const headings = points!.slice(1).map((p, i) => { + const dx = p[0] - points![i][0]; + const dy = p[1] - points![i][1]; + expect(dx === 0 || dy === 0).toBe(true); + return dx > 0 ? "R" : dx < 0 ? "L" : dy > 0 ? "D" : "U"; + }); + expect(headings.join("")).toBe("RDLUR"); + // with segments far enough apart to see the way it goes + for (let i = 1; i < points!.length - 2; i++) { + expect( + Math.abs(points![i + 1][0] - points![i][0]) + + Math.abs(points![i + 1][1] - points![i][1]), + ).toBeGreaterThan(40); + } + }, + ); +}); + +describe("elbow arrow routing through a narrow gap", () => { + it.each([752, 754, 754.94, 756, 758, 760, 765])( + "runs through the gap between elements a little apart, rather than around them (the lower one at y = %d)", + (lowerY) => { + // an S from the right of the lower element to the left of the upper + // one, with about 10px between them, the lower one a little to the + // left: the route runs through the gap, past the corners of both + const upper = API.createElement({ + type: "rectangle", + x: 848.21, + y: 630.52, + width: 224.54, + height: 112, + }); + const lower = API.createElement({ + type: "rectangle", + x: 824.23, + y: lowerY, + width: 224.54, + height: 112, + }); + const arrow = API.createElement({ + type: "arrow", + elbowed: true, + x: 0, + y: 0, + points: [pointFrom(0, 0), pointFrom(1, 1)], + startBinding: { + elementId: lower.id, + fixedPoint: [1.0267, 0.5001], + mode: "orbit", + }, + endBinding: { + elementId: upper.id, + fixedPoint: [-0.0267, 0.5001], + mode: "orbit", + }, + endArrowhead: "arrow", + }) as unknown as ExcalidrawElbowArrowElement; + + const { x, y, points } = updateElbowArrowRoute( + arrow, + arrayToMap([upper, lower]) as NonDeletedSceneElementsMap, + ); + + // right, up into the gap, left through it, up and right into the end + expect(points).toHaveLength(6); + const middle = y! + points![2][1]; + expect(points![3][1]).toBeCloseTo(points![2][1]); + expect(middle).toBeGreaterThan(upper.y + upper.height); + expect(middle).toBeLessThan(lower.y); + expect(x! + points![3][0]).toBeLessThan(upper.x); + }, + ); +}); + +describe("elbow arrow loops", () => { + it.each([ + ["the right corner of a diamond", "diamond", 227, 249, [0.995, 0.5028]], + [ + "the middle of the right of a rectangle", + "rectangle", + 200, + 100, + [1.03, 0.5], + ], + [ + "the middle of the top of a rectangle", + "rectangle", + 200, + 100, + [0.5, -0.06], + ], + ] as const)( + "loops around the corner from %s back to the same point", + (_, type, width, height, fixedPoint) => { + const element = API.createElement({ + type, + x: 0, + y: 0, + width, + height, + }); + const arrow = API.createElement({ + type: "arrow", + elbowed: true, + x: 0, + y: 0, + points: [pointFrom(0, 0), pointFrom(1, 1)], + startBinding: { + elementId: element.id, + fixedPoint: fixedPoint as FixedPoint, + mode: "orbit", + }, + endBinding: { + elementId: element.id, + fixedPoint: fixedPoint as FixedPoint, + mode: "orbit", + }, + endArrowhead: "arrow", + }) as unknown as ExcalidrawElbowArrowElement; + + const { points } = updateElbowArrowRoute( + arrow, + arrayToMap([element]) as NonDeletedSceneElementsMap, + ); + + // a padding (or so) across, turning the same way all around, back to + // where it started + expect(points).toHaveLength(5); + expect(points![4][0]).toBeCloseTo(points![0][0]); + expect(points![4][1]).toBeCloseTo(points![0][1]); + const segments = points! + .slice(1) + .map(([x, y], i) => [x - points![i][0], y - points![i][1]]); + segments.forEach(([dx, dy], i) => { + expect(Math.abs(dx) + Math.abs(dy)).toBeGreaterThanOrEqual(39.5); + expect(Math.abs(dx) + Math.abs(dy)).toBeLessThan(50); + const [nx, ny] = segments[(i + 1) % 4]; + expect(dx * ny - dy * nx).toBeGreaterThan(0); + }); + }, + ); +}); + +describe("elbow arrow routing while dragging elements", () => { + it.each([16, 24])( + "doesn't jitter between routes when dragged past another element %dpx below it", + (gap) => { + // an arrow from the right of the lower element to the left of the + // upper one (an S between them), with the lower one dragged sideways + const upper = API.createElement({ + type: "rectangle", + x: 0, + y: 0, + width: 224, + height: 112, + }); + const lower = API.createElement({ + type: "rectangle", + x: 0, + y: 112 + gap, + width: 224, + height: 112, + }); + const arrow = API.createElement({ + type: "arrow", + elbowed: true, + x: 0, + y: 0, + points: [pointFrom(0, 0), pointFrom(1, 1)], + startBinding: { + elementId: lower.id, + fixedPoint: [1.0267, 0.5001], + mode: "orbit", + }, + endBinding: { + elementId: upper.id, + fixedPoint: [-0.0267, 0.5001], + mode: "orbit", + }, + endArrowhead: "arrow", + }) as unknown as ExcalidrawElbowArrowElement; + + const routeWithLowerAt = (x: number) => { + const update = updateElbowArrowRoute( + arrow, + arrayToMap([upper, { ...lower, x }]) as NonDeletedSceneElementsMap, + ); + return update.points!.map( + ([px, py]) => [update.x! + px, update.y! + py] as [number, number], + ); + }; + + // in half px steps, noting where the route changes more than the + // element moves + const routes = Array.from({ length: 1201 }, (_, step) => + routeWithLowerAt(-300 + step / 2), + ); + const changes = routes + .map((points, step) => { + const previous = routes[step - 1]; + return previous && + (points.length !== previous.length || + points.some( + ([px, py], i) => + Math.abs(px - previous[i][0]) > 3 || + Math.abs(py - previous[i][1]) > 3, + )) + ? step + : null; + }) + .filter((step): step is number => step !== null); + + // it changes where it has to, but never back and forth from one step + // to the next + const flickers = changes.filter((step, i) => step - changes[i - 1] <= 2); + expect(flickers).toEqual([]); + }, + ); +}); diff --git a/packages/excalidraw/actions/actionFlip.test.tsx b/packages/excalidraw/actions/actionFlip.test.tsx index 0be29c9800..1ac91aea88 100644 --- a/packages/excalidraw/actions/actionFlip.test.tsx +++ b/packages/excalidraw/actions/actionFlip.test.tsx @@ -32,10 +32,10 @@ describe("flipping re-centers selection", () => { API.createElement({ type: "arrow", id: "arr", - x: 149.9, + x: 149, y: 95, - width: 156, - height: 239.9, + width: 161, + height: 245, startBinding: { elementId: "rec1", fixedPoint: [0.49, -0.05], @@ -49,11 +49,14 @@ describe("flipping re-centers selection", () => { startArrowhead: null, endArrowhead: "arrow", fixedSegments: null, + // as routed: flipping routes it again, so its bounds (and the + // selection's, which flipping is centered on) only stay the same if + // the route does points: [ pointFrom(0, 0), - pointFrom(0, -35), - pointFrom(-90, -35), - pointFrom(-90, 204), + pointFrom(0, -41), + pointFrom(-95, -41), + pointFrom(-95, 204), pointFrom(66, 204), ], elbowed: true, @@ -72,11 +75,11 @@ describe("flipping re-centers selection", () => { const rec1 = h.elements.find((el) => el.id === "rec1")!; expect(rec1.x).toBeCloseTo(100, 0); - expect(rec1.y).toBeCloseTo(101, 0); + expect(rec1.y).toBeCloseTo(100, 0); const rec2 = h.elements.find((el) => el.id === "rec2")!; expect(rec2.x).toBeCloseTo(220, 0); - expect(rec2.y).toBeCloseTo(251, 0); + expect(rec2.y).toBeCloseTo(250, 0); }); });