R wiring: nothing over or under parts, cables as wide as drawn, clear bridges, cables that split, tidy every circuit

Parts are walls with a margin: a line only touches a part where it ends on
its pin. When the usual route and its alternatives are blocked, a search
of the grid around the parts finds the way. Cables count as wide as their
sleeve, so they keep clear of each other. A further wire or cable of a
signal branches off the lines already laid, and cables of one signal are
drawn as one that splits. At crossings the thinner line jumps over the
wider one, as wide as it needs (vertical ones sideways); cables hop with
every line inside. Tidy every circuit lays out all circuits in one go.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-23 14:57:16 +02:00
parent 51d71e2564
commit 24a62c3601
10 changed files with 749 additions and 121 deletions

View File

@ -4,7 +4,7 @@ import { CHECKED_INPUTS } from '~/lib/logic/check'
import { cableBits, GRID as G, pinKindOf, pinPos, routeWire, type Pt, type Shape } from '~/lib/logic/geometry'
import type { CircuitNode, PanelRow, PinRef, Wire } from '~/lib/logic/types'
import { branchCorners, branchTo, endGrip, moveCorner, moveSegment, nearEnd, routeTouchesBox, segmentAt, segmentDrag, splitDrag } from '~/lib/logic/wires'
import { circuitRoutes, findCrossings } from '~/lib/logic/routing'
import { circuitRoutes, planHops } from '~/lib/logic/routing'
import { seriesLinks, type Link } from '~/lib/logic/bulk'
import { dropLinks, dropPins, fitStart, type DropPin } from '~/lib/logic/fit'
import type { CanvasOps, MenuEntry } from '~/composables/useMenu'
@ -47,6 +47,8 @@ interface Route {
kind: string
/** A cable between connector ports: its type's name and colour. */
port?: { name: string; color?: string }
/** It jumps over other lines somewhere. */
hops?: boolean
}
/** The middle of a route's longest straight run, where a cable's label goes. */
@ -67,25 +69,32 @@ function midOfLongest(draw: Pt[]): Pt | undefined {
const toPath = (pts: Pt[]) => pts.map(([x, y], i) => `${i ? 'L' : 'M'}${x * G} ${y * G}`).join('')
const routes = computed<Route[]>(() => {
const routed = circuitRoutes(def.value, shapes.value, { tidy: !!ed.project.value.settings.tidy })
const hops = new Map<number, Map<number, number[]>>()
for (const c of findCrossings(routed)) {
const segs = hops.get(c.wire) ?? hops.set(c.wire, new Map()).get(c.wire)!
segs.set(c.seg, [...(segs.get(c.seg) ?? []), c.x])
/** How wide a wire is drawn, in pixels, when it is a cable: its sleeve with the outline. */
function cablePx(w: Wire | undefined): number | undefined {
const from = w && nodeMap.value.get(w.from.node)
if (!from) return
if (from.kind === 'bundle') {
const bits = cableBits(from)
return bits <= RIBBON_MAX ? bits * LANE * G + 6 : 8
}
const style = ed.project.value.settings.crossing ?? 'bow'
const conn = shapes.value.get(from.id)?.outputs.find(p => p.key === w.from.pin)?.conn
if (conn) return Math.min(8, Math.max(2, ed.getDef.value.conn?.(conn)?.lines.length ?? 2)) * LANE * G + 6
}
const routes = computed<Route[]>(() => {
const byId = new Map(def.value.wires.map(w => [w.id, w]))
const routed = circuitRoutes(def.value, shapes.value, { tidy: !!ed.project.value.settings.tidy, widthOf: id => cablePx(byId.get(id)) })
const hops = planHops(routed)
const style = ed.project.value.settings.crossing ?? 'bow'
return routed.map((r, k) => {
const wire = byId.get(r.id)!
const from = nodeMap.value.get(wire.from.node)
const pin = from && shapes.value.get(from.id)?.outputs.find(p => p.key === wire.from.pin)
const route: Route = { wire, pts: r.grid, draw: r.draw, d: wirePath(r.draw, hops.get(k), style), src: r.net, kind: pin ? pinKindOf(pin) : '' }
const route: Route = { wire, pts: r.grid, draw: r.draw, d: wirePath(r.draw, hops.get(k), style), src: r.net, kind: pin ? pinKindOf(pin) : '', hops: !!hops.get(k)?.size }
if (pin?.conn) {
// A cable between connector ports: a sleeve in its type's colour, named.
const type = ed.getDef.value.conn?.(pin.conn)
route.port = { name: type?.name ?? '?', color: type?.color }
route.d = toPath(r.draw)
route.sleeve = Math.min(8, Math.max(2, type?.lines.length ?? 2)) * LANE * G + 3
route.mark = midOfLongest(r.draw)
}
@ -94,8 +103,7 @@ const routes = computed<Route[]>(() => {
if (route.bits <= RIBBON_MAX) {
// Each wire keeps the colour of the wire that runs into the bundle.
const feed = new Map(def.value.wires.filter(w => w.to.node === from.id).map(w => [w.to.pin, w.color]))
route.d = toPath(r.draw)
route.lanes = ribbon(r.draw, route.bits).map((lane, i) => ({ i, d: toPath(lane), color: feed.get(`b${i}`) }))
route.lanes = ribbon(r.draw, route.bits).map((lane, i) => ({ i, d: wirePath(lane, hops.get(k), style), color: feed.get(`b${i}`) }))
route.sleeve = route.bits * LANE * G + 3
}
// The width mark sits on the middle of the longest straight run.
@ -107,6 +115,34 @@ const routes = computed<Route[]>(() => {
const routeOf = (wire: Wire) => routes.value.find(r => r.wire === wire)
/** Classes of a wire's group: its colour, its signal's value, and how it is being used. */
function wireClass(r: Route) {
return [
r.wire.color ? `c-${r.wire.color}` : r.port?.color ? `c-${r.port.color}` : '',
{
on: srcVal(r.src) === 1,
'port-cable': !!r.port,
selected: wireSelected.value.has(r.wire.id),
hover: hoverSrc.value === r.src,
cable: !!r.bits,
'drop-target': dropWire.value === r.wire.id,
moving: movingWire.value === r.wire.id,
},
]
}
/**
* Sleeved cables, grouped by signal: each group is drawn outline first, then
* core, then lines, so cables of one signal that share a trunk merge into
* one cable that splits. Groups that hop over others come later, on top.
*/
const cableGroups = computed(() => {
const groups = new Map<string, Route[]>()
for (const r of routes.value) if (r.lanes || r.port) groups.set(r.src, [...(groups.get(r.src) ?? []), r])
const hopping = (g: Route[]) => (g.some(r => r.hops) ? 1 : 0)
return [...groups.values()].sort((a, b) => hopping(a) - hopping(b))
})
/** The number a cable carries right now: wire 0 is the lowest bit. */
function cableValue(r: Route): { dec: string; tip: string } | null {
if (!r.bits) return null
@ -1431,42 +1467,28 @@ defineExpose({ fit, zoomAt })
<g ref="content" :transform="`translate(${view.x} ${view.y}) scale(${view.zoom})`">
<g class="wires">
<g
v-for="r in routes"
:key="r.wire.id"
class="wire"
:class="[
r.wire.color ? `c-${r.wire.color}` : r.port?.color ? `c-${r.port.color}` : '',
{
on: srcVal(r.src) === 1,
'port-cable': !!r.port,
selected: wireSelected.has(r.wire.id),
hover: hoverSrc === r.src,
cable: !!r.bits,
'drop-target': dropWire === r.wire.id,
moving: movingWire === r.wire.id,
},
]"
>
<path v-if="wireSelected.has(r.wire.id)" :d="r.d" class="wire-halo" :style="r.sleeve ? { strokeWidth: `${r.sleeve + 9}px` } : undefined" />
<template v-if="r.port">
<!-- A cable between connector ports: one sleeve, named after its type -->
<path :d="r.d" class="cable-sleeve" :style="{ strokeWidth: `${r.sleeve! + 3}px` }" />
<path :d="r.d" class="cable-core" :style="{ strokeWidth: `${r.sleeve}px` }" />
</template>
<template v-else-if="r.lanes">
<!-- Ribbon cable: a sleeve in the cable's colour, one line per wire inside -->
<!-- Cables (ribbons, and cables between connector ports): a sleeve, a core, a line per wire -->
<template v-for="grp in cableGroups" :key="grp[0]!.src">
<g v-for="r in grp" :key="`h${r.wire.id}`" class="wire" :class="wireClass(r)">
<path v-if="wireSelected.has(r.wire.id)" :d="r.d" class="wire-halo" :style="{ strokeWidth: `${r.sleeve! + 9}px` }" />
<path :d="r.d" class="cable-sleeve" :style="{ strokeWidth: `${r.sleeve! + 3}px` }" />
</g>
<g v-for="r in grp" :key="`c${r.wire.id}`" class="wire" :class="wireClass(r)">
<path :d="r.d" class="cable-core" :style="{ strokeWidth: `${r.sleeve}px` }" />
</g>
<g v-for="r in grp" :key="`l${r.wire.id}`" class="wire" :class="wireClass(r)">
<path
v-for="l in r.lanes"
v-for="l in r.lanes ?? []"
:key="l.i"
:d="l.d"
class="lane"
:class="[l.color ? `c-${l.color}` : '', { on: ed.val(r.wire.from.node, `b${l.i}`) === 1 }]"
/>
</g>
</template>
<template v-else>
<g v-for="r in routes" :key="r.wire.id" class="wire" :class="wireClass(r)">
<template v-if="!r.port && !r.lanes">
<path v-if="wireSelected.has(r.wire.id)" :d="r.d" class="wire-halo" :style="r.sleeve ? { strokeWidth: `${r.sleeve + 9}px` } : undefined" />
<path :d="r.d" class="wire-line" />
<path v-if="flow && srcVal(r.src) === 1" :d="r.d" class="wire-flow" />
</template>

View File

@ -191,9 +191,14 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
<EditorFold id="circuit-tools" title="Tools">
<div class="grid gap-2">
<button class="btn w-full" title="Remove hand-placed bends in this circuit and lay out every wire tidily (undo brings them back)" @click="ed.tidyAll()">
<Icon name="lucide:wand-sparkles" class="size-4" /> Tidy all wires
<div class="sel-row">
<button class="btn grow" title="Remove hand-placed bends in this circuit and lay out every wire tidily (undo brings them back)" @click="ed.tidyAll()">
<Icon name="lucide:wand-sparkles" class="size-4" /> Tidy this circuit
</button>
<button class="btn grow" title="The same in every circuit of the project, in one go (undo brings them all back)" @click="ed.tidyEverything()">
<Icon name="lucide:sparkles" class="size-4" /> Tidy every circuit
</button>
</div>
<button
v-if="!ed.task.value"
class="btn w-full"

View File

@ -3,7 +3,7 @@ import { wirePath } from '~/lib/draw'
import type { CrossingStyle } from '~/lib/logic/types'
const props = defineProps<{ style: CrossingStyle }>()
const d = computed(() => wirePath([[3, 14], [37, 14]], new Map([[0, [20]]]), props.style, 1))
const d = computed(() => wirePath([[3, 14], [37, 14]], new Map([[0, [{ lo: 15, hi: 25, r: 5 }]]]), props.style, 1))
</script>
<template>

View File

@ -50,6 +50,7 @@ const SHORTCUTS: [string, string][] = [
['Delete', 'Remove the selection'],
['Ctrl+Z, Ctrl+Shift+Z', 'Undo, redo'],
['Logo (top left), Esc', 'Pause menu: save, load, settings, back to the main menu. Your work is saved'],
['Tidy this circuit / every circuit', 'In the Circuit panel (Tools) or with Space: hand-placed bends go, every wire is laid out anew around the parts. Ctrl+Z undoes it'],
['F', 'Fit the circuit to the screen'],
['Enter', 'Open the selected component'],
]

View File

@ -40,6 +40,8 @@ const ACTIONS: Action[] = [
{ id: 'find', label: 'Find anything in the project', icon: 'lucide:search', keys: 'Ctrl+F', aka: 'search where used', run: () => (ed.dialog.value = 'search') },
{ id: 'table', label: 'Truth table', icon: 'lucide:table', aka: 'test outputs', run: () => (ed.dialog.value = 'table') },
{ id: 'fit', label: 'Fit the circuit to the screen', icon: 'lucide:scan', keys: 'F', aka: 'zoom view', run: () => emit('fit') },
{ id: 'tidy', label: 'Tidy this circuit', icon: 'lucide:wand-sparkles', aka: 'wires clean route layout', when: () => ed.def.value.wires.length > 0, run: () => ed.tidyAll() },
{ id: 'tidy-all', label: 'Tidy every circuit', icon: 'lucide:sparkles', aka: 'wires clean route layout all components', run: () => ed.tidyEverything() },
{ id: 'examples', label: 'Add example parts', icon: 'lucide:book-open', aka: 'library not and or adder counter', run: () => ed.loadExamples() },
{ id: 'connector', label: 'New connector type', icon: 'lucide:plug', aka: 'cable hdmi rj45 bus port', when: () => ed.canPlaceKind('portin'), run: () => ed.addConnector() },
{ id: 'undo', label: 'Undo', icon: 'lucide:undo-2', keys: 'Ctrl+Z', when: () => ed.canUndo.value, run: () => ed.undo() },

View File

@ -1261,6 +1261,26 @@ function create() {
notify(bent ? `Tidied. ${bent} hand-placed bend${bent === 1 ? ' was' : 's were'} removed (Ctrl+Z brings ${bent === 1 ? 'it' : 'them'} back)` : 'Tidy wiring is on')
}
/** Tidy wiring in every circuit of the project: all hand-placed bends go, one undo step. */
function tidyEverything() {
let bent = 0
let circuits = 0
for (const d of project.value.components) {
const n = d.wires.filter(w => w.pts).length
if (n) circuits++
bent += n
for (const w of d.wires) delete w.pts
}
project.value.settings.tidy = true
commit(false)
persist()
notify(
bent
? `Tidied every circuit: ${bent} hand-placed bend${bent === 1 ? '' : 's'} in ${circuits} circuit${circuits === 1 ? '' : 's'} removed (Ctrl+Z brings them back)`
: 'Every circuit is tidy',
)
}
function selectAll() {
selection.value = def.value.nodes.map(n => n.id)
wireSel.value = def.value.wires.map(w => w.id)
@ -2329,6 +2349,7 @@ function create() {
stopLinking,
setTidy,
tidyAll,
tidyEverything,
exportTable,
transistors,
transistorsOfNode,

View File

@ -428,7 +428,8 @@ export function useMenu() {
'sep',
{ label: 'Select all', icon: 'lucide:box-select', keys: 'Ctrl+A', disabled: !ed.def.value.nodes.length, run: () => ed.selectAll() },
{ label: 'Fit to screen', icon: 'lucide:scan', keys: 'F', run: ops.fit },
{ label: 'Tidy all wires', icon: 'lucide:wand-sparkles', disabled: !ed.def.value.wires.length, run: () => ed.tidyAll() },
{ label: 'Tidy this circuit', icon: 'lucide:wand-sparkles', disabled: !ed.def.value.wires.length, run: () => ed.tidyAll() },
{ label: 'Tidy every circuit', icon: 'lucide:sparkles', run: () => ed.tidyEverything() },
{ label: 'Find…', icon: 'lucide:search', keys: 'Ctrl+F', run: () => (ed.dialog.value = 'search') },
{ label: 'Print sheet / PDF', icon: 'lucide:printer', keys: 'Ctrl+P', disabled: !ed.def.value.nodes.length, run: () => ed.exportSheet('print') },
'sep',

View File

@ -102,35 +102,47 @@ export function sevenSegment(value: number) {
return segs.map((s, i) => ({ d: `M${s[0]} ${s[1]}L${s[2]} ${s[3]}`, on: (bits >> i) & 1 }))
}
const HOP = 5
/** A hop on one segment: from lo to hi along it (grid units), r pixels high. */
export interface HopSpan {
lo: number
hi: number
r: number
}
/**
* SVG path for a wire (points in grid units), with a hop drawn on its
* horizontal segments wherever another signal crosses (`hops`: segment
* index to crossing x positions). `scale` is pixels per grid unit.
* SVG path for a wire (points in grid units), with hops where it jumps over
* other lines (`hops`: segment index to the stretches it jumps). Horizontal
* segments jump upwards, vertical ones to the left. `scale` is pixels per
* grid unit.
*/
export function wirePath(pts: Pt[], hops: Map<number, number[]> | undefined, style: CrossingStyle, scale = G): string {
const r = HOP
export function wirePath(pts: Pt[], hops: Map<number, HopSpan[]> | undefined, style: CrossingStyle, scale = G): string {
let d = `M${pts[0]![0] * scale} ${pts[0]![1] * scale}`
for (let i = 0; i < pts.length - 1; i++) {
const [ax, ay] = pts[i]!
const [bx, by] = pts[i + 1]!
const xs = hops?.get(i)
if (xs && style !== 'plain' && ay === by) {
const dir = Math.sign(bx - ax)
const y = ay * scale
let prev = ax * scale
for (const hx of xs.map(x => x * scale).sort((p, q) => dir * (p - q))) {
// Skip hops too close to a corner or to the previous hop.
if (Math.abs(hx - prev) < r + 1 || Math.abs(bx * scale - hx) < r + 1) continue
const s = hx - dir * r
const e = hx + dir * r
d += `L${s} ${y}`
if (style === 'bow') d += `A${r} ${r} 0 0 ${dir > 0 ? 1 : 0} ${e} ${y}`
else if (style === 'triangle') d += `L${hx} ${y - r * 1.3}L${e} ${y}`
else if (style === 'bridge') d += `L${s} ${y - r}L${e} ${y - r}L${e} ${y}`
else d += `M${e} ${y}`
prev = e
const spans = hops?.get(i)
if (spans?.length && style !== 'plain' && (ay === by || ax === bx)) {
const horizontal = ay === by
const from = (horizontal ? ax : ay) * scale
const to = (horizontal ? bx : by) * scale
const dir = Math.sign(to - from)
const c = (horizontal ? ay : ax) * scale
// A point at `t` along the segment, `off` pixels out to the side the hop bulges.
const at = (t: number, off = 0) => (horizontal ? `${t} ${c - off}` : `${c - off} ${t}`)
const list = spans.map(h => ({ s: (dir > 0 ? h.lo : h.hi) * scale, e: (dir > 0 ? h.hi : h.lo) * scale, r: h.r })).sort((p, q) => dir * (p.s - q.s))
for (const { s, e, r } of list) {
const half = Math.abs(e - s) / 2
d += `L${at(s)}`
if (style === 'bow') {
// Up for a horizontal segment, to the left for a vertical one.
const sweep = horizontal ? (dir > 0 ? 1 : 0) : dir > 0 ? 0 : 1
d += `A${half} ${r} 0 0 ${sweep} ${at(e)}`
} else if (style === 'triangle') {
const lift = r * 1.3
if (half <= r * 1.2) d += `L${at((s + e) / 2, lift)}L${at(e)}`
else d += `L${at(s + dir * r, lift)}L${at(e - dir * r, lift)}L${at(e)}`
} else if (style === 'bridge') d += `L${at(s, r)}L${at(e, r)}L${at(e)}`
else d += `M${at(e)}`
}
}
d += `L${bx * scale} ${by * scale}`

View File

@ -1,15 +1,20 @@
// Routes all wires of a circuit so that wires of different signals never
// run on top of each other.
// 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; 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.
// 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 { pinPos, routeWire, simplify, type Pt, type Shape } from './geometry'
import { GRID, pinPos, routeWire, simplify, type Pt, type Shape } from './geometry'
import type { ComponentDef } from './types'
export interface RouteInput {
@ -22,6 +27,8 @@ export interface RouteInput {
/** 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 {
@ -38,6 +45,8 @@ export interface Routed {
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 {
@ -48,46 +57,75 @@ export interface Crossing {
x: number
}
const LANE = 0.25
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) {
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 })
else if (ax === bx && ay !== by) push(this.cols, ax, { lo: Math.min(ay, by), hi: Math.max(ay, by), net })
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 shares with lines of other nets. */
overlap(a: Pt, b: Pt, net: string): number {
/**
* 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 list = horizontal ? this.rows.get(a[1]) : this.cols.get(a[0])
if (!list) return 0
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) continue
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 counts too: it would read as one wire.
// Touching end to end on one line counts too: it would read as one wire.
if (o > 0) total += o
else if (o === 0) total += 0.5
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) {
@ -113,24 +151,46 @@ class BodyIndex {
}
}
/** Bodies whose inside (minus a small margin) the segment passes through. */
hits(a: Pt, b: Pt): number {
/**
* 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(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++) {
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 + 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 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++
}
@ -142,8 +202,11 @@ class BodyIndex {
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 } {
/**
* 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]!
@ -152,7 +215,7 @@ function cost(route: Pt[], net: string, occ: Occupancy, bodies: BodyIndex, pins:
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
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]) {
@ -199,6 +262,8 @@ function* candidates(a: Pt, b: Pt): Generator<Pt[]> {
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]
}
@ -208,23 +273,267 @@ function* candidates(a: Pt, b: Pt): Generator<Pt[]> {
/** 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<number>): Pt[] {
// ── 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 = 8_000
const ALL_VISITS = 200_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)
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)
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
}
@ -236,6 +545,7 @@ function separate(routes: Routed[]) {
lo: number
hi: number
net: string
h: number
}
const rows = new Map<number, Item[]>()
const cols = new Map<number, Item[]>()
@ -244,8 +554,8 @@ function separate(routes: Routed[]) {
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 })
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 })
}
})
@ -260,7 +570,24 @@ function separate(routes: Routed[]) {
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]))
// 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 })
@ -341,6 +668,87 @@ export function findCrossings(routes: Routed[]): Crossing[] {
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
}
// ── 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
@ -438,9 +846,9 @@ function tidyRoutes(inputs: RouteInput[], boxes: Box[], occ: Occupancy, bodies:
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) {
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)
occ.add([w.a, w.b], w.net, w.h)
continue
}
const min = Math.min(y1, y2)
@ -483,11 +891,12 @@ function tidyRoutes(inputs: RouteInput[], boxes: Box[], occ: Occupancy, bodies:
// 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
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)
occ.add(route, w.net, w.h)
}
})
}
@ -496,6 +905,8 @@ function tidyRoutes(inputs: RouteInput[], boxes: Box[], occ: Occupancy, bodies:
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[] {
@ -510,18 +921,26 @@ export function routeAll(inputs: RouteInput[], bodies: Box[], pins: Pt[], opts:
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)
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)
const r = autoRoute(w, occ, bodyIndex, pinSet, trunks.get(w.net) ?? [], budget)
grid.set(w.id, r)
occ.add(r, w.net)
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) }
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
@ -546,7 +965,17 @@ export function circuitRoutes(def: ComponentDef, shapes: Map<string, Shape>, opt
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 } : {}) })
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 routeAll(inputs, bodies, pins, opts)
}

View File

@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import { shapeOf, type Pt } from '../app/lib/logic/geometry'
import { createProject, lookup } from '../app/lib/logic/ops'
import { circuitRoutes, findCrossings, routeAll, type Routed } from '../app/lib/logic/routing'
import { circuitRoutes, findCrossings, planHops, routeAll, WIRE_H, type Box, type Routed } from '../app/lib/logic/routing'
/** Every pair of segments from different nets that lie on the same line and overlap. */
function overlaps(routes: Routed[]) {
@ -133,3 +133,138 @@ describe('tidy routing on every example', () => {
})
}
})
/** Segments of a route that run through the inside of a part (its edges, where pins sit, are fine). */
function throughParts(r: Routed, boxes: Box[]): number {
let n = 0
for (let i = 0; i < r.grid.length - 1; i++) {
const [ax, ay] = r.grid[i]!
const [bx, by] = r.grid[i + 1]!
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 (const b of boxes) {
const hit = ly === hy ? ly > b.y && ly < b.y + b.h && hx > b.x && lx < b.x + b.w : lx > b.x && lx < b.x + b.w && hy > b.y && ly < b.y + b.h
if (hit) n++
}
}
return n
}
describe('lines and parts', () => {
const p = createProject({ examples: true })
const get = lookup(p)
for (const tidy of [false, true]) {
it(`no wire runs over or under a part, on any example${tidy ? ' (tidy)' : ''}`, () => {
for (const def of p.components) {
const shapes = new Map(def.nodes.map(n => [n.id, shapeOf(n, get)]))
const boxes = def.nodes.filter(n => n.kind !== 'note').map(n => {
const b = shapes.get(n.id)!.body
return { x: n.x + b.x, y: n.y + b.y, w: b.w, h: b.h }
})
const routes = circuitRoutes({ ...def, wires: def.wires.map(w => ({ ...w, pts: undefined })) }, shapes, { tidy })
for (const r of routes) expect(throughParts(r, boxes), `${def.name}: ${r.id}`).toBe(0)
}
})
}
it('goes around a part in the way, keeping off its edges', () => {
const part = { x: 4, y: -3, w: 4, h: 6 }
const [r] = routeAll([{ id: 'w', net: 'n', a: [0, 0], b: [14, 0] }], [part], [])
expect(throughParts(r!, [part])).toBe(0)
// Not along the part's top or bottom edge either.
expect(r!.grid.some(([, y]) => y === -3 || y === 3)).toBe(false)
})
it('finds a way around a whole wall of parts', () => {
const wall = [-12, -6, 0, 6].map(y => ({ x: 5, y, w: 3, h: 6 }))
const [r] = routeAll([{ id: 'w', net: 'n', a: [0, 1], b: [14, 1] }], wall, [])
expect(throughParts(r!, wall)).toBe(0)
expect(r!.grid.at(-1)).toEqual([14, 1])
})
})
describe('cables', () => {
const CABLE = 0.47 // half the width of a 4-wire ribbon, in grid units
it('keeps two cables of different signals a column apart, where wires could sit side by side', () => {
// Both want column 5 for their vertical step.
const ends = (h?: number) =>
routeAll(
[
{ id: 'c1', net: 'n1', a: [0, 0], b: [10, 6], h },
{ id: 'c2', net: 'n2', a: [0, 2], b: [10, 8], h },
],
[],
[],
).map(r => r.grid[1]![0])
const [w1, w2] = ends()
expect(Math.abs(w2! - w1!)).toBe(1)
const [c1, c2] = ends(CABLE)
expect(Math.abs(c2! - c1!)).toBeGreaterThanOrEqual(2)
})
it('a second cable of one signal branches off the first, like a wire', () => {
const routes = routeAll(
[
{ id: 'c1', net: 'bus', a: [0, 0], b: [12, 8], h: CABLE },
{ id: 'c2', net: 'bus', a: [0, 0], b: [20, 10], h: CABLE },
],
[],
[],
)
const [first, second] = routes.map(r => r.grid)
// On its own it would turn at column 10; it follows the first down column 6 instead.
expect(first!.slice(0, 3)).toEqual([[0, 0], [6, 0], [6, 8]])
expect(second!.slice(0, 3)).toEqual(first!.slice(0, 3))
expect(second!.at(-1)).toEqual([20, 10])
})
})
describe('hops', () => {
const H = 0.47
it('a wire jumps over a cable, as wide as the cable', () => {
const routes = routeAll(
[
{ id: 'cable', net: 'c', a: [5, -6], b: [6, 6], pts: [[5, -6], [5, 6]], h: H },
{ id: 'wire', net: 'w', a: [0, 0], b: [10, 0] },
],
[],
[],
)
const hops = planHops(routes)
expect(hops.has(0)).toBe(false)
const [hop] = [...hops.get(1)!.values()][0]!
expect(hop!.hi - hop!.lo).toBeGreaterThanOrEqual(2 * (H + WIRE_H))
})
it('a vertical wire jumps sideways over a horizontal cable', () => {
const routes = routeAll(
[
{ id: 'cable', net: 'c', a: [0, 0], b: [10, 0], h: H },
{ id: 'wire', net: 'w', a: [5, -6], b: [6, 6], pts: [[5, -6], [5, 6]] },
],
[],
[],
)
const hops = planHops(routes)
expect(hops.has(0)).toBe(false)
expect(hops.get(1)?.size).toBe(1)
})
it('two plain wires: the horizontal one hops; nothing hops over its own signal', () => {
const routes = routeAll(
[
{ id: 'h', net: 'n1', a: [0, 3], b: [10, 3] },
{ id: 'v', net: 'n2', a: [5, 0], b: [6, 8], pts: [[5, 0], [5, 8]] },
{ id: 'v2', net: 'n1', a: [0, 3], b: [8, 9], pts: [[7, 3], [7, 9]] },
],
[],
[],
)
const hops = planHops(routes)
expect([...hops.keys()].map(k => routes[k]!.id).sort()).toEqual(['h', 'v2'])
})
})