/** * Keeps an edge out of every node box (FZ-9208). * * React Flow's path builders see the two port points and nothing else, so a * backward edge (target left of its source) bends out and cuts back across * whatever sits between, and a smoothstep's middle run lands on whichever node * border happens to sit at the midpoint. Edges paint under nodes, so both read * as a line that vanishes into one box and reappears out of another. * * The router keeps React Flow's own path whenever it stays `clearance` away * from every box outside the port stubs, so the common forward edge looks * exactly as before. Only a path that intrudes is replaced, by an orthogonal * route found with A* over the gaps between the inflated boxes, drawn in the * kind's own corner style. * * Pure: no DOM, no React, no `@xyflow`, so it runs in vitest under Node. */ import type { Rect } from "../model/document"; import { buildSpatialHash } from "../interaction/spatialHash"; import type { SpatialHash } from "../interaction/spatialHash"; import type { EdgePathKind } from "./edgeStyle"; /** * Flow units between an edge and any node box it passes. Main's rows are 24 * apart, so this leaves an 8-unit channel down the middle of the tightest gap * the demo graphs lay out. */ export const edgeClearance = 8; export interface EdgeObstacle extends Rect { readonly id: string; } /** A graph edge by its two node ids. */ export interface EdgeLink { readonly source: string; readonly target: string; } export interface EdgeObstacles { readonly boxes: readonly EdgeObstacle[]; readonly clearance: number; /** * Every edge in the graph. With them, edges that cross the same gap between * two ranks get tracks of their own instead of all taking the gap's middle * (FZ-9291). Without them each edge is routed as if it were alone. */ readonly links?: readonly EdgeLink[]; } export type EdgeSide = "left" | "right" | "top" | "bottom"; export interface EdgeEnds { readonly sourceX: number; readonly sourceY: number; readonly targetX: number; readonly targetY: number; readonly sourceSide: EdgeSide; readonly targetSide: EdgeSide; } interface Point { readonly x: number; readonly y: number; } const directions: Record = { left: { x: -1, y: 0 }, right: { x: 1, y: 0 }, top: { x: 0, y: -1 }, bottom: { x: 0, y: 1 }, }; /** Corner radius per path shape, so a detour still reads as its kind. */ const cornerRadius: Record = { bezier: 24, smoothstep: 5, step: 0, straight: 0, }; const indexes = new WeakMap(); function indexFor(boxes: readonly EdgeObstacle[]): SpatialHash { let index = indexes.get(boxes); if (!index) { index = buildSpatialHash(boxes.map((box) => ({ id: box.id, rect: box }))); indexes.set(boxes, index); } return index; } function boxesNear(obstacles: EdgeObstacles, area: Rect): EdgeObstacle[] { const byId = new Map(obstacles.boxes.map((box) => [box.id, box])); const found: EdgeObstacle[] = []; for (const item of indexFor(obstacles.boxes).query(area)) { const box = byId.get(item.id); if (box) found.push(box); } return found; } function tokens(d: string): (string | number)[] { const out: (string | number)[] = []; for (const part of d.split(/([MLQCZ])/i)) { if (/^[MLQCZ]$/i.test(part)) { out.push(part.toUpperCase()); continue; } for (const value of part.match(/-?(?=\.?\d)\d*\.?\d*(?:e[-+]?\d+)?/gi) ?? []) out.push(Number(value)); } return out; } /** Points along an absolute M/L/Q/C path, the commands React Flow writes. */ export function samplePath(d: string): Point[] { const list = tokens(d); const points: Point[] = []; let at: Point = { x: 0, y: 0 }; let command = "M"; let index = 0; const take = (): number => { const value = list[index]; index += 1; return typeof value === "number" ? value : Number.NaN; }; while (index < list.length) { if (typeof list[index] === "string") { command = list[index] as string; index += 1; if (command === "Z") continue; } if (command === "M") { at = { x: take(), y: take() }; points.push(at); command = "L"; } else if (command === "L") { at = sampleLine(points, at, { x: take(), y: take() }); } else if (command === "Q") { at = sampleQuadratic(points, at, { x: take(), y: take() }, { x: take(), y: take() }); } else if (command === "C") { at = sampleCubic( points, at, { x: take(), y: take() }, { x: take(), y: take() }, { x: take(), y: take() }, ); } else { return points; } } return points; } function sampleLine(points: Point[], at: Point, to: Point): Point { const steps = Math.max(1, Math.ceil(Math.hypot(to.x - at.x, to.y - at.y) / 4)); for (let step = 1; step <= steps; step += 1) { const t = step / steps; points.push({ x: at.x + (to.x - at.x) * t, y: at.y + (to.y - at.y) * t }); } return to; } function sampleQuadratic(points: Point[], at: Point, control: Point, to: Point): Point { for (let step = 1; step <= 8; step += 1) { const t = step / 8; const u = 1 - t; points.push({ x: u * u * at.x + 2 * u * t * control.x + t * t * to.x, y: u * u * at.y + 2 * u * t * control.y + t * t * to.y, }); } return to; } function sampleCubic(points: Point[], at: Point, first: Point, second: Point, to: Point): Point { const steps = Math.max(16, Math.ceil(Math.hypot(to.x - at.x, to.y - at.y) / 4)); for (let step = 1; step <= steps; step += 1) { const t = step / steps; const u = 1 - t; points.push({ x: u * u * u * at.x + 3 * u * u * t * first.x + 3 * u * t * t * second.x + t * t * t * to.x, y: u * u * u * at.y + 3 * u * u * t * first.y + 3 * u * t * t * second.y + t * t * t * to.y, }); } return to; } function distanceToBox(point: Point, box: Rect): number { const dx = Math.max(box.x - point.x, 0, point.x - (box.x + box.width)); const dy = Math.max(box.y - point.y, 0, point.y - (box.y + box.height)); return Math.hypot(dx, dy); } /** The box the port sits in or on, if any: a port is drawn on its own node. */ function ownBox(point: Point, boxes: readonly EdgeObstacle[]): EdgeObstacle | undefined { let best: EdgeObstacle | undefined; let bestDistance = 0.5; for (const box of boxes) { const distance = distanceToBox(point, box); if (distance <= bestDistance) { best = box; bestDistance = distance; } } return best; } /** How far the port point sits inside its own frame, measured along its side. */ function depth(point: Point, side: EdgeSide, box: EdgeObstacle | undefined): number { if (!box) return 0; switch (side) { case "right": return Math.max(0, box.x + box.width - point.x); case "left": return Math.max(0, point.x - box.x); case "bottom": return Math.max(0, box.y + box.height - point.y); case "top": return Math.max(0, point.y - box.y); } } function bounds(points: readonly Point[], pad: number): Rect { let minX = Infinity; let minY = Infinity; let maxX = -Infinity; let maxY = -Infinity; for (const point of points) { minX = Math.min(minX, point.x); minY = Math.min(minY, point.y); maxX = Math.max(maxX, point.x); maxY = Math.max(maxY, point.y); } return { x: minX - pad, y: minY - pad, width: maxX - minX + pad * 2, height: maxY - minY + pad * 2, }; } /** * True when a sample outside either port stub comes within `clearance` of a * box. The stub is the stretch from the port to `clearance` past its own frame. */ export function pathIntrudes(d: string, ends: EdgeEnds, obstacles: EdgeObstacles): boolean { const { clearance } = obstacles; const from = { x: ends.sourceX, y: ends.sourceY }; const to = { x: ends.targetX, y: ends.targetY }; const points = samplePath(d); if (points.length === 0) return false; const near = boxesNear(obstacles, bounds(points, clearance)); const fromStub = depth(from, ends.sourceSide, ownBox(from, near)) + clearance; const toStub = depth(to, ends.targetSide, ownBox(to, near)) + clearance; for (const point of points) { if (Math.hypot(point.x - from.x, point.y - from.y) <= fromStub) continue; if (Math.hypot(point.x - to.x, point.y - to.y) <= toStub) continue; for (const box of near) { if (distanceToBox(point, box) < clearance - 0.25) return true; } } return false; } interface Inflated { readonly left: number; readonly right: number; readonly top: number; readonly bottom: number; } function inflate(box: Rect, by: number): Inflated { return { left: box.x - by, right: box.x + box.width + by, top: box.y - by, bottom: box.y + box.height + by, }; } function strictlyInside(x: number, y: number, rect: Inflated): boolean { return x > rect.left && x < rect.right && y > rect.top && y < rect.bottom; } /** Sorted unique values plus the midpoint of every gap, so a run can take the middle of a channel. */ function lines(values: number[]): number[] { const sorted = [...new Set(values.map((value) => Math.round(value * 1000) / 1000))].sort( (a, b) => a - b, ); const out: number[] = []; for (let index = 0; index < sorted.length; index += 1) { out.push(sorted[index]); const next = sorted[index + 1]; if (next !== undefined && next - sorted[index] > 1) out.push((sorted[index] + next) / 2); } return out; } /** Exit point: `clearance` past the port's own frame, straight out of its side. */ function stubEnd( point: Point, side: EdgeSide, box: EdgeObstacle | undefined, clearance: number, ): Point { const reach = depth(point, side, box) + clearance; const dir = directions[side]; return { x: point.x + dir.x * reach, y: point.y + dir.y * reach }; } class Heap { private readonly items: { key: number; cost: number }[] = []; get size(): number { return this.items.length; } push(key: number, cost: number): void { const items = this.items; items.push({ key, cost }); let index = items.length - 1; while (index > 0) { const parent = (index - 1) >> 1; if (items[parent].cost <= items[index].cost) break; [items[parent], items[index]] = [items[index], items[parent]]; index = parent; } } pop(): { key: number; cost: number } | undefined { const items = this.items; const top = items[0]; const last = items.pop(); if (items.length > 0 && last) { items[0] = last; let index = 0; for (;;) { const left = index * 2 + 1; const right = left + 1; let smallest = index; if (left < items.length && items[left].cost < items[smallest].cost) smallest = left; if (right < items.length && items[right].cost < items[smallest].cost) smallest = right; if (smallest === index) break; [items[smallest], items[index]] = [items[index], items[smallest]]; index = smallest; } } return top; } } const stepX = [1, 0, -1, 0]; const stepY = [0, 1, 0, -1]; function directionIndex(side: EdgeSide): number { const dir = directions[side]; return stepX.findIndex((dx, index) => dx === dir.x && stepY[index] === dir.y); } /** * The orthogonal route from one stub end to the other through `boxes` * inflated by `clearance`, fewest turns weighed against length. `null` when * the region holds no such route. */ function orthogonalRoute( start: Point, startDirection: number, goal: Point, goalDirection: number, boxes: readonly EdgeObstacle[], clearance: number, area: Rect, ): Point[] | null { const grid = routeGrid(start, goal, boxes, clearance, area); const startX = gridIndex(grid.xs, start.x); const startY = gridIndex(grid.ys, start.y); const goalX = gridIndex(grid.xs, goal.x); const goalY = gridIndex(grid.ys, goal.y); if (startX < 0 || startY < 0 || goalX < 0 || goalY < 0) return null; if (!gridFree(grid, startX, startY) || !gridFree(grid, goalX, goalY)) return null; const search: RouteSearch = { grid, goal, goalX, goalY, goalDirection, turn: clearance * 4, best: new Map(), from: new Map(), heap: new Heap(), }; const first = gridKey(grid, startX, startY, startDirection); const reached = searchRoute(search, first, startX, startY); if (reached === undefined) return null; return traceRoute(grid, search.from, reached); } interface RouteGrid { readonly xs: readonly number[]; readonly ys: readonly number[]; readonly rects: readonly Inflated[]; } interface RouteSearch { readonly grid: RouteGrid; readonly goal: Point; readonly goalX: number; readonly goalY: number; readonly goalDirection: number; readonly turn: number; readonly best: Map; readonly from: Map; readonly heap: Heap; } interface GridNode { readonly key: number; readonly ix: number; readonly iy: number; readonly dir: number; readonly cost: number; } function routeGrid( start: Point, goal: Point, boxes: readonly EdgeObstacle[], clearance: number, area: Rect, ): RouteGrid { const rects = boxes.map((box) => inflate(box, clearance)); const xs = lines([ start.x, goal.x, area.x, area.x + area.width, ...rects.flatMap((r) => [r.left, r.right]), ]); const ys = lines([ start.y, goal.y, area.y, area.y + area.height, ...rects.flatMap((r) => [r.top, r.bottom]), ]); return { xs, ys, rects }; } function gridIndex(values: readonly number[], value: number): number { return values.indexOf(Math.round(value * 1000) / 1000); } function gridFree(grid: RouteGrid, ix: number, iy: number): boolean { return grid.rects.every((rect) => !strictlyInside(grid.xs[ix], grid.ys[iy], rect)); } function gridOpen(grid: RouteGrid, ax: number, ay: number, bx: number, by: number): boolean { const { xs, ys } = grid; const minX = Math.min(xs[ax], xs[bx]); const maxX = Math.max(xs[ax], xs[bx]); const minY = Math.min(ys[ay], ys[by]); const maxY = Math.max(ys[ay], ys[by]); return grid.rects.every((rect) => { if (minY === maxY) return !(minY > rect.top && minY < rect.bottom && maxX > rect.left && minX < rect.right); return !(minX > rect.left && minX < rect.right && maxY > rect.top && minY < rect.bottom); }); } function canStep(grid: RouteGrid, ix: number, iy: number, nx: number, ny: number): boolean { if (nx < 0 || ny < 0 || nx >= grid.xs.length || ny >= grid.ys.length) return false; return gridFree(grid, nx, ny) && gridOpen(grid, ix, iy, nx, ny); } function gridKey(grid: RouteGrid, ix: number, iy: number, dir: number): number { return (iy * grid.xs.length + ix) * 4 + dir; } function gridCell(grid: RouteGrid, key: number): { ix: number; iy: number; dir: number } { const columns = grid.xs.length; const dir = key % 4; const cell = (key - dir) / 4; const ix = cell % columns; return { ix, iy: (cell - ix) / columns, dir }; } function routeHeuristic(search: RouteSearch, ix: number, iy: number): number { return ( Math.abs(search.grid.xs[ix] - search.goal.x) + Math.abs(search.grid.ys[iy] - search.goal.y) ); } function bendCost(search: RouteSearch, dir: number, next: number, nx: number, ny: number): number { const atGoal = nx === search.goalX && ny === search.goalY; return ( (next === dir ? 0 : search.turn) + (atGoal && next !== search.goalDirection ? search.turn : 0) ); } function searchRoute( search: RouteSearch, first: number, startX: number, startY: number, ): number | undefined { const { best, heap } = search; best.set(first, 0); heap.push(first, routeHeuristic(search, startX, startY)); let budget = 200_000; while (heap.size > 0 && budget > 0) { budget -= 1; const current = heap.pop(); if (!current) break; const { ix, iy, dir } = gridCell(search.grid, current.key); const cost = best.get(current.key) ?? Infinity; if (current.cost - routeHeuristic(search, ix, iy) > cost + 1e-6) continue; if (ix === search.goalX && iy === search.goalY) return current.key; relaxNeighbours(search, { key: current.key, ix, iy, dir, cost }); } return undefined; } function relaxNeighbours(search: RouteSearch, node: GridNode): void { const { grid, best, from, heap } = search; for (let next = 0; next < 4; next += 1) { if (next === (node.dir + 2) % 4) continue; const nx = node.ix + stepX[next]; const ny = node.iy + stepY[next]; if (!canStep(grid, node.ix, node.iy, nx, ny)) continue; const length = Math.abs(grid.xs[nx] - grid.xs[node.ix]) + Math.abs(grid.ys[ny] - grid.ys[node.iy]); const nextKey = gridKey(grid, nx, ny, next); const nextCost = node.cost + length + bendCost(search, node.dir, next, nx, ny); if (nextCost < (best.get(nextKey) ?? Infinity)) { best.set(nextKey, nextCost); from.set(nextKey, node.key); heap.push(nextKey, nextCost + routeHeuristic(search, nx, ny)); } } } function traceRoute(grid: RouteGrid, from: Map, reached: number): Point[] { const route: Point[] = []; for (let at: number | undefined = reached; at !== undefined; at = from.get(at)) { const { ix, iy } = gridCell(grid, at); route.push({ x: grid.xs[ix], y: grid.ys[iy] }); } return route.reverse(); } function simplify(points: readonly Point[]): Point[] { const out: Point[] = []; for (const point of points) { const last = out[out.length - 1]; if (last && Math.abs(last.x - point.x) < 1e-6 && Math.abs(last.y - point.y) < 1e-6) continue; const before = out[out.length - 2]; if (before && last) { const sameX = Math.abs(before.x - last.x) < 1e-6 && Math.abs(last.x - point.x) < 1e-6; const sameY = Math.abs(before.y - last.y) < 1e-6 && Math.abs(last.y - point.y) < 1e-6; if (sameX || sameY) out.pop(); } out.push(point); } return out; } function format(value: number): string { return String(Math.round(value * 1000) / 1000); } interface Corner { readonly enter: Point; readonly corner: Point; readonly leave: Point; } /** Corner `index` of `points` rounded by `radius`, capped at half of either leg. */ function roundCorner(points: readonly Point[], index: number, radius: number): Corner | null { const before = points[index - 1]; const corner = points[index]; const after = points[index + 1]; const inLength = Math.hypot(corner.x - before.x, corner.y - before.y); const outLength = Math.hypot(after.x - corner.x, after.y - corner.y); const r = Math.min(radius, inLength / 2, outLength / 2); if (r <= 0) return null; return { enter: { x: corner.x - ((corner.x - before.x) / inLength) * r, y: corner.y - ((corner.y - before.y) / inLength) * r, }, corner, leave: { x: corner.x + ((after.x - corner.x) / outLength) * r, y: corner.y + ((after.y - corner.y) / outLength) * r, }, }; } function cornerPath({ enter, corner, leave }: Corner): string { return `M${format(enter.x)},${format(enter.y)} Q${format(corner.x)},${format(corner.y)} ${format(leave.x)},${format(leave.y)}`; } /** * The largest radius up to `radius` that rounds corner `index` without the * curve coming inside the clearance, so a tight corridor gets a tighter bend. */ function fittedRadius( points: readonly Point[], index: number, radius: number, ends: EdgeEnds, obstacles: EdgeObstacles, ): number { const fits = (r: number): boolean => { const corner = roundCorner(points, index, r); return !corner || !pathIntrudes(cornerPath(corner), ends, obstacles); }; if (fits(radius)) return radius; let low = 0; let high = radius; for (let step = 0; step < 12; step += 1) { const middle = (low + high) / 2; if (fits(middle)) low = middle; else high = middle; } return low; } /** A polyline with corner `index` rounded by `radii[index]`. */ function polylinePath(points: readonly Point[], radii: readonly number[]): string { let d = `M${format(points[0].x)},${format(points[0].y)}`; for (let index = 1; index < points.length - 1; index += 1) { const corner = roundCorner(points, index, radii[index] ?? 0); if (!corner) { d += ` L${format(points[index].x)},${format(points[index].y)}`; continue; } d += ` L${format(corner.enter.x)},${format(corner.enter.y)} Q${format(corner.corner.x)},${format(corner.corner.y)} ${format(corner.leave.x)},${format(corner.leave.y)}`; } const last = points[points.length - 1]; return `${d} L${format(last.x)},${format(last.y)}`; } function midpoint(points: readonly Point[]): Point { let total = 0; for (let index = 1; index < points.length; index += 1) { total += Math.hypot( points[index].x - points[index - 1].x, points[index].y - points[index - 1].y, ); } let left = total / 2; for (let index = 1; index < points.length; index += 1) { const a = points[index - 1]; const b = points[index]; const length = Math.hypot(b.x - a.x, b.y - a.y); if (length >= left && length > 0) { const t = left / length; return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }; } left -= length; } return points[0]; } /** * A route around the boxes, as `[d, labelX, labelY]`, or `null` when there is * none in reach, in which case the caller keeps React Flow's path. */ export function routeAroundBoxes( path: EdgePathKind, ends: EdgeEnds, obstacles: EdgeObstacles, ): [d: string, labelX: number, labelY: number] | null { const { clearance } = obstacles; const from = { x: ends.sourceX, y: ends.sourceY }; const to = { x: ends.targetX, y: ends.targetY }; const largest = obstacles.boxes.reduce((size, box) => Math.max(size, box.width, box.height), 0); for (const reach of [1, 3]) { const area = bounds([from, to], (largest + clearance * 2) * reach); const near = boxesNear(obstacles, area); const start = stubEnd(from, ends.sourceSide, ownBox(from, near), clearance); const goal = stubEnd(to, ends.targetSide, ownBox(to, near), clearance); const inner = orthogonalRoute( start, directionIndex(ends.sourceSide), goal, (directionIndex(ends.targetSide) + 2) % 4, near, clearance, area, ); if (!inner) continue; const points = simplify([from, ...inner, to]); const label = midpoint(points); // A rounded corner cuts inside its turn, toward the box it turns around, // so each corner gets the largest bend that keeps the clearance. const radius = cornerRadius[path]; const radii = points.map((_, index) => index === 0 || index === points.length - 1 ? 0 : fittedRadius(points, index, radius, ends, obstacles), ); return [polylinePath(points, radii), label.x, label.y]; } return null; } /** * What one track across a gap carries (FZ-9291). `target`: every edge into * the same node shares a trunk, so a run leads to exactly one node. `edge`: * every edge gets a lane of its own. */ type TrackSharing = "target" | "edge"; const trackSharing: TrackSharing = "target"; /** Edge coordinates turned so the source side points down: `u` across the gap, `v` from source to target. */ interface Frame { readonly local: (point: Point) => Point; readonly world: (point: Point) => Point; } const frames: Record = { bottom: { local: ({ x, y }) => ({ x, y }), world: ({ x, y }) => ({ x, y }), }, top: { local: ({ x, y }) => ({ x, y: -y }), world: ({ x, y }) => ({ x, y: -y }), }, right: { local: ({ x, y }) => ({ x: y, y: x }), world: ({ x, y }) => ({ x: y, y: x }), }, left: { local: ({ x, y }) => ({ x: y, y: -x }), world: ({ x, y }) => ({ x: -y, y: x }), }, }; const opposite: Record = { left: "right", right: "left", top: "bottom", bottom: "top", }; interface Span { readonly u0: number; readonly u1: number; readonly v0: number; readonly v1: number; } function localSpan(box: Rect, frame: Frame): Span { const a = frame.local({ x: box.x, y: box.y }); const b = frame.local({ x: box.x + box.width, y: box.y + box.height }); return { u0: Math.min(a.x, b.x), u1: Math.max(a.x, b.x), v0: Math.min(a.y, b.y), v1: Math.max(a.y, b.y), }; } function trackKey(sharing: TrackSharing, link: EdgeLink): string { return sharing === "target" ? link.target : `${link.source}\u0000${link.target}`; } interface Rank { readonly v0: number; readonly v1: number; readonly spans: Span[]; } /** Boxes whose `v` extents overlap form one rank, ordered from source side to target side. */ function ranksOf(spans: readonly Span[]): Rank[] { const sorted = [...spans].sort((a, b) => a.v0 - b.v0); const ranks: { v0: number; v1: number; spans: Span[] }[] = []; for (const span of sorted) { const last = ranks[ranks.length - 1]; if (last && span.v0 < last.v1) { last.v1 = Math.max(last.v1, span.v1); last.spans.push(span); } else ranks.push({ v0: span.v0, v1: span.v1, spans: [span] }); } for (const rank of ranks) rank.spans.sort((a, b) => a.u0 - b.u0); return ranks; } /** The open `u` intervals a vertical run can take through a rank and keep the clearance. */ function channels(rank: Rank, clearance: number): [number, number][] { const open: [number, number][] = []; let from = Number.NEGATIVE_INFINITY; for (const span of rank.spans) { const to = span.u0 - clearance; if (to > from) open.push([from, to]); from = Math.max(from, span.u1 + clearance); } open.push([from, Number.POSITIVE_INFINITY]); return open; } /** * Where a link crosses one rank it skips: held at `goal` when its channel * reaches the target's line, which saves a bend, else the channel nearest * `ideal`. The source's line isn't held: a port can sit off its box's centre, * so holding it would put a jog at the source. */ function virtualPoint( open: readonly [number, number][], ideal: number, goal: number, ): { u: number; channel: number } { const held = open.findIndex(([lo, hi]) => lo <= goal && goal <= hi); if (held >= 0) return { u: goal, channel: held }; let best = { u: ideal, channel: 0, cost: Number.POSITIVE_INFINITY }; open.forEach(([lo, hi], channel) => { const u = Math.min(Math.max(ideal, lo), hi); const cost = Math.abs(u - ideal); if (cost < best.cost) best = { u, channel, cost }; }); return { u: best.u, channel: best.channel }; } /** A link's way across the gaps, in the source side's frame: one `v` per gap and the `u` it holds through each rank it skips. */ interface Course { readonly vs: number[]; readonly us: number[]; readonly open: [number, number][]; } interface Group { readonly key: string; readonly lone: boolean; u0: number; u1: number; } function linkKey(link: EdgeLink): string { return `${link.source}\u0000${link.target}`; } interface Passing { readonly link: string; readonly rank: number; readonly slot: number; readonly u: number; readonly channel: number; } interface Piece { readonly gap: number; readonly key: string; } interface Layers { readonly spans: Map; readonly ranks: Rank[]; readonly rankOf: Map; readonly open: [number, number][][]; } interface LinkEnds { readonly source: Span; readonly target: Span; readonly rs: number; readonly rt: number; } interface TrackPlan { readonly gaps: Map>; readonly pieces: Map; readonly passing: Passing[]; readonly virtual: Map; readonly channelOf: Map; } function layersOf(boxes: readonly EdgeObstacle[], side: EdgeSide, clearance: number): Layers { const frame = frames[side]; const spans = new Map(boxes.map((box) => [box.id, localSpan(box, frame)])); const ranks = ranksOf([...spans.values()]); const rankOf = new Map(); ranks.forEach((rank, index) => { for (const span of rank.spans) rankOf.set(span, index); }); return { spans, ranks, rankOf, open: ranks.map((rank) => channels(rank, clearance)) }; } function forwardEnds(link: EdgeLink, layers: Layers): LinkEnds | undefined { const source = layers.spans.get(link.source); const target = layers.spans.get(link.target); if (!source || !target) return undefined; const rs = layers.rankOf.get(source)!; const rt = layers.rankOf.get(target)!; if (rt <= rs) return undefined; return { source, target, rs, rt }; } function virtualCourse( id: string, { source, target, rs, rt }: LinkEnds, open: readonly [number, number][][], ): { us: number[]; passes: Passing[] } { const sourceU = (source.u0 + source.u1) / 2; const targetU = (target.u0 + target.u1) / 2; const us = [sourceU]; const passes: Passing[] = []; for (let rank = rs + 1; rank < rt; rank += 1) { const ideal = sourceU + ((targetU - sourceU) * (rank - rs)) / (rt - rs); const at = virtualPoint(open[rank], ideal, targetU); us.push(at.u); passes.push({ link: id, rank, slot: us.length - 1, ...at }); } us.push(targetU); return { us, passes }; } function groupsAt(gaps: Map>, gap: number): Map { let groups = gaps.get(gap); if (!groups) { groups = new Map(); gaps.set(gap, groups); } return groups; } function widenGroup( groups: Map, key: string, lone: boolean, a: number, b: number, ): void { const group = groups.get(key); if (group) { group.u0 = Math.min(group.u0, a, b); group.u1 = Math.max(group.u1, a, b); } else groups.set(key, { key, lone, u0: Math.min(a, b), u1: Math.max(a, b) }); } function placePieces( gaps: Map>, link: EdgeLink, id: string, us: readonly number[], { rs, rt }: LinkEnds, sharing: TrackSharing, ): Piece[] { const own: Piece[] = []; for (let gap = rs; gap < rt; gap += 1) { const last = gap === rt - 1; const key = last ? trackKey(sharing, link) : `${id}\u0000${gap}`; own.push({ gap, key }); widenGroup(groupsAt(gaps, gap), key, rt - rs === 1, us[gap - rs], us[gap - rs + 1]); } return own; } function collectPieces( links: readonly EdgeLink[], layers: Layers, sharing: TrackSharing, ): TrackPlan { const plan: TrackPlan = { gaps: new Map(), pieces: new Map(), passing: [], virtual: new Map(), channelOf: new Map(), }; for (const link of links) { const ends = forwardEnds(link, layers); if (!ends) continue; const id = linkKey(link); if (plan.pieces.has(id)) continue; const { us, passes } = virtualCourse(id, ends, layers.open); plan.passing.push(...passes); plan.virtual.set(id, us); plan.channelOf.set( id, passes.map((pass) => layers.open[pass.rank][pass.channel]), ); plan.pieces.set(id, placePieces(plan.gaps, link, id, us, ends, sharing)); } return plan; } function spreadChannel( group: readonly Passing[], open: readonly [number, number][][], virtual: Map, clearance: number, ): void { if (group.length < 2) return; const [lo, hi] = open[group[0].rank][group[0].channel]; const sorted = [...group].sort((a, b) => a.u - b.u || a.link.localeCompare(b.link)); const crowded = sorted.some( (pass, index) => index > 0 && pass.u - sorted[index - 1].u < clearance, ); if (!crowded) return; const width = Number.isFinite(lo) && Number.isFinite(hi) ? hi - lo : clearance * (group.length + 1); let base = sorted[0].u; if (Number.isFinite(lo)) base = lo; else if (Number.isFinite(hi)) base = hi - width; const pitch = width / (group.length + 1); sorted.forEach((pass, index) => { virtual.get(pass.link)![pass.slot] = base + pitch * (index + 1); }); } function spreadChannels( passing: readonly Passing[], open: readonly [number, number][][], virtual: Map, clearance: number, ): void { // Links through one channel of one rank take evenly spaced lanes in it. const byChannel = new Map(); for (const pass of passing) { const key = `${pass.rank}:${pass.channel}`; byChannel.set(key, [...(byChannel.get(key) ?? []), pass]); } for (const group of byChannel.values()) spreadChannel(group, open, virtual, clearance); } function conflictSets(list: readonly Group[], clearance: number): Group[][] { const parent = list.map((_, index) => index); const root = (index: number): number => { let at = index; while (parent[at] !== at) at = parent[at]; return at; }; for (let a = 0; a < list.length; a += 1) for (let b = a + 1; b < list.length; b += 1) if (list[a].u0 <= list[b].u1 + clearance && list[b].u0 <= list[a].u1 + clearance) parent[root(b)] = root(a); const sets = new Map(); for (let index = 0; index < list.length; index += 1) { const at = root(index); sets.set(at, [...(sets.get(at) ?? []), list[index]]); } return [...sets.values()]; } function lanesOf( members: readonly Group[], clearance: number, ): { lane: Map; count: number } { const sorted = [...members].sort((a, b) => a.u0 - b.u0 || a.key.localeCompare(b.key)); const ends: number[] = []; const lane = new Map(); for (const group of sorted) { let free = ends.findIndex((end) => end + clearance < group.u0); if (free < 0) { free = ends.length; ends.push(group.u1); } else ends[free] = group.u1; lane.set(group.key, free); } return { lane, count: ends.length }; } function levelGap( gap: number, groups: Map, ranks: readonly Rank[], clearance: number, levels: Map, ): void { const lo = ranks[gap].v1 + clearance; const hi = ranks[gap + 1].v0 - clearance; if (lo >= hi) return; for (const members of conflictSets([...groups.values()], clearance)) { const { lane, count } = lanesOf(members, clearance); if (count < 2 && members.every((group) => group.lone)) continue; const pitch = (hi - lo) / (count + 1); for (const [key, index] of lane) levels.set(`${gap}\u0000${key}`, lo + pitch * (index + 1)); } } function levelsOf( gaps: Map>, ranks: readonly Rank[], clearance: number, ): Map { const levels = new Map(); for (const [gap, groups] of gaps) levelGap(gap, groups, ranks, clearance, levels); return levels; } function coursesOf(plan: TrackPlan, levels: Map): Map { const courses = new Map(); for (const [id, own] of plan.pieces) { const vs = own.map(({ gap, key }) => levels.get(`${gap}\u0000${key}`)); if (vs.some((v) => v === undefined)) continue; courses.set(id, { vs: vs as number[], us: plan.virtual.get(id)!.slice(1, -1), open: plan.channelOf.get(id) ?? [], }); } return courses; } /** * Every link that shares a gap with another, or skips a rank, with its course. * A link that crosses its gap alone gets none and keeps the ordinary route. * * Like a layered layout's dummy nodes, a link that skips ranks gets a virtual * point in each rank it crosses, in the open channel between that rank's * boxes, so it never runs through a node; each piece then crosses one gap * like any other edge. In each gap, groups whose spans overlap are one * conflict set; interval colouring gives the fewest tracks, evenly spaced. */ function planTracks( links: readonly EdgeLink[], boxes: readonly EdgeObstacle[], side: EdgeSide, clearance: number, sharing: TrackSharing, ): Map { const layers = layersOf(boxes, side, clearance); const plan = collectPieces(links, layers, sharing); spreadChannels(plan.passing, layers.open, plan.virtual, clearance); return coursesOf(plan, levelsOf(plan.gaps, layers.ranks, clearance)); } const plans = new WeakMap< readonly EdgeLink[], WeakMap>> >(); function tracksFor(obstacles: EdgeObstacles, side: EdgeSide): Map | undefined { const { links, boxes, clearance } = obstacles; if (!links || links.length === 0) return undefined; let byBoxes = plans.get(links); if (!byBoxes) { byBoxes = new WeakMap(); plans.set(links, byBoxes); } let bySide = byBoxes.get(boxes); if (!bySide) { bySide = new Map(); byBoxes.set(boxes, bySide); } const key = `${side}:${clearance}`; let tracks = bySide.get(key); if (!tracks) { tracks = planTracks(links, boxes, side, clearance, trackSharing); bySide.set(key, tracks); } return tracks; } /** * A step or smoothstep edge on its own tracks across the gaps it crosses, as * `[d, labelX, labelY]`, through a virtual point in each rank it skips. * `null` when the edge crosses its gap alone, has no course, or a run would * come inside the clearance, in which case the caller routes it as before. */ export function routeOnTrack( path: EdgePathKind, ends: EdgeEnds, obstacles: EdgeObstacles, ): [d: string, labelX: number, labelY: number] | null { if (path !== "smoothstep" && path !== "step") return null; if (ends.targetSide !== opposite[ends.sourceSide]) return null; const courses = tracksFor(obstacles, ends.sourceSide); if (!courses || courses.size === 0) return null; const from = { x: ends.sourceX, y: ends.sourceY }; const to = { x: ends.targetX, y: ends.targetY }; const source = ownBox(from, boxesNear(obstacles, bounds([from], 1))); const target = ownBox(to, boxesNear(obstacles, bounds([to], 1))); if (!source || !target) return null; const course = courses.get(linkKey({ source: source.id, target: target.id })); if (!course) return null; const frame = frames[ends.sourceSide]; const a = frame.local(from); const b = frame.local(to); const { vs, us } = course; const { clearance } = obstacles; if (!(a.y < vs[0] && vs[vs.length - 1] < b.y)) return null; if (us.length === 0 && Math.abs(a.x - b.x) < 0.5) return null; // A port can sit off its box's centre. A virtual point planned a hair away // from the port's own line takes that line when its channel allows, so the // edge doesn't jog just before it leaves or lands. const snapped = us.map((u, index) => { const [lo, hi] = course.open[index] ?? [u, u]; for (const line of [index === us.length - 1 ? b.x : undefined, index === 0 ? a.x : undefined]) if (line !== undefined && Math.abs(line - u) < clearance * 2 && lo <= line && line <= hi) return line; return u; }); const local = [a]; const holds = [a.x, ...snapped, b.x]; vs.forEach((v, gap) => { local.push({ x: holds[gap], y: v }, { x: holds[gap + 1], y: v }); }); local.push(b); const points = simplify(local.map(frame.world)); const radius = cornerRadius[path]; const radii = points.map((_, index) => index === 0 || index === points.length - 1 ? 0 : fittedRadius(points, index, radius, ends, obstacles), ); const d = polylinePath(points, radii); if (pathIntrudes(d, ends, obstacles)) return null; const label = midpoint(points); return [d, label.x, label.y]; }