fix: Short loops

This commit is contained in:
Mark Tolmacs committed 2026-11-25 11:15:43 +00:00
1 parent 6cbba63bc4
commit 682560e14e
2 files changed
+227 -8

No files matched your search

+115 -1
View File
@@ -829,13 +829,18 @@ const findRoute = (
gaps: number[],
elementsOverlap = false,
cornersClear = false,
parts: readonly ObstacleParts[] = [],
): GlobalPoint[] => {
// Where the elements' bounds overlap, they're one obstacle, the bounds
// around both, which the route leaves from and enters as it would a single
// element (its legs running through it where they start or end inside
// it): so it goes around them both as they look together, and only changes
// as the bounds around them do, continuously, rather than switching
// between the padding around one and the other as they move
// between the padding around one and the other as they move. (Only its
// grid and legs are the union's, though: inside it, the route runs as
// close to and through the elements' own bounds as it does, so through the
// room in the corners of the union, around neither element, as freely as
// it would anywhere else, see clearanceCost.)
if (
start.obstacle !== null &&
end.obstacle !== null &&
@@ -855,6 +860,9 @@ const findRoute = (
{ ...end, obstacle: 0 },
[union],
[Math.max(...gaps)],
false,
false,
[[a, b]],
);
}
const obstacles = shareGaps(elementObstacles, gaps, cornersClear);
@@ -972,6 +980,7 @@ const findRoute = (
weights,
overlapping,
strip,
parts,
);
// (searching for the cheapest route with what it costs to cross itself
// takes much longer, and only makes a difference where the cheapest one
@@ -989,6 +998,7 @@ const findRoute = (
weights,
overlapping,
strip,
parts,
true,
);
if (
@@ -1010,6 +1020,13 @@ const findRoute = (
// Grid
// -----------------------------------------------------------------------------
/**
* The elements' own bounds within an obstacle that's the bounds around them
* (where their bounds overlap, see {@link findRoute}), or null for one
* that's a single element's
*/
type ObstacleParts = readonly Bounds[] | null;
type LineKind = keyof typeof LINE_COSTS;
type Line = {
at: number;
@@ -1147,6 +1164,25 @@ const buildGrid = (
}
}
}
// With the ends bound to the same obstacle (the bounds around elements
// that overlap, see findRoute), there's nothing halfway between them, so
// a hairpin's width either side of the lines the legs run on, for a route
// turning back onto one where it's right by the line the other leg ends
// on: rather than folding back onto itself (see minHairpin), or going
// around the obstacle instead
if (start.obstacle !== null && start.obstacle === end.obstacle) {
for (const { point, heading } of [start, end]) {
const axis = headingIsHorizontal(heading) ? 1 : 0;
for (const side of [-1, 1]) {
(axis === 0 ? xs : ys).push({
at: point[axis] + side * minHairpin(false),
kind: "step",
exact: false,
fromEndpoints: true,
});
}
}
}
return { xs: mergeLines(xs), ys: mergeLines(ys) };
};
@@ -1232,6 +1268,7 @@ const clearanceCost = (
allowance: readonly number[],
exclude: number,
crossingOnly: boolean,
parts: readonly ObstacleParts[],
) => {
// (this runs a lot, so it doesn't allocate)
const count = obstacles.length;
@@ -1251,6 +1288,19 @@ const clearanceCost = (
if (exclude & (1 << i) || distance >= BASE_PADDING) {
continue;
}
if (distance < 0 && parts[i]) {
cost +=
weights[i] *
partsClearanceCost(
x,
y,
parts[i]!,
-distance,
allowance[i],
crossingOnly,
);
continue;
}
if (distance < 0) {
// as close as it gets, and running through it past the allowance
const depth = -distance - allowance[i];
@@ -1315,6 +1365,45 @@ const clearanceCost = (
return cost;
};
/**
* The cost per px of route at a point `depth` px inside an obstacle that's
* the bounds around elements (see {@link findRoute}): as close to, or
* through, the elements' own bounds as it is (as {@link clearanceCost} would
* have it for one of them), so the room in the obstacle's corners, around
* neither of them, is as free as any other. (Counting it as no further from
* them than from the obstacle's edge, though, so the cost is continuous
* across it, and only falls off a padding inside it.)
*/
const partsClearanceCost = (
x: number,
y: number,
parts: readonly Bounds[],
depth: number,
allowance: number,
crossingOnly: boolean,
) => {
let distance = Infinity;
for (const part of parts) {
distance = Math.min(distance, signedDistance(x, y, part));
}
if (distance < 0) {
// through one of them, past the allowance
const through = -distance - allowance;
return (
(crossingOnly ? 0 : CLEARANCE_COST) +
(through > 0 ? CROSSING_COST * Math.min(through / CROSSING_RAMP, 1) : 0)
);
}
if (crossingOnly) {
return 0;
}
const room = Math.min(distance, depth);
return room < BASE_PADDING
? CLEARANCE_COST * closeness(1 - room / BASE_PADDING)
: 0;
};
/** Scratch space for {@link clearanceCost}, for up to two obstacles */
const scratch = {
distance: new Float64Array(2),
@@ -1337,6 +1426,7 @@ const segmentClearanceCost = (
allowance: readonly number[],
exclude: number,
crossingOnly: boolean,
parts: readonly ObstacleParts[],
) => {
const horizontal = a[1] === b[1];
const axis = horizontal ? 0 : 1;
@@ -1371,6 +1461,26 @@ const segmentClearanceCost = (
]) {
breakpoints.push(lo - offset, hi + offset);
}
// (and inside one that's the bounds around elements, where it's a
// padding in from its edge, and around the elements, see
// partsClearanceCost)
for (const part of parts[i] ?? []) {
const partAcross = Math.max(
part[1 - axis] - across,
across - part[3 - axis],
);
breakpoints.push(lo + BASE_PADDING, hi - BASE_PADDING);
for (const offset of [
BASE_PADDING,
0,
-allowance[i],
-allowance[i] - CROSSING_RAMP,
partAcross,
-partAcross,
]) {
breakpoints.push(part[axis] - offset, part[axis + 2] + offset);
}
}
});
from = Math.max(from, reachFrom);
to = Math.min(to, reachTo);
@@ -1391,6 +1501,7 @@ const segmentClearanceCost = (
allowance,
exclude,
crossingOnly,
parts,
)
: clearanceCost(
across,
@@ -1400,6 +1511,7 @@ const segmentClearanceCost = (
allowance,
exclude,
crossingOnly,
parts,
);
let cost = 0;
@@ -1460,6 +1572,7 @@ const cheapestPath = (
weights: readonly number[],
overlapping: boolean,
strip: readonly number[],
parts: readonly ObstacleParts[],
avoidSelfCrossing = false,
): GlobalPoint[] | null => {
// (see minHairpin)
@@ -1609,6 +1722,7 @@ const cheapestPath = (
(exemptStart && start.obstacle !== null ? 1 << start.obstacle : 0) |
(exemptEnd && end.obstacle !== null ? 1 << end.obstacle : 0),
nearEndpoint,
parts,
);
edgeCosts.set(key, cost);
}
+112 -7
View File
@@ -25,6 +25,7 @@ import type { LocalPoint } from "@excalidraw/math";
import { getBindingGap } from "../src/binding";
import { Scene } from "../src/Scene";
import { ELBOW_ARROW_CORNER_RADIUS } from "../src/shape";
import type {
ExcalidrawArrowElement,
@@ -1249,6 +1250,108 @@ describe("elbow arrow routing between overlapping elements", () => {
expect(points![0][1] - points![1][1]).toBeGreaterThan(30);
expect(points![2][0]).toBeGreaterThan(points![4][0]);
});
it("loops through the room in the corner of the bounds around both, rather than around them", () => {
// diamonds diagonal from each other, their bounds overlapping, with the
// start on top of the lower one and the end on the right of the upper
// one, just above the start: only their bounds' corners overlap, so the
// room above the lower one and right of the upper one is clear of both
const upper = API.createElement({
type: "diamond",
x: 2123.26,
y: -856.89,
width: 226.95,
height: 248.6,
});
const lower = API.createElement({
type: "diamond",
x: 2235.93,
y: -711.21,
width: 226.95,
height: 248.6,
});
const arrow = API.createElement({
type: "arrow",
elbowed: true,
x: 0,
y: 0,
points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(1, 1)],
startBinding: {
elementId: lower.id,
fixedPoint: [0.5023, 0.0073],
mode: "orbit",
},
endBinding: {
elementId: upper.id,
fixedPoint: [0.995, 0.5028],
mode: "orbit",
},
endArrowhead: "arrow",
}) as unknown as ExcalidrawElbowArrowElement;
const { points } = updateElbowArrowRoute(
arrow,
arrayToMap([lower, upper]) as NonDeletedSceneElementsMap,
);
// up a padding, right a padding past the end, down and left into it:
// a short loop, rather than one around the bounds of both
expect(points).toHaveLength(5);
expect(points![0][1] - points![1][1]).toBeCloseTo(40, 0);
expect(points![2][0] - points![4][0]).toBeCloseTo(40, 0);
});
it("loops back a hairpin's width where the end is right by where the start's leg ends", () => {
// as above, but with the end's line about where the start's leg ends:
// turning back onto it would fold the route back onto itself
const upper = API.createElement({
type: "diamond",
x: 2123.59,
y: -863.11,
width: 226.95,
height: 248.6,
});
const lower = API.createElement({
type: "diamond",
x: 2226.3,
y: -698.96,
width: 226.95,
height: 248.6,
});
const arrow = API.createElement({
type: "arrow",
elbowed: true,
x: 0,
y: 0,
points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(1, 1)],
startBinding: {
elementId: lower.id,
fixedPoint: [0.5023, 0.0073],
mode: "orbit",
},
endBinding: {
elementId: upper.id,
fixedPoint: [0.995, 0.5028],
mode: "orbit",
},
endArrowhead: "arrow",
}) as unknown as ExcalidrawElbowArrowElement;
const { points } = updateElbowArrowRoute(
arrow,
arrayToMap([lower, upper]) as NonDeletedSceneElementsMap,
);
// up past where the end is by a hairpin's width, right a padding past
// the end, and down and left into it: a short loop, rather than one
// around the bounds of both
expect(points).toHaveLength(5);
expect(points![3][1] - points![2][1]).toBeCloseTo(
ELBOW_ARROW_CORNER_RADIUS,
0,
);
expect(points![2][0] - points![4][0]).toBeCloseTo(40, 0);
});
});
describe("elbow arrow clearance", () => {
@@ -1362,7 +1465,7 @@ describe("elbow arrow legs next to another element", () => {
).toBeGreaterThanOrEqual(39.5);
});
it("goes around them both, as one, when they overlap", () => {
it("goes around the bounds of both, but through the room in their corner, when they overlap", () => {
// 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
@@ -1405,23 +1508,25 @@ describe("elbow arrow legs next to another element", () => {
);
// right past the lower one by a padding, down below it by a padding,
// left past the upper one by a padding, and right into the end: around
// the bounds of both, rather than back between the endpoints through
// both of them
// left to where the end's leg starts, up through the room in the corner
// of the bounds around both (below the upper one, left of the lower
// one, around neither), and right into the end: around the bounds of
// both, rather than back between the endpoints through both of them,
// and not around the upper one too, as nothing's in the way
const gap = getBindingGap(upper);
const global = points!.map(
([px, py]) => [px + x!, py + y!] as [number, number],
);
const [start, end] = [global[0], global[global.length - 1]];
const right = lower.x + lower.width + gap + 40;
const left = upper.x - gap - 40;
const leg = end[0] - 40;
const bottom = lower.y + lower.height + gap + 40;
expect(global).toCloselyEqualPoints([
start,
[right, start[1]],
[right, bottom],
[left, bottom],
[left, end[1]],
[leg, bottom],
[leg, end[1]],
end,
]);
});