logigate/app/lib/logic/geometry.ts

205 lines
6.4 KiB
TypeScript
Raw Normal View History

// Node shapes and pin positions, all in grid units relative to the node's
// (x, y). Pins always sit on whole grid points so straight wires line up.
import type { CircuitNode, ComponentDef, SymbolKind } from './types'
export const GRID = 16
export interface PinInfo {
key: string
label: string
dx: number
dy: number
}
export interface Shape {
body: { x: number; y: number; w: number; h: number }
inputs: PinInfo[]
outputs: PinInfo[]
/** Set when the node draws as a logic gate symbol. */
gate?: SymbolKind
}
export type DefLookup = (id: string) => ComponentDef | undefined
const LABEL_CHAR = 0.4 // grid units per character of a pin label
const NAME_CHAR = 0.44
export interface ChipPins {
inputs: { key: string; label: string }[]
outputs: { key: string; label: string }[]
}
/** A component's pins are its input/output nodes, ordered top to bottom. */
export function chipPins(def: ComponentDef): ChipPins {
const byPos = (a: CircuitNode, b: CircuitNode) => a.y - b.y || a.x - b.x
const pins = (kind: 'input' | 'output', fallback: string) =>
def.nodes
.filter(n => n.kind === kind)
.sort(byPos)
.map((n, i) => ({ key: n.id, label: n.label?.trim() || `${fallback}${i + 1}` }))
return { inputs: pins('input', 'in'), outputs: pins('output', 'out') }
}
function gateShape(symbol: SymbolKind, inputs: { key: string; label: string }[], output: { key: string; label: string }): Shape {
const n = inputs.length
if (n === 1) {
return {
gate: symbol,
body: { x: 0, y: -1, w: 3, h: 2 },
inputs: [{ ...inputs[0]!, dx: 0, dy: 0 }],
outputs: [{ ...output, dx: 3, dy: 0 }],
}
}
if (n === 2) {
return {
gate: symbol,
body: { x: 0, y: -0.5, w: 4, h: 3 },
inputs: inputs.map((p, i) => ({ ...p, dx: 0, dy: i * 2 })),
outputs: [{ ...output, dx: 4, dy: 1 }],
}
}
return {
gate: symbol,
body: { x: 0, y: -0.5, w: 4, h: n },
inputs: inputs.map((p, i) => ({ ...p, dx: 0, dy: i })),
outputs: [{ ...output, dx: 4, dy: Math.floor((n - 1) / 2) }],
}
}
function boxShape(name: string, pins: ChipPins): Shape {
const nIn = pins.inputs.length
const nOut = pins.outputs.length
const n = Math.max(nIn, nOut, 1)
const inOff = Math.floor((n - nIn) / 2)
const outOff = Math.floor((n - nOut) / 2)
const longest = (ps: { label: string }[]) => ps.reduce((m, p) => Math.max(m, p.label.length), 0)
const w = Math.max(
3,
Math.ceil(longest(pins.inputs) * LABEL_CHAR + longest(pins.outputs) * LABEL_CHAR + name.length * NAME_CHAR + 1.5),
)
return {
body: n === 1 ? { x: 0, y: -1, w, h: 2 } : { x: 0, y: -0.5, w, h: n },
inputs: pins.inputs.map((p, i) => ({ ...p, dx: 0, dy: inOff + i })),
outputs: pins.outputs.map((p, i) => ({ ...p, dx: w, dy: outOff + i })),
}
}
const NAND_SHAPE = gateShape('nand', [{ key: 'a', label: 'A' }, { key: 'b', label: 'B' }], { key: 'q', label: 'Q' })
const SOURCE_SHAPE: Shape = {
body: { x: 0, y: -0.75, w: 2, h: 1.5 },
inputs: [],
outputs: [{ key: 'q', label: '', dx: 2, dy: 0 }],
}
const SINK_SHAPE: Shape = {
body: { x: 0, y: -0.75, w: 2, h: 1.5 },
inputs: [{ key: 'a', label: '', dx: 0, dy: 0 }],
outputs: [],
}
const HEX_SHAPE: Shape = {
body: { x: 0, y: -0.5, w: 3, h: 4 },
inputs: ['1', '2', '4', '8'].map((label, i) => ({ key: `b${i}`, label, dx: 0, dy: i })),
outputs: [],
}
const CLOCK_SHAPE: Shape = {
body: { x: 0, y: -0.75, w: 3, h: 1.5 },
inputs: [],
outputs: [{ key: 'q', label: '', dx: 3, dy: 0 }],
}
const MISSING_SHAPE: Shape = { body: { x: 0, y: -1, w: 4, h: 2 }, inputs: [], outputs: [] }
export function noteLines(node: CircuitNode): string[] {
return (node.label || 'Note').split('\n')
}
export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
switch (node.kind) {
case 'nand':
return NAND_SHAPE
case 'input':
case 'high':
case 'low':
case 'button':
return SOURCE_SHAPE
case 'clock':
return CLOCK_SHAPE
case 'output':
case 'lamp':
return SINK_SHAPE
case 'hex':
return HEX_SHAPE
case 'note': {
const lines = noteLines(node)
const w = Math.max(2, Math.ceil(Math.max(...lines.map(l => l.length)) * NAME_CHAR + 1))
return { body: { x: 0, y: -0.75, w, h: lines.length + 0.5 }, inputs: [], outputs: [] }
}
case 'chip': {
const def = node.chip ? getDef(node.chip) : undefined
if (!def) return MISSING_SHAPE
const pins = chipPins(def)
if (def.symbol !== 'box' && pins.outputs.length === 1 && pins.inputs.length >= 1 && pins.inputs.length <= 8) {
return gateShape(def.symbol, pins.inputs, pins.outputs[0]!)
}
return boxShape(def.name, pins)
}
}
}
export function pinPos(node: CircuitNode, shape: Shape, key: string, dir: 'in' | 'out') {
const pin = (dir === 'in' ? shape.inputs : shape.outputs).find(p => p.key === key)
return pin ? { x: node.x + pin.dx, y: node.y + pin.dy } : undefined
}
export type Pt = [number, number]
/** Drop repeated points and points in the middle of a straight run. */
export function simplify(pts: Pt[]): Pt[] {
const out: Pt[] = []
for (const p of pts) {
const last = out[out.length - 1]
if (last && last[0] === p[0] && last[1] === p[1]) continue
const prev = out[out.length - 2]
if (prev && last && ((prev[0] === last[0] && last[0] === p[0]) || (prev[1] === last[1] && last[1] === p[1]))) {
out[out.length - 1] = p
continue
}
out.push(p)
}
return out
}
/**
* Orthogonal route from an output pin to an input pin, as a list of points.
* With corner points set, the route runs through them. Otherwise forward
* wires get one vertical segment halfway; backward wires (feedback loops) go
* out to the right, around, and back in from the left.
*/
export function routeWire(a: Pt, b: Pt, corners?: Pt[]): Pt[] {
const [x1, y1] = a
const [x2, y2] = b
if (corners?.length) {
const out: Pt[] = [a]
let prev = a
for (const p of corners) {
if (p[0] !== prev[0] && p[1] !== prev[1]) out.push([p[0], prev[1]])
out.push(p)
prev = p
}
if (b[0] !== prev[0] && b[1] !== prev[1]) out.push([prev[0], b[1]])
out.push(b)
return simplify(out)
}
if (y1 === y2 && x2 > x1) return [a, b]
if (x2 >= x1 + 1) {
const m = Math.round((x1 + x2) / 2)
return [a, [m, y1], [m, y2], b]
}
const ym = Math.abs(y2 - y1) >= 3 ? Math.round((y1 + y2) / 2) : Math.max(y1, y2) + 2
return [a, [x1 + 1, y1], [x1 + 1, ym], [x2 - 1, ym], [x2 - 1, y2], b]
}