logigate/app/lib/logic/geometry.ts

272 lines
8.7 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, LampColor, 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
/** Vertical centre of the pin area, where a box prints its name. */
nameY?: number
/** Lamps and displays from inside the component, shown on its box. */
face?: FaceItem[]
}
export interface FaceItem {
/** Node id inside the component. */
id: string
kind: 'lamp' | 'hex'
label: string
color?: LampColor
/** Top-left corner and size in grid units, relative to the chip node. */
x: number
y: number
w: number
h: number
}
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
const FACE_CHAR = 0.34
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') }
}
/**
* Lamps and hex displays inside a component, arranged on its box the way
* they are placed inside: nodes at about the same height share a row.
*/
export function faceLayout(def: ComponentDef): { items: FaceItem[]; w: number; h: number } {
const empty = { items: [], w: 0, h: 0 }
if (def.face === false) return empty
const nodes = def.nodes.filter(n => n.kind === 'lamp' || n.kind === 'hex').sort((a, b) => a.y - b.y || a.x - b.x)
if (!nodes.length) return empty
const rows: CircuitNode[][] = []
for (const n of nodes) {
const row = rows[rows.length - 1]
if (row && Math.abs(n.y - row[0]!.y) <= 1) row.push(n)
else rows.push([n])
}
const items: FaceItem[] = []
let y = 0
let w = 0
for (const row of rows) {
row.sort((a, b) => a.x - b.x)
let x = 0
let h = 0
for (const n of row) {
const label = n.label?.trim() ?? ''
const iw = Math.max(n.kind === 'hex' ? 1.6 : 1.4, label.length * FACE_CHAR + 0.4)
const ih = (n.kind === 'hex' ? 2.2 : 1.2) + (label ? 0.7 : 0)
items.push({ id: n.id, kind: n.kind as 'lamp' | 'hex', label, color: n.color, x, y, w: iw, h: ih })
x += iw + 0.3
h = Math.max(h, ih)
}
w = Math.max(w, x - 0.3)
y += h + 0.3
}
return { items, w, h: y - 0.3 }
}
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, face: ReturnType<typeof faceLayout>): 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),
Math.ceil(face.w + 1.2),
)
const top = n === 1 ? -1 : -0.5
const pinBottom = n === 1 ? 1 : n - 0.5
const faceTop = pinBottom + 0.2
const faceLeft = (w - face.w) / 2
return {
body: { x: 0, y: top, w, h: pinBottom - top + (face.items.length ? face.h + 0.6 : 0) },
inputs: pins.inputs.map((p, i) => ({ ...p, dx: 0, dy: inOff + i })),
outputs: pins.outputs.map((p, i) => ({ ...p, dx: w, dy: outOff + i })),
nameY: (top + pinBottom) / 2,
face: face.items.map(it => ({ ...it, x: it.x + faceLeft, y: it.y + faceTop })),
}
}
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 noteScale(node: CircuitNode): number {
return node.size === 'sm' ? 0.8 : node.size === 'lg' ? 1.5 : 1
}
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 k = noteScale(node)
const w = Math.max(2, Math.ceil(Math.max(...lines.map(l => l.length)) * NAME_CHAR * k + 1))
return { body: { x: 0, y: -0.75 * k, w, h: (lines.length + 0.5) * k }, inputs: [], outputs: [] }
}
case 'chip': {
const def = node.chip ? getDef(node.chip) : undefined
if (!def) return MISSING_SHAPE
const pins = chipPins(def)
const face = faceLayout(def)
if (def.symbol !== 'box' && !face.items.length && 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, face)
}
}
}
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 (or a spike that doubles back). */
export function simplify(pts: Pt[]): Pt[] {
const out: Pt[] = []
for (const p of pts) {
out.push(p)
for (;;) {
const n = out.length
const [a, b, c] = [out[n - 3], out[n - 2], out[n - 1]!]
if (b && b[0] === c[0] && b[1] === c[1]) out.splice(n - 2, 1)
else if (a && b && ((a[0] === b[0] && b[0] === c[0]) || (a[1] === b[1] && b[1] === c[1]))) out.splice(n - 2, 1)
else break
}
}
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]
}