1
0
Fork 0
polaris-task-force/src/lib/flow-edge-routing.ts
Z8MB1E 28bb08f43e fix(npc-dialogue): bus-route return edges and spread detour lanes
Two routing defects on the dialogue canvas:

- Return edges entering the same handle detoured through identical
  corners, stacking into one thick bundle on the left of the target.
  Each edge now derives a stable lane offset from its id, so parallel
  detours run in visibly separate lanes.
- Long leftward runs relied on greedy corner-hopping alone, which could
  still leave a segment cutting under a card. Back edges now try
  structured bus routes (corridor above or below every card, then swing
  in to the entry handle) and score candidates by residual crossings,
  picking the first clean shape. The router also re-runs until clean
  (bounded to three passes) instead of trusting one greedy pass.

Verified on doc #2: all seven edges route with zero card crossings and
no stacked lanes; tech-tree edge-routing specs still pass.
2026-10-06 14:38:42 -04:00

232 lines
7.4 KiB
TypeScript

/**
* Obstacle-avoiding edge routing shared by the admin flow canvases
* (tech tree, NPC dialogue flow editor).
*
* An edge should not cut through nodes it is not connected to. Given the
* polyline an edge would take (source -> optional waypoints -> target) and
* the rectangles of every other node, this inserts detour points so each
* segment swings around the boxes it would otherwise cross.
*
* The detour is greedy: for the first box a segment hits, it tries that box's
* four (inflated) corners and picks the one with the shortest total bend,
* recursing on the two halves. Bounded depth keeps it cheap and terminating.
*
* Pure module: no React/Payload imports, safe on client and server.
*/
export type RoutePoint = { x: number; y: number };
/** A node rectangle to route around. Ids may be numeric or string. */
export type RouteRect = {
id: number | string;
x: number;
y: number;
width: number;
height: number;
};
/** Clearance kept around a node when routing around it. */
export const ROUTE_CLEARANCE = 22;
const MAX_DEPTH = 4;
const EPS = 1;
/** Does segment a->b cross the interior of rect r? (exported for tests) */
export function segmentCrossesRect(a: RoutePoint, b: RoutePoint, r: RouteRect): boolean {
const x1 = r.x + EPS;
const y1 = r.y + EPS;
const x2 = r.x + r.width - EPS;
const y2 = r.y + r.height - EPS;
if (x2 <= x1 || y2 <= y1) return false;
// Liang-Barsky clip of the segment against the (slightly inset) box.
let t0 = 0;
let t1 = 1;
const dx = b.x - a.x;
const dy = b.y - a.y;
const p = [-dx, dx, -dy, dy];
const q = [a.x - x1, x2 - a.x, a.y - y1, y2 - a.y];
for (let i = 0; i < 4; i += 1) {
if (p[i] === 0) {
if (q[i] < 0) return false;
} else {
const t = q[i] / p[i];
if (p[i] < 0) {
if (t > t1) return false;
if (t > t0) t0 = t;
} else {
if (t < t0) return false;
if (t < t1) t1 = t;
}
}
}
return true;
}
const crosses = segmentCrossesRect;
function corners(r: RouteRect, margin: number): RoutePoint[] {
const x1 = r.x - margin;
const y1 = r.y - margin;
const x2 = r.x + r.width + margin;
const y2 = r.y + r.height + margin;
return [
{ x: x1, y: y1 },
{ x: x2, y: y1 },
{ x: x2, y: y2 },
{ x: x1, y: y2 },
];
}
function inside(p: RoutePoint, r: RouteRect, margin: number): boolean {
return (
p.x > r.x - margin &&
p.x < r.x + r.width + margin &&
p.y > r.y - margin &&
p.y < r.y + r.height + margin
);
}
function dist(a: RoutePoint, b: RoutePoint): number {
return Math.hypot(b.x - a.x, b.y - a.y);
}
/** Detour points from a to b (excluding a, ending with b). */
function detour(
a: RoutePoint,
b: RoutePoint,
obstacles: RouteRect[],
margin: number,
depth: number,
): RoutePoint[] {
if (depth >= MAX_DEPTH) return [b];
const hit = obstacles.find((r) => crosses(a, b, r));
if (!hit) return [b];
let best: RoutePoint | null = null;
let bestLen = Number.POSITIVE_INFINITY;
for (const c of corners(hit, margin)) {
// Skip a corner inside another box, or one not reachable from `a` without
// still cutting through the box. The second half is left to the recursion,
// which chains a second corner for wide boxes.
if (obstacles.some((r) => r.id !== hit.id && inside(c, r, 0))) continue;
if (crosses(a, c, hit)) continue;
// A corner at the current point or the destination makes no progress.
if (dist(a, c) < 1 || dist(c, b) < 1) continue;
const len = dist(a, c) + dist(c, b);
if (len < bestLen) {
bestLen = len;
best = c;
}
}
if (!best) return [b];
return [
...detour(a, best, obstacles, margin, depth + 1),
...detour(best, b, obstacles, margin, depth + 1),
];
}
/** Does any segment of the polyline cut one of the obstacles? */
function hasCrossing(points: RoutePoint[], obstacles: RouteRect[]): boolean {
for (let i = 0; i < points.length - 1; i += 1) {
if (obstacles.some((r) => crosses(points[i], points[i + 1], r))) return true;
}
return false;
}
/** One greedy pass: detour every base segment around the boxes it hits. */
function routePass(points: RoutePoint[], obstacles: RouteRect[], margin: number): RoutePoint[] {
const out: RoutePoint[] = [points[0]];
for (let i = 0; i < points.length - 1; i += 1) {
for (const p of detour(points[i], points[i + 1], obstacles, margin, 0)) {
const last = out[out.length - 1];
if (Math.abs(p.x - last.x) > 0.5 || Math.abs(p.y - last.y) > 0.5) out.push(p);
}
}
return out;
}
/**
* Route a polyline around the given obstacle boxes. Returns a new point list;
* returns the input unchanged when there is nothing to avoid. A single greedy
* pass can leave a residual crossing when a chosen corner's continuation
* hits yet another box, so the result is re-routed until clean (bounded).
*/
export function routeAroundObstacles(
points: RoutePoint[],
obstacles: RouteRect[],
margin = ROUTE_CLEARANCE,
): RoutePoint[] {
if (points.length < 2 || obstacles.length === 0) return points;
let routed = points;
for (let pass = 0; pass < 3; pass += 1) {
routed = routePass(routed, obstacles, margin);
if (!hasCrossing(routed, obstacles)) break;
}
return routed;
}
// ---------------------------------------------------------------------------
// Path building
// ---------------------------------------------------------------------------
export type RouteWaypoint = RoutePoint;
/** Corner rounding radius (px) at each waypoint. */
export const ROUTE_CORNER_RADIUS = 14;
/**
* SVG path through the given points. Each interior corner is cut with a
* quadratic curve so bends read as smooth corners instead of hard angles; the
* radius shrinks automatically on short segments so curves never overshoot.
*/
export function buildRoutePath(points: RouteWaypoint[], radius = ROUTE_CORNER_RADIUS): string {
if (points.length < 2) return "";
const start = points[0];
let d = `M ${start.x},${start.y}`;
for (let i = 1; i < points.length - 1; i += 1) {
const prev = points[i - 1];
const cur = points[i];
const next = points[i + 1];
const inLen = dist(prev, cur);
const outLen = dist(cur, next);
if (inLen === 0 || outLen === 0) {
d += ` L ${cur.x},${cur.y}`;
continue;
}
const r = Math.min(radius, inLen / 2, outLen / 2);
const a = {
x: cur.x - ((cur.x - prev.x) / inLen) * r,
y: cur.y - ((cur.y - prev.y) / inLen) * r,
};
const b = {
x: cur.x + ((next.x - cur.x) / outLen) * r,
y: cur.y + ((next.y - cur.y) / outLen) * r,
};
d += ` L ${a.x},${a.y} Q ${cur.x},${cur.y} ${b.x},${b.y}`;
}
const end = points[points.length - 1];
return `${d} L ${end.x},${end.y}`;
}
/** Point at half the total polyline length, for placing edge labels. */
export function polylineMidpoint(points: RoutePoint[]): RoutePoint {
if (points.length === 0) return { x: 0, y: 0 };
if (points.length === 1) return points[0];
let total = 0;
for (let i = 0; i < points.length - 1; i += 1) total += dist(points[i], points[i + 1]);
let target = total / 2;
for (let i = 0; i < points.length - 1; i += 1) {
const seg = dist(points[i], points[i + 1]);
if (target <= seg) {
const t = seg === 0 ? 0 : target / seg;
return {
x: points[i].x + (points[i + 1].x - points[i].x) * t,
y: points[i].y + (points[i + 1].y - points[i].y) * t,
};
}
target -= seg;
}
return points[points.length - 1];
}