// Cables: several wires bundled into one. A bundle part gathers the wires, // one cable runs to a split part (or several), which fans them out again. // Wire i of the cable is input i of the bundle and output i of the split. // // A cable end can plug straight into a part: its wires sit on the part's // pins (no wire to draw), and it moves with the part. Each wire of a cable // carries a name, from what drives it or else from what it drives, which a // free cable end shows next to its pins. import { cableBits, cableOffsets, MAX_BITS, pinPos, shapeOf, type DefLookup, type Pt } from './geometry' import { pinName } from './labels' import { lookup, uid } from './ops' import type { CircuitNode, ComponentDef, Project, Wire } from './types' const CABLE_ENDS = new Set(['bundle', 'split']) const isCable = (def: ComponentDef, w: Wire) => def.nodes.find(n => n.id === w.from.node)?.kind === 'bundle' /** The bundle a wire belongs to: the wire is the cable itself, or runs into or out of its ends. */ export function cableOf(def: ComponentDef, wire: Wire): CircuitNode | undefined { const nodes = new Map(def.nodes.map(n => [n.id, n])) const from = nodes.get(wire.from.node) if (from?.kind === 'bundle') return from const to = nodes.get(wire.to.node) if (to?.kind === 'bundle') return to if (from?.kind === 'split') { const feed = def.wires.find(w => w.to.node === from.id) const b = feed && nodes.get(feed.from.node) if (b?.kind === 'bundle') return b } return undefined } /** * Replaces the given wires with a cable, wires in the order of the targets * top to bottom. The cable runs from `at.start` to `at.end` (where the * bundle and the split are centred) when given, else from just after the * sources to just before the targets. Returns the new parts, or a reason it can't. */ export function bundleWires( def: ComponentDef, wireIds: string[], get: DefLookup, at?: { start: Pt; end: Pt }, ): { ok: true; bundle: CircuitNode; split: CircuitNode } | { ok: false; error: string } { const nodes = new Map(def.nodes.map(n => [n.id, n])) const ids = new Set(wireIds) const wires = def.wires.filter(w => ids.has(w.id)) if (wires.length < 2) return { ok: false, error: 'Select at least two wires' } if (wires.length > MAX_BITS) return { ok: false, error: `A cable holds at most ${MAX_BITS} wires` } if (wires.some(w => isCable(def, w))) return { ok: false, error: 'A cable cannot go into another cable' } const ends = wires.map(w => { const fn = nodes.get(w.from.node)! const tn = nodes.get(w.to.node)! return { w, a: pinPos(fn, shapeOf(fn, get), w.from.pin, 'out')!, b: pinPos(tn, shapeOf(tn, get), w.to.pin, 'in')! } }) if (ends.some(e => !e.a || !e.b)) return { ok: false, error: 'Some wires have no pins' } // Wire order: top to bottom at the targets, so the split can plug into them; // when only the sources are all on one part, top to bottom there instead, // so the bundle can plug into that part. const one = (ids: Set) => ids.size === 1 && !CABLE_ENDS.has(nodes.get([...ids][0]!)!.kind) const fromOne = one(new Set(wires.map(w => w.from.node))) const toOne = one(new Set(wires.map(w => w.to.node))) if (fromOne && !toOne) ends.sort((p, q) => p.a.y - q.a.y || p.b.y - q.b.y) else ends.sort((p, q) => p.b.y - q.b.y || p.a.y - q.a.y) const n = ends.length const mid = Math.floor((n - 1) / 2) const mean = (v: number[]) => Math.round(v.reduce((s, x) => s + x, 0) / v.length) const right = Math.max(...ends.map(e => e.a.x)) const left = Math.min(...ends.map(e => e.b.x)) // Automatic: the start just after the sources on their middle row, the end // just before the targets on theirs, so the wires keep running the way they // did. Wires that run backwards get a cable that runs backwards. Each end // steps aside when that spot is taken by another part. const taken = def.nodes.map(nd => { const b = shapeOf(nd, get).body return { x: nd.x + b.x, y: nd.y + b.y, w: b.w, h: b.h } }) const start = freeSpot(taken, [right + 2, mean(ends.map(e => e.a.y)) - mid], n, 1) taken.push({ x: start[0], y: start[1] - 0.5, w: 1, h: n }) const end = freeSpot(taken, [left - 3, mean(ends.map(e => e.b.y)) - mid], n, -1) const [bx, sx] = [start[0], end[0]] const bundle: CircuitNode = at ? { id: uid('n'), kind: 'bundle', bits: n, x: Math.round(at.start[0]), y: Math.round(at.start[1]) - mid } : { id: uid('n'), kind: 'bundle', bits: n, x: bx, y: start[1] } const split: CircuitNode = at ? { id: uid('n'), kind: 'split', bits: n, x: Math.round(at.end[0]), y: Math.round(at.end[1]) - mid } : { id: uid('n'), kind: 'split', bits: n, x: sx, y: end[1] } def.nodes.push(bundle, split) def.wires = def.wires.filter(w => !ids.has(w.id)) ends.forEach((e, i) => { const pin = `b${i}` def.wires.push({ id: uid('w'), from: e.w.from, to: { node: bundle.id, pin }, ...(e.w.color ? { color: e.w.color } : {}) }) def.wires.push({ id: uid('w'), from: { node: split.id, pin }, to: e.w.to, ...(e.w.color ? { color: e.w.color } : {}) }) }) // The sleeve starts neutral: the wires inside show their own colours. def.wires.push({ id: uid('w'), from: { node: bundle.id, pin: 'q' }, to: { node: split.id, pin: 'a' } }) { // All the wires leave one part (or reach one part) in cable order: that end plugs straight in, // unless another part sits where it would go. An end placed by hand plugs in when it was // put right by those pins. for (const [end, side] of [ [bundle, new Set(ends.map(e => e.w.from.node))], [split, new Set(ends.map(e => e.w.to.node))], ] as const) { const part = side.size === 1 ? nodes.get([...side][0]!) : undefined const lay = part && !CABLE_ENDS.has(part.kind) ? plugLayout(def, end, part, get) : null if (!part || !lay) continue if (at && Math.hypot(end.x - lay.x, end.y - lay.y) > 2.5) continue const box = { x: lay.x, y: lay.y - 0.5, w: 1, h: lay.offsets[n - 1]! + 1 } const clash = def.nodes.some(nd => { if (nd === part || nd === bundle || nd === split || nd.kind === 'note') return false const b = shapeOf(nd, get).body return box.x < nd.x + b.x + b.w && box.x + box.w > nd.x + b.x && box.y < nd.y + b.y + b.h && box.y + box.h > nd.y + b.y }) if (!clash) plugInto(def, end, part.id, get) } } return { ok: true, bundle, split } } /** The wires on the single-wire side of a cable end: into a bundle, out of a split. */ function singleWires(def: ComponentDef, end: CircuitNode): Wire[] { return end.kind === 'bundle' ? def.wires.filter(w => w.to.node === end.id) : def.wires.filter(w => w.from.node === end.id) } const farEnd = (end: CircuitNode, w: Wire) => (end.kind === 'bundle' ? w.from : w.to) const bitOf = (end: CircuitNode, w: Wire) => Number((end.kind === 'bundle' ? w.to.pin : w.from.pin).slice(1)) /** * Where a cable end sits when plugged into `part`: each of its wires on the * part pin it is wired to, wires not wired to the part one row on from their * neighbour. Null when those pins are not on one edge in the cable's order. */ export function plugLayout(def: ComponentDef, end: CircuitNode, part: CircuitNode, get: DefLookup): { x: number; y: number; offsets: number[] } | null { const n = cableBits(end) const shape = shapeOf(part, get) const pins = end.kind === 'bundle' ? shape.outputs : shape.inputs const ys: (number | undefined)[] = Array.from({ length: n }, () => undefined) let x: number | undefined for (const w of singleWires(def, end)) { const other = farEnd(end, w) const i = bitOf(end, w) const p = other.node === part.id ? pins.find(k => k.key === other.pin) : undefined if (!p || p.bus || !(i >= 0 && i < n) || ys[i] !== undefined) continue if (x !== undefined && part.x + p.dx !== x) return null x = part.x + p.dx ys[i] = part.y + p.dy } const first = ys.findIndex(y => y !== undefined) if (x === undefined || first < 0) return null for (let i = first - 1; i >= 0; i--) ys[i] = ys[i + 1]! - 1 for (let i = first + 1; i < n; i++) ys[i] ??= ys[i - 1]! + 1 for (let i = 1; i < n; i++) if (!(ys[i]! > ys[i - 1]!)) return null const top = ys[0]! return { x: end.kind === 'split' ? x - 1 : x, y: top, offsets: ys.map(y => y! - top) } } /** Plugs a cable end into a part. False, and the end left unplugged, when the pins don't line up. */ export function plugInto(def: ComponentDef, end: CircuitNode, partId: string, get: DefLookup): boolean { const part = def.nodes.find(n => n.id === partId) const lay = part && part.id !== end.id && CABLE_ENDS.has(end.kind) && !CABLE_ENDS.has(part.kind) ? plugLayout(def, end, part, get) : null if (!part || !lay) { delete end.plug return false } end.plug = part.id end.x = lay.x end.y = lay.y const k = lay.offsets[1]! if (k <= 8 && lay.offsets.every((v, i) => v === i * k)) { if (k === 1) delete end.pitch else end.pitch = k delete end.offsets } else end.offsets = lay.offsets for (const w of singleWires(def, end)) if (farEnd(end, w).node === part.id) delete w.pts return true } /** * The part a free cable end touches with all its wires (at least two), every * one wired to it, so it counts as plugged in. One wire landing on a lamp * doesn't make the whole end a plug. */ function touching(def: ComponentDef, end: CircuitNode, nodes: Map, get: DefLookup): string | null { const wires = singleWires(def, end) if (new Set(wires.map(w => bitOf(end, w))).size < 2) return null const ids = new Set(wires.map(w => farEnd(end, w).node)) const part = ids.size === 1 ? nodes.get([...ids][0]!) : undefined if (!part || CABLE_ENDS.has(part.kind)) return null const mine = shapeOf(end, get) const theirs = shapeOf(part, get) const inward = end.kind === 'bundle' for (const w of wires) { const a = pinPos(end, mine, inward ? w.to.pin : w.from.pin, inward ? 'in' : 'out') const b = pinPos(part, theirs, inward ? w.from.pin : w.to.pin, inward ? 'out' : 'in') if (!a || !b || a.x !== b.x || a.y !== b.y) return null } return part.id } /** What a wire of a cable is called at its source: the name of the switch, row or component pin driving it. */ function sourceName(node: CircuitNode, pin: string, get: DefLookup): string { if (node.kind === 'panel') return node.rows?.find(r => r.id === pin)?.label?.trim() ?? '' if (node.kind === 'input' || node.kind === 'button' || node.kind === 'clock') return node.label?.trim() ?? '' return pinName(node, pin, get) ?? '' } /** What a wire of a cable is called at its target: the lamp, output or component pin it drives. */ function targetName(node: CircuitNode, pin: string, get: DefLookup): string { if (node.kind === 'output' || node.kind === 'lamp' || node.kind === 'hex') return node.label?.trim() ?? '' return pinName(node, pin, get) ?? '' } function setNames(node: CircuitNode, names: string[]) { if (!names.some(Boolean)) delete node.names else if (node.names?.join('\n') !== names.join('\n') || node.names.length !== names.length) node.names = names } /** Names every cable's wires, on the bundle and its splits. */ function syncNames(def: ComponentDef, nodes: Map, get: DefLookup) { const named = new Set() const bundles = def.nodes.filter(n => n.kind === 'bundle') // Twice, so a cable fed by another cable's split picks up its names. for (let round = 0; round < 2; round++) { for (const b of bundles) { const splits = new Set(def.wires.filter(w => w.from.node === b.id && nodes.get(w.to.node)?.kind === 'split').map(w => w.to.node)) const names = Array.from({ length: cableBits(b) }, (_, i) => { const pin = `b${i}` const feed = def.wires.find(w => w.to.node === b.id && w.to.pin === pin) const src = feed && nodes.get(feed.from.node) const own = src ? sourceName(src, feed.from.pin, get) : '' if (own) return own for (const w of def.wires) { if (w.from.pin !== pin || !splits.has(w.from.node)) continue const t = nodes.get(w.to.node) const name = t ? targetName(t, w.to.pin, get) : '' if (name) return name } return '' }) setNames(b, names) named.add(b.id) for (const id of splits) { setNames(nodes.get(id)!, names) named.add(id) } } } // A split with no bundle behind it (a plug waiting for its cable) is named after what its wires drive. for (const n of def.nodes) { if (n.kind !== 'split' || named.has(n.id)) continue const names = Array.from({ length: cableBits(n) }, (_, i) => { for (const w of def.wires) { if (w.from.node !== n.id || w.from.pin !== `b${i}`) continue const t = nodes.get(w.to.node) const name = t ? targetName(t, w.to.pin, get) : '' if (name) return name } return '' }) setNames(n, names) } // Rows of a free panel that feed a cable show the wire's name until they get their own. for (const w of def.wires) { const b = nodes.get(w.to.node) const p = nodes.get(w.from.node) if (b?.kind !== 'bundle' || p?.kind !== 'panel' || p.attach) continue const row = p.rows?.find(r => r.id === w.from.pin) const name = b.names?.[Number(w.to.pin.slice(1))] if (row && !row.label?.trim() && name) row.name = name } } /** * Keeps cables in step after a change: names follow what the wires connect, * plugged ends stay on their part's pins (and come loose when they no longer * line up), and a free end whose wires all touch one part's pins plugs in. */ export function syncCables(project: Project) { const get = lookup(project) for (const def of project.components) { if (!def.nodes.some(n => CABLE_ENDS.has(n.kind))) continue const nodes = new Map(def.nodes.map(n => [n.id, n])) syncNames(def, nodes, get) for (const end of def.nodes) { if (!CABLE_ENDS.has(end.kind)) continue const id = end.plug ?? touching(def, end, nodes, get) if (id) plugInto(def, end, id, get) } } } /** * Whether a part already shows `name` at the pin a cable wire meets: a * switch, lamp or pin called that (or named after the wire, dimmed), a * panel row or a component pin of that name. */ function showsName(node: CircuitNode, pin: string, name: string, get: DefLookup): boolean { switch (node.kind) { case 'input': case 'button': case 'clock': case 'output': case 'lamp': return !!node.autoLabel || !node.label?.trim() || node.label.trim() === name case 'panel': { const row = node.rows?.find(r => r.id === pin) return (row?.label?.trim() || row?.name?.trim()) === name } case 'chip': return pinName(node, pin, get) === name default: return false } } /** * The names a free cable end shows next to its wires, '' where the part at * the other end of a wire shows that name already. None on a plugged end: * the part it sits on shows them. */ export function nameTags(def: ComponentDef, end: CircuitNode, get: DefLookup): string[] { if (end.plug || !end.names?.some(Boolean)) return [] const nodes = new Map(def.nodes.map(n => [n.id, n])) const wires = singleWires(def, end) const mine = shapeOf(end, get) const inward = end.kind === 'bundle' return Array.from({ length: cableBits(end) }, (_, i) => { const name = end.names![i]?.trim() ?? '' const links = wires.filter(w => bitOf(end, w) === i) const known = links.length > 0 && links.every(w => { const far = farEnd(end, w) const other = nodes.get(far.node) if (!other) return false // A part sitting right on the pin covers the name anyway. const a = pinPos(end, mine, inward ? w.to.pin : w.from.pin, inward ? 'in' : 'out') const b = pinPos(other, shapeOf(other, get), far.pin, inward ? 'out' : 'in') return (a && b && a.x === b.x && a.y === b.y) || showsName(other, far.pin, name, get) }) return known ? '' : name }) } /** Cable ends plugged into one of the given parts: they move along with them. */ export function pluggedInto(def: ComponentDef, ids: Set): CircuitNode[] { return def.nodes.filter(n => n.plug && ids.has(n.plug)) } /** * A new input panel for a bundle: a switch for each wire that has nothing * driving it yet, lined up with the bundle's pins. When it drives every * wire, the bundle plugs into it. Null when every wire is driven already. */ export function cablePanel(def: ComponentDef, bundleId: string, get: DefLookup): CircuitNode | null { const bundle = def.nodes.find(n => n.id === bundleId && n.kind === 'bundle') if (!bundle) return null const fed = new Set(def.wires.filter(w => w.to.node === bundle.id).map(w => w.to.pin)) const free = cableOffsets(bundle) .map((dy, i) => ({ pin: `b${i}`, dy, name: bundle.names?.[i] })) .filter(p => !fed.has(p.pin)) if (!free.length) return null const top = free[0]!.dy const panel: CircuitNode = { id: uid('n'), kind: 'panel', x: 0, y: bundle.y + top, rows: free.map(p => ({ id: uid('r'), type: 'switch' as const, dy: p.dy - top, ...(p.name ? { name: p.name } : {}) })), } panel.x = bundle.x - shapeOf(panel, get).body.w def.nodes.push(panel) free.forEach((p, i) => def.wires.push({ id: uid('w'), from: { node: panel.id, pin: panel.rows![i]!.id }, to: { node: bundle.id, pin: p.pin } })) if (!fed.size) plugInto(def, bundle, panel.id, get) return panel } /** * The nearest free place for a cable end of `n` wires (top pin at `at`): * as given, else a little further along (`dir` +1 away from the sources, * -1 away from the targets) or up and down, keeping half a step clear. */ function freeSpot(taken: { x: number; y: number; w: number; h: number }[], at: Pt, n: number, dir: 1 | -1): Pt { const free = (x: number, y: number) => !taken.some(b => x - 0.5 < b.x + b.w && x + 1.5 > b.x && y - 1 < b.y + b.h && y + n > b.y) for (let step = 0; step <= 4; step++) { for (const dy of [0, 1, -1, 2, -2, 3, -3, 4, -4, 6, -6]) { const x = at[0] + dir * step if (free(x, at[1] + dy)) return [x, at[1] + dy] } } return at } /** * Takes a cable apart again: its bundle and splits go, and each source is * wired straight to the targets its wire reached. Returns how many wires * now run on their own. */ export function dissolveCable(def: ComponentDef, bundleId: string): number { const bundle = def.nodes.find(n => n.id === bundleId && n.kind === 'bundle') if (!bundle) return 0 const splits = new Set(def.wires.filter(w => w.from.node === bundle.id).map(w => w.to.node)) for (const id of [...splits]) if (def.nodes.find(n => n.id === id)?.kind !== 'split') splits.delete(id) const added: Wire[] = [] for (let i = 0; i < cableBits(bundle); i++) { const pin = `b${i}` const feed = def.wires.find(w => w.to.node === bundle.id && w.to.pin === pin) if (!feed) continue for (const w of def.wires) { if (!splits.has(w.from.node) || w.from.pin !== pin) continue added.push({ id: uid('w'), from: feed.from, to: w.to, ...(w.color ? { color: w.color } : {}) }) } } const gone = new Set([bundle.id, ...splits]) def.nodes = def.nodes.filter(n => !gone.has(n.id)) def.wires = [...def.wires.filter(w => !gone.has(w.from.node) && !gone.has(w.to.node)), ...added] return added.length } /** * The same path moved sideways by `d` (grid units): to the right of the * direction of travel for positive `d`, corners kept square. Used to draw * each wire of a cable as its own line inside the sleeve. */ export function offsetPath(pts: Pt[], d: number): Pt[] { const normals: Pt[] = [] for (let i = 0; i < pts.length - 1; i++) { const dx = Math.sign(pts[i + 1]![0] - pts[i]![0]) const dy = Math.sign(pts[i + 1]![1] - pts[i]![1]) normals.push([-dy, dx]) } return pts.map((p, i) => { const a = normals[i - 1] const b = normals[i] const n: Pt = !a ? b! : !b ? a : a[0] === b[0] && a[1] === b[1] ? a : a[0] === -b[0] && a[1] === -b[1] ? a : [a[0] + b[0], a[1] + b[1]] return [p[0] + d * n[0], p[1] + d * n[1]] }) } /** Space between the lines of a ribbon cable, in grid units. */ export const LANE = 0.14 /** Cables with up to this many wires show each wire as its own line. */ export const RIBBON_MAX = 16 /** One line per wire of a cable, wire 0 on top (on the left of the direction of travel). */ export function ribbon(pts: Pt[], bits: number): Pt[][] { return Array.from({ length: bits }, (_, i) => offsetPath(pts, (i - (bits - 1) / 2) * LANE)) } /** A choice of pins to run a cable from (or to): a numbered group like A0–A3, or all of them. */ export interface PinGroup { label: string pins: string[] } /** * Pins worth a cable, in pin order: each run of names counting up with the * same stem (A0–A3, B0–B3, S0–S3), then all of them together. Pins that * can't be used (`usable` false) break runs and are left out. */ export function pinGroups(pins: { key: string; label: string }[], usable: (key: string) => boolean = () => true): PinGroup[] { const out: PinGroup[] = [] const name = (p: { label: string }) => /^(.*?)(\d+)$/.exec(p.label.trim()) let run: { key: string; label: string }[] = [] const flush = () => { if (run.length >= 2) out.push({ label: `${run[0]!.label}–${run[run.length - 1]!.label}`, pins: run.map(p => p.key) }) run = [] } for (const p of pins) { const m = name(p) const prev = run[run.length - 1] const pm = prev && name(prev) if (!usable(p.key) || !m) { flush() continue } if (pm && pm[1] === m[1] && Number(m[2]) === Number(pm[2]) + 1) run.push(p) else { flush() run = [p] } } flush() const all = pins.filter(p => usable(p.key)) if (all.length >= 2 && !out.some(g => g.pins.length === all.length)) { out.push({ label: `all ${all.length}${all.length <= 6 ? ` (${all[0]!.label}–${all[all.length - 1]!.label})` : ''}`, pins: all.map(p => p.key) }) } return out.filter(g => g.pins.length <= MAX_BITS) } /** * A plug on some of a part's outputs (wire 0 the top one): a bundle sitting * on the pins, without a cable yet. Pulling the cable out of its pin gives * it the other end, where it is dropped. */ export function cableFromPins(def: ComponentDef, partId: string, pins: string[], get: DefLookup): { ok: true; bundle: CircuitNode } | { ok: false; error: string } { const part = def.nodes.find(n => n.id === partId) if (!part) return { ok: false, error: 'Part not found' } // Outputs on the right edge only: a cable end on the left would sit inside the box. const outs = shapeOf(part, get).outputs.filter(p => !p.bus && p.face !== -1 && pins.includes(p.key)).sort((a, b) => a.dy - b.dy) if (outs.length < 2) return { ok: false, error: 'A cable needs at least two pins' } if (outs.length > MAX_BITS) return { ok: false, error: `A cable holds at most ${MAX_BITS} wires` } const bundle: CircuitNode = { id: uid('n'), kind: 'bundle', bits: outs.length, x: part.x + outs[0]!.dx, y: part.y + outs[0]!.dy } def.nodes.push(bundle) outs.forEach((p, i) => def.wires.push({ id: uid('w'), from: { node: part.id, pin: p.key }, to: { node: bundle.id, pin: `b${i}` } })) plugInto(def, bundle, part.id, get) return { ok: true, bundle } } /** * A plug on some of a part's free inputs: a split sitting on the pins, * without a cable yet. Pulling the cable out of its pin gives it the * other end, where it is dropped (or attach an input panel to it). */ export function cableIntoPins(def: ComponentDef, partId: string, pins: string[], get: DefLookup): { ok: true; split: CircuitNode } | { ok: false; error: string } { const part = def.nodes.find(n => n.id === partId) if (!part) return { ok: false, error: 'Part not found' } const fed = new Set(def.wires.filter(w => w.to.node === part.id).map(w => w.to.pin)) // Inputs on the left edge only: a cable end on the right would sit inside the box. const ins = shapeOf(part, get).inputs.filter(p => !p.bus && p.face !== 1 && pins.includes(p.key) && !fed.has(p.key)).sort((a, b) => a.dy - b.dy) if (ins.length < 2) return { ok: false, error: 'A cable needs at least two free inputs' } if (ins.length > MAX_BITS) return { ok: false, error: `A cable holds at most ${MAX_BITS} wires` } const split: CircuitNode = { id: uid('n'), kind: 'split', bits: ins.length, x: part.x + ins[0]!.dx - 1, y: part.y + ins[0]!.dy } def.nodes.push(split) ins.forEach((p, i) => def.wires.push({ id: uid('w'), from: { node: split.id, pin: `b${i}` }, to: { node: part.id, pin: p.key } })) plugInto(def, split, part.id, get) return { ok: true, split } } /** * The other end of a cable pulled out of a cable end, placed at `x`, `y`: * out of a bundle a split, out of a split a bundle, with as many wires. * Null when it isn't a cable end, or a split that already has its cable. */ export function cableEnd(def: ComponentDef, endId: string, x: number, y: number): CircuitNode | null { const from = def.nodes.find(n => n.id === endId) if (!from || !CABLE_ENDS.has(from.kind)) return null if (from.kind === 'split' && def.wires.some(w => w.to.node === from.id)) return null const end: CircuitNode = { id: uid('n'), kind: from.kind === 'bundle' ? 'split' : 'bundle', bits: cableBits(from), x, y } def.nodes.push(end) const [bundle, split] = end.kind === 'split' ? [from, end] : [end, from] def.wires.push({ id: uid('w'), from: { node: bundle.id, pin: 'q' }, to: { node: split.id, pin: 'a' } }) return end } /** The ends of the cable a cable end belongs to (its bundle and every split it feeds), and which of its wires are in use. */ function cableUse(def: ComponentDef, endId: string): { ends: CircuitNode[]; before: number; keep: number[] } | null { const end = def.nodes.find(n => n.id === endId && CABLE_ENDS.has(n.kind)) if (!end) return null const nodes = new Map(def.nodes.map(n => [n.id, n])) const feed = end.kind === 'split' ? def.wires.find(w => w.to.node === end.id && w.to.pin === 'a') : undefined const fromBundle = feed && nodes.get(feed.from.node) const bundle = end.kind === 'bundle' ? end : fromBundle?.kind === 'bundle' ? fromBundle : undefined const ends = bundle ? [bundle, ...def.wires.filter(w => w.from.node === bundle.id).map(w => nodes.get(w.to.node)).filter((n): n is CircuitNode => n?.kind === 'split')] : [end] const before = Math.max(...ends.map(cableBits)) const ids = new Set(ends.map(e => e.id)) const used = new Set() for (const w of def.wires) { if (ids.has(w.to.node) && nodes.get(w.to.node)!.kind === 'bundle') used.add(wireBit(w.to.pin)) if (ids.has(w.from.node) && nodes.get(w.from.node)!.kind === 'split') used.add(wireBit(w.from.pin)) } const keep = Array.from({ length: before }, (_, i) => i).filter(i => used.has(i)) for (let i = 0; keep.length < 2 && i < before; i++) if (!keep.includes(i)) keep.push(i) keep.sort((a, b) => a - b) return { ends, before, keep } } const wireBit = (pin: string) => (/^b\d+$/.test(pin) ? Number(pin.slice(1)) : -1) /** How many wires a cable has and how many of them are in use (at least two count). */ export function cableInUse(def: ComponentDef, endId: string): { before: number; after: number } | null { const use = cableUse(def, endId) return use ? { before: use.before, after: use.keep.length } : null } /** * Drops the wires of a cable that carry nothing: fed by nothing at its * bundle and taken by nothing from any of its splits (or, for a lone end, * not wired at all). The rest close up in order with their names, each on * the row it had, so nothing wired to them moves; at least two stay. * Returns the number of wires before and after, or null when all are in use. */ export function trimCable(def: ComponentDef, endId: string): { before: number; after: number } | null { const use = cableUse(def, endId) if (!use || use.keep.length >= use.before) return null const { ends, before, keep } = use const nodes = new Map(def.nodes.map(n => [n.id, n])) const ids = new Set(ends.map(e => e.id)) const map = new Map(keep.map((old, k) => [old, k])) for (const e of ends) { const offs = cableOffsets(e) const rows = keep.map(i => offs[i] ?? i) const rel = rows.map(v => v - rows[0]!) e.y += rows[0]! e.bits = keep.length const step = rel[1]! if (step <= 8 && rel.every((v, k) => v === k * step)) { if (step === 1) delete e.pitch else e.pitch = step delete e.offsets } else e.offsets = rel if (e.names) e.names = keep.map(i => e.names![i] ?? '') } // Wires on the dropped ones go; the others move to their new number. def.wires = def.wires.filter(w => { const side = ids.has(w.to.node) && nodes.get(w.to.node)!.kind === 'bundle' ? w.to : ids.has(w.from.node) && nodes.get(w.from.node)!.kind === 'split' ? w.from : undefined if (!side || wireBit(side.pin) < 0) return true const to = map.get(wireBit(side.pin)) if (to === undefined) return false side.pin = `b${to}` return true }) return { before, after: keep.length } }