logigate/app/lib/logic/routing.ts

385 lines
13 KiB
TypeScript

// 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[]
}
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<number, Seg[]>()
cols = new Map<number, Seg[]>()
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<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)
}
}
}
/** 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<number>, 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<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) {
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]
}
}
}
function autoRoute(input: RouteInput, occ: Occupancy, bodies: BodyIndex, pins: Set<number>): Pt[] {
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<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 })
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<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) {
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
}
export function routeAll(inputs: RouteInput[], bodies: Box[], pins: Pt[]): 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[]>()
// Hand-routed wires first: they are fixed, the others route around them.
for (const w of inputs) {
if (!w.pts?.length) continue
const r = routeWire(w.a, w.b, w.pts)
grid.set(w.id, r)
occ.add(r, w.net)
}
for (const w of inputs) {
if (w.pts?.length) 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<string, Shape>): 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 })
}
return routeAll(inputs, bodies, pins)
}