logigate/app/lib/logic/cables.ts

157 lines
7.2 KiB
TypeScript

// 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.
import { cableBits, MAX_BITS, pinPos, shapeOf, type DefLookup, type Pt } from './geometry'
import { uid } from './ops'
import type { CircuitNode, ComponentDef, Wire } from './types'
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' } })
return { ok: true, bundle, split }
}
/**
* 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))
}