1
0
Fork 0
polaris-task-force/src/lib/flow-edge-routing.ts
Z8MB1E efab41ba29 refactor(flow): share the edge shape builder between both flow canvases
Extract the dialogue canvas's routing upgrades into routeEdge() in the
shared lib: perpendicular handle stubs, candidate scoring (Z-step vs
straight for forward edges, top/bottom bus corridors for back edges),
per-edge detour lane spreading, and multi-pass obstacle clearing. The
NPC dialogue RoutedFlowEdge becomes a thin renderer over it, and the
tech tree RoutedEdge now inherits the same logic while keeping its own
features intact: manual waypoints route verbatim (and define the
add-a-bend base), per-source stepPosition lanes feed the Z-step, and
its fixed right/left handles map to the new direction params.

New pure spec covers the Z-step shape, blocked-forward detouring,
back-edge bus routing, per-id lane spread, and waypoint pass-through.
2026-10-06 14:47:14 -04:00

381 lines
12 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];
}
// ---------------------------------------------------------------------------
// Edge shape builder
// ---------------------------------------------------------------------------
/** How far a line leaves its handle before it may bend (px). */
export const EDGE_STUB = 24;
/** Which side of its card a handle sits on. */
export type StubDirection = "left" | "right" | "top" | "bottom";
function stubFor(point: RoutePoint, direction: StubDirection | null | undefined, length: number): RoutePoint {
switch (direction) {
case "left":
return { x: point.x - length, y: point.y };
case "right":
return { x: point.x + length, y: point.y };
case "top":
return { x: point.x, y: point.y - length };
case "bottom":
return { x: point.x, y: point.y + length };
default:
return point;
}
}
/**
* Detour lanes come in three depths so edges that enter the same handle (or
* loop around the same card) don't collapse onto one identical lane and read
* as a single thick bundle. The depth is derived from the edge id, so it is
* stable across renders and differs between edges with overwhelming
* probability.
*/
const LANE_STEPS = [0, 16, 32];
export function laneFor(id: string): number {
let h = 0;
for (let i = 0; i < id.length; i += 1) h = (h * 31 + id.charCodeAt(i)) | 0;
return LANE_STEPS[Math.abs(h) % LANE_STEPS.length];
}
export type EdgeRouteInput = {
/** Edge identity, used to spread detour lanes. */
id?: string;
start: RoutePoint;
end: RoutePoint;
sourceDirection?: StubDirection | null;
targetDirection?: StubDirection | null;
/** Rectangles of every node card on the canvas. */
nodes: RouteRect[];
sourceId?: number | string;
targetId?: number | string;
/** Manual waypoints: routed verbatim (cleaned), skipping auto candidates. */
waypoints?: RoutePoint[];
/** Where the forward Z-step's vertical run sits (0..1). */
stepPosition?: number;
stubLength?: number;
};
export type EdgeRouteResult = {
/** Final polyline to render (detoured, clean when possible). */
points: RoutePoint[];
/** The winning unrouted base shape (for "add a bend" handles). */
base: RoutePoint[];
};
/**
* Build the full route for one edge between two cards.
*
* Forward edges prefer a tidy Z-step (perpendicular stubs at each handle);
* back edges try structured "bus routes" that run along a corridor above or
* below every card before swinging into the entry handle. Candidates are
* scored by residual crossings after detouring, and the cleanest wins.
* Back edges treat ALL cards as obstacles (including their own ends, which
* the line must loop around); forward edges exclude their own endpoints.
*/
export function routeEdge(input: EdgeRouteInput): EdgeRouteResult {
const {
id = "",
start,
end,
sourceDirection,
targetDirection,
nodes,
sourceId,
targetId,
waypoints,
stepPosition = 0.5,
stubLength = EDGE_STUB,
} = input;
const endpointFree = nodes.filter((r) => r.id !== sourceId && r.id !== targetId);
const isBackEdge = end.x < start.x;
const obstacles = isBackEdge ? nodes : endpointFree;
const lane = laneFor(id);
const margin = ROUTE_CLEARANCE + lane;
const sStub = stubFor(start, sourceDirection, stubLength);
const tStub = stubFor(end, targetDirection, stubLength);
const crossingCount = (points: RoutePoint[]) => {
let n = 0;
for (let i = 0; i < points.length - 1; i += 1) {
if (obstacles.some((r) => crosses(points[i], points[i + 1], r))) n += 1;
}
return n;
};
if (waypoints && waypoints.length > 0) {
const base = [start, ...waypoints, end];
return { points: routeAroundObstacles(base, obstacles, margin), base };
}
const candidates: RoutePoint[][] = [];
if (isBackEdge && obstacles.length > 0) {
const topY = Math.min(...obstacles.map((r) => r.y)) - ROUTE_CLEARANCE - lane;
const botY = Math.max(...obstacles.map((r) => r.y + r.height)) + ROUTE_CLEARANCE + lane;
const bus = (y: number): RoutePoint[] => [
start,
sStub,
{ x: sStub.x, y },
{ x: tStub.x, y },
tStub,
end,
];
candidates.push(bus(topY), bus(botY), [start, sStub, tStub, end]);
} else if (isBackEdge) {
candidates.push([start, sStub, tStub, end]);
} else {
const stepX = sStub.x + (tStub.x - sStub.x) * stepPosition;
candidates.push(
[start, sStub, { x: stepX, y: sStub.y }, { x: stepX, y: tStub.y }, tStub, end],
[start, sStub, tStub, end],
);
}
let best: RoutePoint[] | null = null;
let bestBase = candidates[0];
let bestScore = Number.POSITIVE_INFINITY;
for (const candidate of candidates) {
const cleaned = routeAroundObstacles(candidate, obstacles, margin);
const score = crossingCount(cleaned);
if (score < bestScore) {
best = cleaned;
bestBase = candidate;
bestScore = score;
}
if (score === 0) break;
}
return { points: best ?? [start, end], base: bestBase };
}