// 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' } 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' } }) if (!at) { // 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. 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 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 every wire of its single-wire side, so it counts as plugged in. */ function touching(def: ComponentDef, end: CircuitNode, nodes: Map, get: DefLookup): string | null { const wires = singleWires(def, end) 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) } } } for (const n of def.nodes) if (n.kind === 'split' && !named.has(n.id)) delete 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) } } } /** 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 /** 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)) }