logigate/app/lib/logic/routing.ts

1121 lines
42 KiB
TypeScript
Raw Permalink Normal View History

// Routes all wires and cables of a circuit so that lines of different
// signals never run on top of (or right beside) each other, and nothing
// runs over or under a part.
//
// 1. Wires with hand-placed corners keep them. Every other wire uses its
// usual route if that is free. A wire of a signal that is already laid
// may branch off it instead, so one signal (a cable too) splits from one
// trunk. Otherwise the cheapest free alternative: another column for the
// vertical step, a detour, and last a search of the grid around parts.
// 2. Parts are walls with a margin around them; a line only touches a part
// where it ends on its pin. Cables count as wide as they are drawn.
// 3. Anything still sharing a line with another signal is drawn on its own
// parallel lane, spaced by the widths of the two.
// 4. Crossings between different signals get hops (bow, triangle, bridge,
// gap): the thinner line jumps over the wider one, as wide as it needs.
import { GRID, pinPos, routeWire, simplify, type Pt, type Shape } from './geometry'
import type { ComponentDef } from './types'
export interface RouteInput {
id: string
/** Wires with the same net (source pin) may share lines. */
net: string
a: Pt
b: Pt
pts?: Pt[]
/** Side the wire leaves the source (1 right, default) and arrives at the target from (-1 left, default). */
aFace?: 1 | -1
bFace?: 1 | -1
/** Half the drawn width in grid units: a wire is thin, a cable as wide as its sleeve. */
h?: number
}
export interface Box {
x: number
y: number
w: number
h: number
}
export interface Routed {
id: string
net: string
/** Whole-grid route: what dragging and corner handles work on. */
grid: Pt[]
/** Route as drawn, moved onto separate lanes where needed. */
draw: Pt[]
/** Half the drawn width in grid units. */
h: number
}
export interface Crossing {
/** Index of the routed wire that hops (the horizontal one). */
wire: number
/** Segment of `draw` the hop sits on. */
seg: number
x: number
}
const EPS = 1e-6
/** Space between two lines moved onto lanes beside each other. */
const LANE_GAP = 0.125
/** Half the width of a plain wire, in grid units. */
export const WIRE_H = 1 / GRID
/** Space two lines of different signals keep between their edges. */
const NEAR = 0.25
/** Space a line keeps from the parts it passes. */
const CLEAR = 0.2
/** Cost of a segment that runs through (or along) a part. */
const BODY = 5000
interface Seg {
lo: number
hi: number
net: string
h: number
}
/** Lines already taken, by row (horizontal) and column (vertical). */
class Occupancy {
rows = new Map<number, Seg[]>()
cols = new Map<number, Seg[]>()
/** The widest line so far, to know how far beside a line to look. */
hmax = WIRE_H
add(route: Pt[], net: string, h = WIRE_H) {
this.hmax = Math.max(this.hmax, h)
for (let i = 0; i < route.length - 1; i++) {
const [ax, ay] = route[i]!
const [bx, by] = route[i + 1]!
if (ay === by && ax !== bx) push(this.rows, ay, { lo: Math.min(ax, bx), hi: Math.max(ax, bx), net, h })
else if (ax === bx && ay !== by) push(this.cols, ax, { lo: Math.min(ay, by), hi: Math.max(ay, by), net, h })
}
}
/**
* Length that a segment (of half-width h) shares with lines of other nets:
* on its own line, or on a line so close beside it that the two would
* touch (a wide cable next to a wire or another cable).
*/
overlap(a: Pt, b: Pt, net: string, h = WIRE_H): number {
const horizontal = a[1] === b[1]
const c = horizontal ? a[1] : a[0]
const lo = horizontal ? Math.min(a[0], b[0]) : Math.min(a[1], b[1])
const hi = horizontal ? Math.max(a[0], b[0]) : Math.max(a[1], b[1])
const lines = horizontal ? this.rows : this.cols
const reach = Math.floor(h + this.hmax + NEAR)
let total = 0
for (let d = -reach; d <= reach; d++) {
const list = lines.get(c + d)
if (!list) continue
for (const s of list) {
if (s.net === net || (d !== 0 && Math.abs(d) >= h + s.h + NEAR)) continue
const o = Math.min(hi, s.hi) - Math.max(lo, s.lo)
// Touching end to end on one line counts too: it would read as one wire.
if (o > 0) total += o
else if (o === 0 && d === 0) total += 0.5
}
}
return total
}
/** A line of another net crosses this point (running through it, not ending there). */
crossedAt(x: number, y: number, net: string, vertical: boolean): boolean {
const list = vertical ? this.cols.get(x) : this.rows.get(y)
const at = vertical ? y : x
return !!list?.some(s => s.net !== net && at > s.lo + EPS && at < s.hi - EPS)
}
}
function push<T>(map: Map<number, T[]>, key: number, value: T) {
const list = map.get(key)
if (list) list.push(value)
else map.set(key, [value])
}
/** Node bodies bucketed by area, so a segment only checks the parts near it. */
class BodyIndex {
private cells = new Map<number, Box[]>()
private stamp = new Map<Box, number>()
private query = 0
private static SIZE = 4
private static key = (cx: number, cy: number) => (cx + 50_000) * 100_000 + cy + 50_000
constructor(boxes: Box[]) {
const S = BodyIndex.SIZE
for (const box of boxes) {
for (let cx = Math.floor(box.x / S); cx <= Math.floor((box.x + box.w) / S); cx++) {
for (let cy = Math.floor(box.y / S); cy <= Math.floor((box.y + box.h) / S); cy++) push(this.cells, BodyIndex.key(cx, cy), box)
}
}
}
/**
* Parts a segment (of half-width h) runs through or along: each part with a
* margin around it. An end on a pin (trimA, trimB) is let off that margin,
* since a line has to touch the part it plugs into.
*/
hits(a: Pt, b: Pt, h = WIRE_H, trimA = false, trimB = false): number {
const S = BodyIndex.SIZE
const c = h + CLEAR
let [ax, ay] = a
let [bx, by] = b
if (trimA || trimB) {
const t = c + 0.01
const len = Math.abs(bx - ax) + Math.abs(by - ay)
if (len <= (trimA ? t : 0) + (trimB ? t : 0)) return 0
const dx = Math.sign(bx - ax)
const dy = Math.sign(by - ay)
if (trimA) {
ax += dx * t
ay += dy * t
}
if (trimB) {
bx -= dx * t
by -= dy * t
}
}
const q = ++this.query
let n = 0
const lx = Math.min(ax, bx)
const hx = Math.max(ax, bx)
const ly = Math.min(ay, by)
const hy = Math.max(ay, by)
for (let cx = Math.floor((lx - c) / S); cx <= Math.floor((hx + c) / S); cx++) {
for (let cy = Math.floor((ly - c) / S); cy <= Math.floor((hy + c) / S); cy++) {
for (const box of this.cells.get(BodyIndex.key(cx, cy)) ?? []) {
if (this.stamp.get(box) === q) continue
this.stamp.set(box, q)
const x0 = box.x - c
const x1 = box.x + box.w + c
const y0 = box.y - c
const y1 = box.y + box.h + c
const hit = ly === hy ? ly > y0 && ly < y1 && hx > x0 && lx < x1 : lx > x0 && lx < x1 && hy > y0 && ly < y1
if (hit) n++
}
}
}
return n
}
}
const pinKey = (x: number, y: number) => (x + 50_000) * 100_000 + y + 50_000
const pinKeys = (pins: Pt[]) => new Set(pins.map(([x, y]) => pinKey(x, y)))
/**
* Cost of a route; stops counting once it is above `limit`. `fromPin`: it
* starts on a pin (false for a branch off a line of its own signal).
*/
function cost(route: Pt[], net: string, occ: Occupancy, bodies: BodyIndex, pins: Set<number>, limit = Infinity, h = WIRE_H, fromPin = true): { penalty: number; total: number } {
let penalty = 0
let length = route.length * 0.5
const first = route[0]!
const last = route[route.length - 1]!
for (let i = 0; i < route.length - 1; i++) {
const a = route[i]!
const b = route[i + 1]!
length += Math.abs(b[0] - a[0]) + Math.abs(b[1] - a[1])
penalty += occ.overlap(a, b, net, h) * 1000 + bodies.hits(a, b, h, fromPin && i === 0, i === route.length - 2) * BODY
// Running over someone else's pin looks like a connection.
if (pins.size) {
if (a[1] === b[1]) {
for (let x = Math.min(a[0], b[0]); x <= Math.max(a[0], b[0]); x++) {
if ((x === first[0] && a[1] === first[1]) || (x === last[0] && a[1] === last[1])) continue
if (pins.has(pinKey(x, a[1]))) penalty += 300
}
} else {
for (let y = Math.min(a[1], b[1]); y <= Math.max(a[1], b[1]); y++) {
if ((y === first[1] && a[0] === first[0]) || (y === last[1] && a[0] === last[0])) continue
if (pins.has(pinKey(a[0], y))) penalty += 300
}
}
}
if (penalty + length > limit) return { penalty, total: Infinity }
}
return { penalty, total: penalty + length }
}
/** Alternative routes for a wire whose usual route collides with something. */
function* candidates(a: Pt, b: Pt): Generator<Pt[]> {
const [x1, y1] = a
const [x2, y2] = b
const mid = Math.round((x1 + x2) / 2)
if (x2 >= x1 + 2) {
// Another column for the vertical step.
for (let d = 1; d <= x2 - x1; d++) {
for (const m of [mid + d, mid - d]) if (m > x1 && m < x2) yield [a, [m, y1], [m, y2], b]
}
// Detours: step to a free row and back.
for (let dy = 1; dy <= 6; dy++) {
for (const yd of [Math.min(y1, y2) - dy, Math.max(y1, y2) + dy]) {
for (const m1 of [x1 + 1, x1 + 2]) {
for (const m2 of [x2 - 1, x2 - 2]) {
if (m2 > m1) yield [a, [m1, y1], [m1, yd], [m2, yd], [m2, y2], b]
}
}
}
}
return
}
// Backward wires (feedback): out to the right, around, back in from the left.
const rows = new Set<number>()
for (let d = 0; d <= 6; d++) rows.add(Math.round((y1 + y2) / 2) + d).add(Math.round((y1 + y2) / 2) - d)
for (let d = 2; d <= 7; d++) rows.add(Math.max(y1, y2) + d).add(Math.min(y1, y2) - d)
for (const ym of rows) {
// On the row of either end the detour would fold back into a straight line through the parts.
if (ym === y1 || ym === y2) continue
for (const r of [x1 + 1, x1 + 2, x1 + 3]) {
for (const l of [x2 - 1, x2 - 2, x2 - 3]) yield [a, [r, y1], [r, ym], [l, ym], [l, y2], b]
}
}
}
/** A wire to or from a pin facing the unusual way (the inner pins of ports). */
const reversed = (w: RouteInput) => w.aFace === -1 || w.bFace === 1
// ── Grid search ─────────────────────────────────────────────────────
// When neither the usual route nor its alternatives are free, a search of
// the grid around the two ends: steps along free lines, turns cost a little,
// parts are walls, other signals' lines are very expensive to run along and
// a little expensive to cross. It may also start from any point of a line of
// its own signal, so the wire branches off it.
const DX = [1, -1, 0, 0]
const DY = [0, 0, 1, -1]
const TURN = 2
const CROSS = 1.5
const ALONG = 60
const PIN = 300
/** Most points one search looks at before it gives up, and all searches of one routing together. */
const MAX_VISITS = 6_000
const ALL_VISITS = 120_000
/** A tiny binary heap of (cost, state). */
class Heap {
keys: number[] = []
vals: number[] = []
get size() {
return this.keys.length
}
push(k: number, v: number) {
const ks = this.keys
const vs = this.vals
let i = ks.length
ks.push(k)
vs.push(v)
while (i > 0) {
const p = (i - 1) >> 1
if (ks[p]! <= k) break
ks[i] = ks[p]!
vs[i] = vs[p]!
i = p
}
ks[i] = k
vs[i] = v
}
pop(): number {
const ks = this.keys
const vs = this.vals
const top = vs[0]!
const k = ks.pop()!
const v = vs.pop()!
const n = ks.length
if (n) {
let i = 0
for (;;) {
let c = 2 * i + 1
if (c >= n) break
if (c + 1 < n && ks[c + 1]! < ks[c]!) c++
if (ks[c]! >= k) break
ks[i] = ks[c]!
vs[i] = vs[c]!
i = c
}
ks[i] = k
vs[i] = v
}
return top
}
}
/**
* The cheapest square path to `b` (arriving moving right, into a pin facing
* left) from `a` (leaving right, out of a pin facing right) or from any of
* `branches` (points on lines of the same signal). Null when none is found.
*/
function maze(a: Pt, b: Pt, branches: Pt[], net: string, h: number, occ: Occupancy, bodies: BodyIndex, pins: Set<number>, margin: number, budget: { left: number }): Pt[] | null {
// A pin whose first step is already blocked can not be reached.
if (budget.left <= 0 || bodies.hits(a, [a[0] + 1, a[1]], h, true) || bodies.hits([b[0] - 1, b[1]], b, h, false, true)) return null
const xs = [a[0], b[0], ...branches.map(p => p[0])]
const ys = [a[1], b[1], ...branches.map(p => p[1])]
const x0 = Math.min(...xs) - margin
const y0 = Math.min(...ys) - margin
const W = Math.max(...xs) + margin - x0 + 1
const H = Math.max(...ys) + margin - y0 + 1
const N = W * H
if (N > 400_000) return null
const id = (x: number, y: number) => x - x0 + (y - y0) * W
const best = new Float64Array(N * 4).fill(Infinity)
const prev = new Int32Array(N * 4).fill(-1)
const edge = new Float64Array(N * 4).fill(NaN)
const heap = new Heap()
const goal = id(b[0], b[1])
const est = (x: number, y: number) => Math.abs(x - b[0]) + Math.abs(y - b[1])
// Cost of one step from (x, y) in direction d; Infinity when it runs into a part.
const step = (x: number, y: number, d: number): number => {
const k = id(x, y) * 4 + d
const cached = edge[k]!
if (!Number.isNaN(cached)) return cached
const nx = x + DX[d]!
const ny = y + DY[d]!
const p: Pt = [x, y]
const q: Pt = [nx, ny]
let c = 1
if (bodies.hits(p, q, h, x === a[0] && y === a[1], nx === b[0] && ny === b[1])) c = Infinity
else {
c += occ.overlap(p, q, net, h) * ALONG
if ((nx !== b[0] || ny !== b[1]) && pins.has(pinKey(nx, ny))) c += PIN
if (occ.crossedAt(nx, ny, net, d < 2)) c += CROSS
}
edge[k] = c
return c
}
const start = (x: number, y: number, d: number, c: number) => {
const s = id(x, y) * 4 + d
if (c < best[s]!) {
best[s] = c
heap.push(c + est(x, y), s)
}
}
// Out of the pin to the right; or from a branch point, any way.
start(a[0], a[1], 0, 0)
for (const p of branches) for (let d = 0; d < 4; d++) start(p[0], p[1], d, 1)
const fromPin = (s: number) => {
const node = s >> 2
return node === id(a[0], a[1])
}
let visits = 0
while (heap.size) {
const s = heap.pop()
const node = s >> 2
const d = s & 3
const c = best[s]!
if (node === goal && d === 0) {
// Walk back to where it started.
const out: Pt[] = []
let t = s
for (;;) {
const n = t >> 2
out.push([(n % W) + x0, Math.floor(n / W) + y0])
const pt = prev[t]!
if (pt < 0) break
t = pt
}
return simplify(out.reverse())
}
if (++visits > MAX_VISITS || --budget.left <= 0) return null
const x = (node % W) + x0
const y = Math.floor(node / W) + y0
for (let nd = 0; nd < 4; nd++) {
if (nd === (d ^ 1)) continue // no U-turns
// Leaving the source pin: straight out only.
if (prev[s]! < 0 && fromPin(s) && nd !== 0) continue
const nx = x + DX[nd]!
const ny = y + DY[nd]!
if (nx < x0 || ny < y0 || nx >= x0 + W || ny >= y0 + H) continue
// Into the target pin only from its left.
if (nx === b[0] && ny === b[1] && nd !== 0) continue
const e = step(x, y, nd)
if (e === Infinity) continue
const nc = c + e + (nd !== d ? TURN : 0)
const ns = id(nx, ny) * 4 + nd
if (nc < best[ns]!) {
best[ns] = nc
prev[ns] = s
heap.push(nc + est(nx, ny), ns)
}
}
}
return null
}
/** Every grid point on a route, with the part of the route that leads to it. */
function pointsOn(route: Pt[]): { p: Pt; prefix: Pt[] }[] {
const out: { p: Pt; prefix: Pt[] }[] = []
for (let i = 0; i < route.length - 1; i++) {
const [ax, ay] = route[i]!
const [bx, by] = route[i + 1]!
const n = Math.abs(bx - ax) + Math.abs(by - ay)
const dx = Math.sign(bx - ax)
const dy = Math.sign(by - ay)
for (let k = i === 0 ? 1 : 0; k <= n; k++) {
const p: Pt = [ax + dx * k, ay + dy * k]
out.push({ p, prefix: [...route.slice(0, i + 1), p] })
}
}
return out
}
const routeLength = (r: Pt[]) => r.reduce((s, p, i) => (i ? s + Math.abs(p[0] - r[i - 1]![0]) + Math.abs(p[1] - r[i - 1]![1]) : 0), 0)
/**
* A wire of a signal that already has lines: it may branch off them, so the
* signal splits from one trunk. Tries the spots on each line nearest the
* target and keeps the shortest free branch.
*/
function branchRoute(input: RouteInput, trunk: Pt[][], occ: Occupancy, bodies: BodyIndex, pins: Set<number>, h: number): { route: Pt[]; added: number } | null {
const [bx, by] = input.b
let best: { route: Pt[]; added: number } | null = null
for (const t of trunk) {
for (let i = 0; i < t.length - 1; i++) {
const [ax, ay] = t[i]!
const [cx, cy] = t[i + 1]!
const spots: Pt[] = []
if (ay === cy) {
const lo = Math.min(ax, cx)
const hi = Math.max(ax, cx)
for (const k of [1, 2, 3]) spots.push([Math.max(lo, Math.min(hi, bx - k)), ay])
} else {
const lo = Math.min(ay, cy)
const hi = Math.max(ay, cy)
if (ax < bx) spots.push([ax, Math.max(lo, Math.min(hi, by))])
}
for (const p of spots) {
if (p[0] >= bx || (p[0] === t[0]![0] && p[1] === t[0]![1])) continue
const tail = routeWire(p, input.b)
const added = routeLength(tail)
if (best && added >= best.added) continue
if (cost(tail, input.net, occ, bodies, pins, Infinity, h, false).penalty > 0) continue
best = { route: simplify([...t.slice(0, i + 1), ...tail]), added }
}
}
}
return best
}
function autoRoute(input: RouteInput, occ: Occupancy, bodies: BodyIndex, pins: Set<number>, trunk: Pt[][], budget: { left: number }): Pt[] {
const h = input.h ?? WIRE_H
// Wires to the inner pins of ports keep their simple shape.
if (reversed(input)) return routeWire(input.a, input.b, undefined, input.aFace, input.bFace)
const usual = routeWire(input.a, input.b)
const base = cost(usual, input.net, occ, bodies, pins, Infinity, h)
// Its signal is laid already: branch off it when that is free and no longer.
if (trunk.length) {
const branch = branchRoute(input, trunk, occ, bodies, pins, h)
if (branch && (base.penalty > 0 || branch.added <= routeLength(usual))) return branch.route
}
if (base.penalty === 0) return usual
let best = usual
let bestCost = base.total
let bestPenalty = base.penalty
for (const c of candidates(input.a, input.b)) {
const route = simplify(c)
const k = cost(route, input.net, occ, bodies, pins, bestCost, h)
if (k.total < bestCost) {
best = route
bestCost = k.total
bestPenalty = k.penalty
if (k.penalty === 0 && route.length <= 4) break
}
}
if (bestPenalty === 0) return best
// Still through a part or along another signal: search the grid, nearby first.
const branches = trunk.flatMap(pointsOn)
for (const margin of [6, 16]) {
const found = maze(input.a, input.b, branches.map(x => x.p), input.net, h, occ, bodies, pins, margin, budget)
if (!found) continue
// Started on a line of its own signal: the route runs along that line to there.
const from = found[0]!
const lead = from[0] === input.a[0] && from[1] === input.a[1] ? [] : (branches.find(x => x.p[0] === from[0] && x.p[1] === from[1])?.prefix.slice(0, -1) ?? [])
const route = simplify([...lead, ...found])
if (cost(route, input.net, occ, bodies, pins, Infinity, h, true).total < bestCost || bestPenalty >= BODY) return route
break
}
return best
}
/** Moves lines of different nets that share a row or column onto separate lanes. */
function separate(routes: Routed[]) {
interface Item {
r: number
i: number
lo: number
hi: number
net: string
h: number
}
const rows = new Map<number, Item[]>()
const cols = new Map<number, Item[]>()
routes.forEach((route, r) => {
const p = route.draw
for (let i = 0; i < p.length - 1; i++) {
const [ax, ay] = p[i]!
const [bx, by] = p[i + 1]!
if (ay === by && ax !== bx) push(rows, ay, { r, i, lo: Math.min(ax, bx), hi: Math.max(ax, bx), net: route.net, h: route.h })
else if (ax === bx && ay !== by) push(cols, ax, { r, i, lo: Math.min(ay, by), hi: Math.max(ay, by), net: route.net, h: route.h })
}
})
const shifts = new Map<number, { i: number; axis: 0 | 1; off: number }[]>()
const plan = (lines: Map<number, Item[]>, axis: 0 | 1) => {
for (const items of lines.values()) {
if (new Set(items.map(it => it.net)).size < 2) continue
// Clusters of segments that overlap (or touch) each other.
items.sort((p, q) => p.lo - q.lo)
let cluster: Item[] = []
let reach = -Infinity
const flush = () => {
const nets = [...new Set(cluster.map(it => it.net))]
if (nets.length > 1) {
// The first stays, the others go alternately to either side, each
// as far out as the widths of it and its neighbour need.
const width = new Map(cluster.map(it => [it.net, it.h]))
const lane = new Map<string, number>()
let up = width.get(nets[0]!)!
let down = up
nets.forEach((n, k) => {
const h = width.get(n)!
if (k === 0) return lane.set(n, 0)
// Next out from the edge reached so far on that side.
if (k % 2) {
lane.set(n, up + LANE_GAP + h)
up += LANE_GAP + 2 * h
} else {
lane.set(n, -(down + LANE_GAP + h))
down += LANE_GAP + 2 * h
}
})
for (const it of cluster) {
const off = lane.get(it.net)!
if (off) push(shifts, it.r, { i: it.i, axis, off })
}
}
cluster = []
}
for (const it of items) {
if (it.lo > reach + EPS) flush()
cluster.push(it)
reach = Math.max(reach, it.hi)
}
flush()
}
}
plan(rows, 1)
plan(cols, 0)
for (const [r, list] of shifts) {
const p = routes[r]!.draw
list.sort((x, y) => y.i - x.i)
for (const shift of list) {
const { axis, off } = shift
let i = shift.i
const last = p.length - 1
const toward = (from: Pt, to: Pt): Pt => [from[0] + Math.sign(to[0] - from[0]) * 0.5, from[1] + Math.sign(to[1] - from[1]) * 0.5]
if (i + 1 === last) {
// Keep the last half step on the pin's line: shift a copy of it.
const s = toward(p[last]!, p[i]!)
p.splice(last, 0, [...s] as Pt, [...s] as Pt)
}
if (i === 0) {
const s = toward(p[0]!, p[1]!)
p.splice(1, 0, [...s] as Pt, [...s] as Pt)
i = 2
}
p[i]![axis] += off
p[i + 1]![axis] += off
}
}
}
/** Crossings of horizontal lines over vertical lines of other nets. */
export function findCrossings(routes: Routed[]): Crossing[] {
const verticals: { x: number; lo: number; hi: number; net: string }[] = []
routes.forEach(route => {
const p = route.draw
for (let i = 0; i < p.length - 1; i++) {
const [ax, ay] = p[i]!
const [bx, by] = p[i + 1]!
if (ax === bx && ay !== by) verticals.push({ x: ax, lo: Math.min(ay, by), hi: Math.max(ay, by), net: route.net })
}
})
verticals.sort((p, q) => p.x - q.x)
const out: Crossing[] = []
routes.forEach((route, w) => {
const p = route.draw
for (let i = 0; i < p.length - 1; i++) {
const [ax, ay] = p[i]!
const [bx, by] = p[i + 1]!
if (ay !== by || ax === bx) continue
const lo = Math.min(ax, bx)
const hi = Math.max(ax, bx)
// First vertical at x > lo.
let k = 0
let top = verticals.length
while (k < top) {
const m = (k + top) >> 1
if (verticals[m]!.x <= lo + EPS) k = m + 1
else top = m
}
for (; k < verticals.length && verticals[k]!.x < hi - EPS; k++) {
const v = verticals[k]!
if (v.net !== route.net && ay > v.lo + EPS && ay < v.hi - EPS) out.push({ wire: w, seg: i, x: v.x })
}
}
})
return out
}
/** A hop on one segment: from lo to hi along it (grid units), r pixels high. */
export interface Hop {
lo: number
hi: number
r: number
}
/**
* Where lines jump over each other. At each crossing of two signals the
* thinner line hops over the wider one (a wire over a cable), the horizontal
* one when both are as wide; when its segment has no room for the hop (too
* near a corner), the other one hops. A hop is as wide as the line it clears
* plus its own width, at least `minR` pixels; hops that would touch on one
* segment join into one longer bridge. Per route, per segment.
*/
export function planHops(routes: Routed[], minR = 5): Map<number, Map<number, Hop[]>> {
interface S {
r: number
seg: number
c: number
lo: number
hi: number
}
const hs: S[] = []
const vs: S[] = []
routes.forEach((route, r) => {
const p = route.draw
for (let i = 0; i < p.length - 1; i++) {
const [ax, ay] = p[i]!
const [bx, by] = p[i + 1]!
if (ay === by && ax !== bx) hs.push({ r, seg: i, c: ay, lo: Math.min(ax, bx), hi: Math.max(ax, bx) })
else if (ax === bx && ay !== by) vs.push({ r, seg: i, c: ax, lo: Math.min(ay, by), hi: Math.max(ay, by) })
}
})
vs.sort((p, q) => p.c - q.c)
const out = new Map<number, Map<number, Hop[]>>()
const add = (s: S, at: number, r: number) => {
const segs = out.get(s.r) ?? out.set(s.r, new Map()).get(s.r)!
const list = segs.get(s.seg) ?? segs.set(s.seg, []).get(s.seg)!
list.push({ lo: at - r / GRID, hi: at + r / GRID, r })
}
const fits = (s: S, at: number, r: number) => at - r / GRID >= s.lo + 0.15 && at + r / GRID <= s.hi - 0.15
for (const h of hs) {
// Verticals strictly inside this horizontal's span (binary search for the first).
let k = 0
let top = vs.length
while (k < top) {
const m = (k + top) >> 1
if (vs[m]!.c <= h.lo + EPS) k = m + 1
else top = m
}
for (; k < vs.length && vs[k]!.c < h.hi - EPS; k++) {
const v = vs[k]!
const hr = routes[h.r]!
const vr = routes[v.r]!
if (hr.net === vr.net || h.c <= v.lo + EPS || h.c >= v.hi - EPS) continue
const r = Math.max(minR, (hr.h + vr.h) * GRID + 2)
// The thinner one hops; as wide as each other, the horizontal one.
const order: [S, number][] = vr.h < hr.h - EPS ? [[v, h.c], [h, v.c]] : [[h, v.c], [v, h.c]]
const hop = order.find(([s, at]) => fits(s, at, r))
if (hop) add(hop[0], hop[1], r)
}
}
// Hops that would touch join into one.
for (const segs of out.values()) {
for (const [seg, list] of segs) {
list.sort((p, q) => p.lo - q.lo)
const merged: Hop[] = []
for (const hop of list) {
const last = merged[merged.length - 1]
if (last && hop.lo <= last.hi + 2 / GRID) {
last.hi = Math.max(last.hi, hop.hi)
last.r = Math.max(last.r, hop.r)
} else merged.push({ ...hop })
}
segs.set(seg, merged)
}
}
return out
}
/** Where each route is crossed by (or crosses) a line of another signal, for labels to keep clear of. */
export function crossingPoints(routes: Routed[]): Map<number, Pt[]> {
const out = new Map<number, Pt[]>()
const verticals: { r: number; x: number; lo: number; hi: number }[] = []
routes.forEach((route, r) => {
const p = route.draw
for (let i = 0; i < p.length - 1; i++) {
const [ax, ay] = p[i]!
const [bx, by] = p[i + 1]!
if (ax === bx && ay !== by) verticals.push({ r, x: ax, lo: Math.min(ay, by), hi: Math.max(ay, by) })
}
})
routes.forEach((route, r) => {
const p = route.draw
for (let i = 0; i < p.length - 1; i++) {
const [ax, ay] = p[i]!
const [bx, by] = p[i + 1]!
if (ay !== by || ax === bx) continue
const lo = Math.min(ax, bx)
const hi = Math.max(ax, bx)
for (const v of verticals) {
if (routes[v.r]!.net === route.net || v.x <= lo + EPS || v.x >= hi - EPS || ay <= v.lo + EPS || ay >= v.hi - EPS) continue
const pt: Pt = [v.x, ay]
out.set(r, [...(out.get(r) ?? []), pt])
out.set(v.r, [...(out.get(v.r) ?? []), pt])
}
}
})
return out
}
// ── Tidy routing ────────────────────────────────────────────────────
// The way a panel builder wires a cabinet. Every forward wire takes its
// vertical step in the free gap right in front of the part it feeds. All
// wires that share a gap get their own column there, evenly spaced, in the
// order that crosses the fewest other wires; wires of one signal share one
// trunk with branches off it.
interface TidyNet {
net: string
/** Row of the source pin. */
y1: number
/** Rows of the target pins in this gap. */
ys: number[]
min: number
max: number
wires: RouteInput[]
}
const inside = (y: number, n: TidyNet) => y > n.min + EPS && y < n.max - EPS
/** Cost of a wire lying along another signal's line: far worse than a crossing. */
const SHARED_LINE = 10
/**
* Crossings between two signals in one gap when `a` takes the column left
* of `b`. If `a` ends on the row where `b` starts, `b`'s first run and
* `a`'s last run would share that row between the two columns.
*/
function crossings(a: TidyNet, b: TidyNet): number {
let n = inside(b.y1, a) ? 1 : 0
for (const y of a.ys) {
if (inside(y, b)) n++
if (Math.abs(y - b.y1) < EPS) n += SHARED_LINE
}
return n
}
/**
* Left-to-right order of the signals in one gap: each one goes where it
* adds the fewest crossings with those placed so far. A few signals per
* gap, so this stays cheap.
*/
function order(nets: TidyNet[]): TidyNet[] {
const out: TidyNet[] = []
for (const n of [...nets].sort((a, b) => a.y1 - b.y1 || a.min - b.min)) {
let best = 0
let bestCost = Infinity
for (let at = 0; at <= out.length; at++) {
let c = 0
for (let i = 0; i < out.length; i++) c += i < at ? crossings(out[i]!, n) : crossings(n, out[i]!)
// On a tie the later place wins, so signals keep their top-to-bottom order.
if (c <= bestCost) {
bestCost = c
best = at
}
}
out.splice(best, 0, n)
}
return out
}
/**
* Columns for the ordered signals: one compact staircase, a grid step
* apart, in the middle of the gap lo+1 .. hi-1. The block slides sideways
* to the nearest spot where no column runs along another signal's line;
* only the columns of this gap are looked at.
*/
function columns(nets: TidyNet[], lo: number, hi: number, occ: Occupancy): number[] {
const k = nets.length
const width = hi - lo - 1
const center = lo + 1 + Math.floor((width - k) / 2)
let best: number[] = []
let bestCost = Infinity
for (let d = 0; d <= width; d++) {
for (const start of d ? [center - d, center + d] : [center]) {
if (start < lo + 1 || start + k - 1 > hi - 1) continue
let c = 0
nets.forEach((n, i) => (c += occ.overlap([start + i, n.min], [start + i, n.max], n.net)))
if (c < bestCost) {
best = nets.map((_, i) => start + i)
bestCost = c
}
if (c === 0) return best
}
}
return best
}
function tidyRoutes(inputs: RouteInput[], boxes: Box[], occ: Occupancy, bodies: BodyIndex, pins: Set<number>, grid: Map<string, Pt[]>) {
// One gap per target column: everything that enters parts at that x is
// sorted together, so separate bundles can't end up crossing each other.
const gaps = new Map<number, { hi: number; nets: Map<string, TidyNet & { lo: number }> }>()
for (const w of inputs) {
if (grid.has(w.id) || reversed(w)) continue
const [x1, y1] = w.a
const [x2, y2] = w.b
if (x2 < x1 + 2) continue // feedback wires keep the usual router
if (y1 === y2 && cost([w.a, w.b], w.net, occ, bodies, pins, Infinity, w.h).penalty === 0) {
grid.set(w.id, [w.a, w.b])
occ.add([w.a, w.b], w.net, w.h)
continue
}
const min = Math.min(y1, y2)
const max = Math.max(y1, y2)
// The gap starts at the nearest part on the left that the vertical step would cut through.
let lo = x1
for (const b of boxes) {
const right = b.x + b.w
if (right > lo && right < x2 && b.y < max && b.y + b.h > min) lo = Math.ceil(right)
}
if (lo + 1 > x2 - 1) continue
const gap = gaps.get(x2) ?? gaps.set(x2, { hi: x2, nets: new Map() }).get(x2)!
const net = gap.nets.get(w.net)
if (net) {
net.ys.push(y2)
net.min = Math.min(net.min, y2)
net.max = Math.max(net.max, y2)
net.lo = Math.max(net.lo, lo)
net.wires.push(w)
} else gap.nets.set(w.net, { net: w.net, y1, ys: [y2], min, max, lo, wires: [w] })
}
for (const gap of [...gaps.values()].sort((p, q) => p.hi - q.hi)) {
// The block must fit right of every member's nearest obstacle; a signal
// whose obstacle leaves too little room routes the usual way instead.
let members = [...gap.nets.values()]
for (;;) {
const lo = Math.max(...members.map(n => n.lo))
if (!members.length || gap.hi - lo - 1 >= members.length) break
members = members.filter(n => n.lo !== lo)
}
if (!members.length) continue
const lo = Math.max(...members.map(n => n.lo))
const nets = order(members)
const cols = columns(nets, lo, gap.hi, occ)
nets.forEach((n, i) => {
const x = cols[i]!
for (const w of n.wires) {
const route = simplify([w.a, [x, w.a[1]], [x, w.b[1]], w.b])
// Through a part, or along another signal's line: the usual router finds a way around.
let blocked = false
for (let s = 0; s < route.length - 1 && !blocked; s++) {
const h = w.h ?? WIRE_H
blocked = bodies.hits(route[s]!, route[s + 1]!, h, s === 0, s === route.length - 2) > 0 || occ.overlap(route[s]!, route[s + 1]!, w.net, h) > 0
}
if (blocked) continue
grid.set(w.id, route)
occ.add(route, w.net, w.h)
}
})
}
}
export interface RouteOptions {
/** Electrician-style layout for wires without hand-placed corners. */
tidy?: boolean
/** Drawn width of a wire in pixels (a cable's sleeve); plain wires otherwise. */
widthOf?: (wireId: string) => number | undefined
}
export function routeAll(inputs: RouteInput[], bodies: Box[], pins: Pt[], opts: RouteOptions = {}): Routed[] {
const occ = new Occupancy()
const pinSet = new Set(pins.map(([x, y]) => pinKey(x, y)))
const bodyIndex = new BodyIndex(bodies)
const grid = new Map<string, Pt[]>()
// Plugged in: the two pins touch, there is nothing to route.
for (const w of inputs) if (w.a[0] === w.b[0] && w.a[1] === w.b[1]) grid.set(w.id, [w.a, w.b])
// Hand-routed wires next: they are fixed, the others route around them.
for (const w of inputs) {
if (!w.pts?.length || grid.has(w.id)) continue
const r = routeWire(w.a, w.b, w.pts)
grid.set(w.id, r)
occ.add(r, w.net, w.h)
}
if (opts.tidy) tidyRoutes(inputs, bodies, occ, bodyIndex, pinSet, grid)
// Lines of each signal so far, for the next wire of it to branch off.
const trunks = new Map<string, Pt[][]>()
for (const w of inputs) {
const g = grid.get(w.id)
if (g && g.length > 1) trunks.set(w.net, [...(trunks.get(w.net) ?? []), g])
}
const budget = { left: ALL_VISITS }
for (const w of inputs) {
if (grid.has(w.id)) continue
const r = autoRoute(w, occ, bodyIndex, pinSet, trunks.get(w.net) ?? [], budget)
grid.set(w.id, r)
occ.add(r, w.net, w.h)
trunks.set(w.net, [...(trunks.get(w.net) ?? []), r])
}
const routes = inputs.map(w => {
const g = grid.get(w.id)!
return { id: w.id, net: w.net, grid: g, draw: g.map(p => [p[0], p[1]] as Pt), h: w.h ?? WIRE_H }
})
separate(routes)
return routes
}
/** Routes every wire of a circuit, given the shapes of its parts. */
export function circuitRoutes(def: ComponentDef, shapes: Map<string, Shape>, opts: RouteOptions = {}): Routed[] {
const c = circuitOf(def, shapes, opts)
return routeAll(c.inputs, [...c.bodies.values()], [...c.pins.values()].flat(), opts)
}
/** A circuit's wires to route, and the body and pins of each of its parts (by part id). */
function circuitOf(def: ComponentDef, shapes: Map<string, Shape>, opts: RouteOptions) {
const nodes = new Map(def.nodes.map(n => [n.id, n]))
const bodies = new Map<string, Box>()
const pins = new Map<string, Pt[]>()
for (const n of def.nodes) {
const s = shapes.get(n.id)
if (!s) continue
if (n.kind !== 'note') bodies.set(n.id, { x: n.x + s.body.x, y: n.y + s.body.y, w: s.body.w, h: s.body.h })
pins.set(n.id, [...s.inputs, ...s.outputs].map(p => [n.x + p.dx, n.y + p.dy] as Pt))
}
const inputs: RouteInput[] = []
for (const w of def.wires) {
const fn = nodes.get(w.from.node)
const tn = nodes.get(w.to.node)
if (!fn || !tn) continue
const a = pinPos(fn, shapes.get(fn.id)!, w.from.pin, 'out')
const b = pinPos(tn, shapes.get(tn.id)!, w.to.pin, 'in')
if (!a || !b) continue
const px = opts.widthOf?.(w.id)
inputs.push({
id: w.id,
net: `${w.from.node}:${w.from.pin}`,
a: [a.x, a.y],
b: [b.x, b.y],
pts: w.pts,
...(a.face === -1 ? { aFace: -1 as const } : {}),
...(b.face === 1 ? { bFace: 1 as const } : {}),
...(px ? { h: px / 2 / GRID } : {}),
})
}
return { inputs, bodies, pins }
}
// ── Corners after a move ────────────────────────────────────────────
// Hand-placed corners are fixed lines the router routes around, so after
// parts move they are looked at again by the router's own rules: a route
// through them must not run over or under a part (by its full width), along
// a line of another signal or over someone else's pin. Only wires that
// moved or that a moved part now lies on are looked at.
export interface Moved {
/** How far each part that moved went. */
by: Map<string, Pt>
/** Wires whose corners went along with the parts. */
carried: Set<string>
}
type Side = 'a' | 'b' | ''
/**
* Hand-placed corners after parts moved. A wire carried along whole keeps
* its corners unless something that did not come along is now in its way.
* A wire with a moved end keeps the corners on the side that stayed for as
* long as the route through them is clear, and lets go of the others; a
* wire that a moved part now lies on does the same from either side. What
* is let go the router lays out. Returns the corners of every wire looked
* at again; null where none are left.
*/
export function settleCorners(def: ComponentDef, shapes: Map<string, Shape>, moved: Moved, opts: RouteOptions = {}): Map<string, Pt[] | null> {
const out = new Map<string, Pt[] | null>()
if (!moved.by.size) return out
const { inputs, bodies, pins } = circuitOf(def, shapes, opts)
const wires = new Map(def.wires.map(w => [w.id, w]))
// How far a part went, as a key: parts with the same one moved together.
const went = (id: string) => `${moved.by.get(id) ?? [0, 0]}`
// The parts that did not go the same way, with their pins: what can be in the way of a wire that came along.
const apart = new Map<string, { bodies: BodyIndex; pins: Set<number> }>()
const apartFrom = (k: string) => {
let s = apart.get(k)
if (!s) {
const ids = new Set(def.nodes.filter(n => went(n.id) !== k).map(n => n.id))
const of = <T>(m: Map<string, T>) => [...m].filter(([id]) => ids.has(id)).map(([, v]) => v)
s = { bodies: new BodyIndex(of(bodies)), pins: pinKeys(of(pins).flat()) }
apart.set(k, s)
}
return s
}
const hand = inputs.filter(w => w.pts?.length && (w.a[0] !== w.b[0] || w.a[1] !== w.b[1]))
const occ = new Occupancy()
const look = new Map<RouteInput, Side>()
const whole: RouteInput[] = []
// The parts that did not stay where they were.
const moving = apartFrom('0,0')
const none = new Occupancy()
for (const w of hand) {
const { from, to } = wires.get(w.id)!
const a = moved.by.has(from.node)
const b = moved.by.has(to.node)
if (moved.carried.has(w.id)) {
if (a && b && went(from.node) === went(to.node)) whole.push(w)
else look.set(w, '')
} else if (a || b) look.set(w, a && b ? '' : a ? 'b' : 'a')
else {
// Its ends stayed: looked at when a moved part, or a pin of one, now lies on it.
const r = routeWire(w.a, w.b, w.pts)
if (cost(r, w.net, none, moving.bodies, moving.pins, Infinity, w.h).penalty > 0) look.set(w, '')
else occ.add(r, w.net, w.h)
}
}
// Carried along whole: only what did not come along, and the lines that stay, can be in the way.
const clear = whole.filter(w => {
const s = apartFrom(went(wires.get(w.id)!.from.node))
const ok = cost(routeWire(w.a, w.b, w.pts), w.net, occ, s.bodies, s.pins, Infinity, w.h).penalty === 0
if (!ok) look.set(w, '')
return ok
})
for (const w of clear) occ.add(routeWire(w.a, w.b, w.pts), w.net, w.h)
const all = { bodies: new BodyIndex([...bodies.values()]), pins: pinKeys([...pins.values()].flat()) }
for (const w of hand) {
const side = look.get(w)
if (side === undefined) continue
const kept = keepCorners(w, side, occ, all.bodies, all.pins)
out.set(w.id, kept)
if (kept) occ.add(routeWire(w.a, w.b, kept), w.net, w.h)
}
return out
}
/**
* The most hand-placed corners of a wire that still make a clear route,
* counted from its source ('a'), its target ('b') or either end (''), given
* as the corners of that route. Null when no corners do.
*/
function keepCorners(w: RouteInput, side: Side, occ: Occupancy, bodies: BodyIndex, pins: Set<number>): Pt[] | null {
const pts = w.pts!
for (let k = pts.length; k > 0; k--) {
for (const from of side ? [side] : k === pts.length ? ['a'] : ['a', 'b']) {
const route = routeWire(w.a, w.b, from === 'a' ? pts.slice(0, k) : pts.slice(pts.length - k))
if (route.length > 2 && cost(route, w.net, occ, bodies, pins, Infinity, w.h).penalty === 0) return route.slice(1, -1)
}
}
return null
}