// Routes all wires of a circuit so that wires of different signals never // run on top of each other. // // 1. Wires with hand-placed corners keep them. Every other wire uses its // usual route if that is free; otherwise the cheapest free alternative: // another column for the vertical step, or a detour around parts. // 2. Anything still sharing a line with another signal is drawn on its own // parallel lane, a quarter grid step apart. // 3. Crossings between different signals are listed, so the view can draw // hops (bow, triangle, bridge, gap) at those points. import { 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 } 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[] } 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 LANE = 0.25 const EPS = 1e-6 interface Seg { lo: number hi: number net: string } /** Lines already taken, by row (horizontal) and column (vertical). */ class Occupancy { rows = new Map() cols = new Map() add(route: Pt[], net: string) { 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 }) else if (ax === bx && ay !== by) push(this.cols, ax, { lo: Math.min(ay, by), hi: Math.max(ay, by), net }) } } /** Length that a segment shares with lines of other nets. */ overlap(a: Pt, b: Pt, net: string): number { const horizontal = a[1] === b[1] const list = horizontal ? this.rows.get(a[1]) : this.cols.get(a[0]) if (!list) return 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]) let total = 0 for (const s of list) { if (s.net === net) continue const o = Math.min(hi, s.hi) - Math.max(lo, s.lo) // Touching end to end counts too: it would read as one wire. if (o > 0) total += o else if (o === 0) total += 0.5 } return total } } function push(map: Map, 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() private stamp = new Map() 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) } } } /** Bodies whose inside (minus a small margin) the segment passes through. */ hits(a: Pt, b: Pt): number { const S = BodyIndex.SIZE const q = ++this.query let n = 0 const lx = Math.min(a[0], b[0]) const hx = Math.max(a[0], b[0]) const ly = Math.min(a[1], b[1]) const hy = Math.max(a[1], b[1]) for (let cx = Math.floor(lx / S); cx <= Math.floor(hx / S); cx++) { for (let cy = Math.floor(ly / S); cy <= Math.floor(hy / 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 + 0.2 const x1 = box.x + box.w - 0.2 const y0 = box.y + 0.2 const y1 = box.y + box.h - 0.2 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 /** Cost of a route; stops counting once it is above `limit`. */ function cost(route: Pt[], net: string, occ: Occupancy, bodies: BodyIndex, pins: Set, limit = Infinity): { 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) * 1000 + bodies.hits(a, b) * 60 // 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 { 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() 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) { 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 function autoRoute(input: RouteInput, occ: Occupancy, bodies: BodyIndex, pins: Set): Pt[] { // 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) if (base.penalty === 0) return usual let best = usual let bestCost = base.total for (const c of candidates(input.a, input.b)) { const route = simplify(c) const k = cost(route, input.net, occ, bodies, pins, bestCost) if (k.total < bestCost) { best = route bestCost = k.total if (k.penalty === 0 && route.length <= 4) 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 } const rows = new Map() const cols = new Map() 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 }) else if (ax === bx && ay !== by) push(cols, ax, { r, i, lo: Math.min(ay, by), hi: Math.max(ay, by), net: route.net }) } }) const shifts = new Map() const plan = (lines: Map, 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) { const lane = new Map(nets.map((n, k) => [n, k === 0 ? 0 : (k % 2 ? 1 : -1) * Math.ceil(k / 2) * LANE])) 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 } // ── 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, grid: Map) { // 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 }>() 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).penalty === 0) { grid.set(w.id, [w.a, w.b]) occ.add([w.a, w.b], w.net) 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++) { blocked = bodies.hits(route[s]!, route[s + 1]!) > 0 || occ.overlap(route[s]!, route[s + 1]!, w.net) > 0 } if (blocked) continue grid.set(w.id, route) occ.add(route, w.net) } }) } } export interface RouteOptions { /** Electrician-style layout for wires without hand-placed corners. */ tidy?: boolean } 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() // 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) } if (opts.tidy) tidyRoutes(inputs, bodies, occ, bodyIndex, pinSet, grid) for (const w of inputs) { if (grid.has(w.id)) continue const r = autoRoute(w, occ, bodyIndex, pinSet) grid.set(w.id, r) occ.add(r, w.net) } 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) } }) separate(routes) return routes } /** Routes every wire of a circuit, given the shapes of its parts. */ export function circuitRoutes(def: ComponentDef, shapes: Map, opts: RouteOptions = {}): Routed[] { const nodes = new Map(def.nodes.map(n => [n.id, n])) const bodies: Box[] = [] const pins: Pt[] = [] for (const n of def.nodes) { const s = shapes.get(n.id) if (!s) continue if (n.kind !== 'note') bodies.push({ x: n.x + s.body.x, y: n.y + s.body.y, w: s.body.w, h: s.body.h }) for (const p of [...s.inputs, ...s.outputs]) pins.push([n.x + p.dx, n.y + p.dy]) } 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 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 } : {}) }) } return routeAll(inputs, bodies, pins, opts) }