logigate/app/lib/logic/geometry.ts

498 lines
18 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, FaceShape, LampColor, PanelRow, SymbolKind } from './types'
export const GRID = 16
export interface PinInfo {
key: string
label: string
dx: number
dy: number
/** A cable pin: only joins another cable pin. */
bus?: boolean
}
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[]
/** Where a box prints its name (its middle), or null when it is left off; empty: centred. */
nameAt?: { x: number; y: number } | null
/** Drawings on a hand-drawn box, in grid units relative to the chip node. */
drawing?: FaceShape[]
}
export interface ScreenPixel {
/** Pixel node id inside the component. */
id: string
col: number
row: number
color?: LampColor
}
export interface FaceItem {
/** Node id inside the component; for a screen, the first pixel's. */
id: string
kind: 'lamp' | 'hex' | 'screen'
/** Screen only: its pixels and the size of one, in grid units. */
pixels?: ScreenPixel[]
px?: number
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 }[]
}
/** Pin key of a panel row: the same key the row has as a switch in the simulator. */
export const rowPin = (panelId: string, rowId: string) => `${panelId}:${rowId}`
/** Panel rows that are input pins of their component: switches and buttons, unless the panel keeps them inside. */
export const isPinRow = (panel: CircuitNode, row: PanelRow) => !panel.inner && row.type !== 'clock'
/**
* A component's pins, ordered top to bottom: its input and output nodes,
* and the switch and button rows of its input panels, which count as inputs.
*/
export function chipPins(def: ComponentDef): ChipPins {
const inputs: { key: string; label: string; x: number; y: number }[] = []
for (const n of def.nodes) {
if (n.kind === 'input') inputs.push({ key: n.id, label: n.label?.trim() ?? '', x: n.x, y: n.y })
else if (n.kind === 'panel') {
const rows = n.rows ?? []
const at = panelOffsets(rows)
rows.forEach((r, i) => {
if (isPinRow(n, r)) inputs.push({ key: rowPin(n.id, r.id), label: r.label?.trim() || r.name?.trim() || '', x: n.x, y: n.y + at[i]! })
})
}
}
inputs.sort((a, b) => a.y - b.y || a.x - b.x)
// Outputs: output pins and the rows of output panels.
const outputs: { key: string; label: string; x: number; y: number }[] = []
for (const n of def.nodes) {
if (n.kind === 'output') outputs.push({ key: n.id, label: n.label?.trim() ?? '', x: n.x, y: n.y })
else if (n.kind === 'outpanel' && !n.inner) {
const rows = n.rows ?? []
const at = panelOffsets(rows)
rows.forEach((r, i) => outputs.push({ key: rowPin(n.id, r.id), label: r.label?.trim() || r.name?.trim() || '', x: n.x, y: n.y + at[i]! }))
}
}
outputs.sort((a, b) => a.y - b.y || a.x - b.x)
return {
inputs: inputs.map((p, i) => ({ key: p.key, label: p.label || `in${i + 1}` })),
outputs: outputs.map((p, i) => ({ key: p.key, label: p.label || `out${i + 1}` })),
}
}
/**
* 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)
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
}
const screen = screenLayout(def)
if (screen) {
w = Math.max(w, screen.w)
items.push({ ...screen, x: (w - screen.w) / 2, y })
y += screen.h + 0.3
}
if (!items.length) return empty
return { items, w, h: y - 0.3 }
}
/**
* Pixels inside a component, drawn as one screen without gaps: every
* distinct column and row they sit on becomes a column and row of the
* screen, so they can be spaced out inside for wiring.
*/
export function screenLayout(def: ComponentDef): FaceItem | null {
const pixels = def.nodes.filter(n => n.kind === 'pixel')
if (!pixels.length) return null
const xs = [...new Set(pixels.map(n => n.x))].sort((a, b) => a - b)
const ys = [...new Set(pixels.map(n => n.y))].sort((a, b) => a - b)
const col = new Map(xs.map((x, i) => [x, i]))
const row = new Map(ys.map((y, i) => [y, i]))
const size = Math.max(xs.length, ys.length)
const px = size <= 8 ? 1 : size <= 32 ? 0.5 : 0.25
return {
id: pixels[0]!.id,
kind: 'screen',
label: '',
x: 0,
y: 0,
w: xs.length * px,
h: ys.length * px,
px,
pixels: pixels.map(n => ({ id: n.id, col: col.get(n.x)!, row: row.get(n.y)!, color: n.color })),
}
}
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) }],
}
}
/**
* A box drawn by hand: the size it was given (never shorter than its pins
* need), everything placed where it was put, the rest where it would go
* anyway, and its drawings.
*/
function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeof faceLayout>): Shape {
const auto = boxShape(def.name, pins, face)
const d = def.design!
const top = auto.body.y
const pinH = Math.max(pins.inputs.length, pins.outputs.length, 1)
const w = Math.max(2, d.w)
const h = Math.max(pinH === 1 ? 2 : pinH, d.h)
const hide = new Set(d.hide ?? [])
const place = d.place ?? {}
return {
...auto,
body: { x: 0, y: top, w, h },
outputs: auto.outputs.map(p => ({ ...p, dx: w })),
face: (auto.face ?? [])
.filter(it => !hide.has(it.kind === 'screen' ? 'screen' : it.id))
.map(it => {
const at = place[it.kind === 'screen' ? 'screen' : it.id]
return at ? { ...it, x: at.x, y: top + at.y } : it
}),
nameAt: hide.has('name') ? null : place.name ? { x: place.name.x, y: top + place.name.y } : undefined,
drawing: (d.shapes ?? []).map(sh => ({ ...sh, y: top + sh.y })),
}
}
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 }],
}
// Output pins and lamps pass their signal on: the pin on the right carries the same value.
const SINK_SHAPE: Shape = {
body: { x: 0, y: -0.75, w: 2, h: 1.5 },
inputs: [{ key: 'a', label: '', dx: 0, dy: 0 }],
outputs: [{ key: 'q', label: '', dx: 2, dy: 0 }],
}
/** Width of a signal tag's flag, from its name. */
function tagWidth(node: CircuitNode): number {
return Math.max(2.5, Math.ceil((signalName(node) || '?').length * 0.45 + 1.4))
}
/** The name a signal tag sends, or a reference uses. */
export const signalName = (node: CircuitNode) => node.label?.trim() ?? ''
/** Output panel: a lamp per row with its name, the wire in on the left and on again on the right. */
function outPanelShape(node: CircuitNode): Shape {
const rows = node.rows ?? []
const dys = panelOffsets(rows)
const labels = rows.map(rowLabel)
const w = Math.max(3, Math.ceil(labels.reduce((m, l) => Math.max(m, l.length), 0) * LABEL_CHAR + 2.4))
const last = dys.length ? dys[dys.length - 1]! : 0
return {
body: { x: 0, y: -0.5, w, h: last + 1 },
inputs: rows.map((r, i) => ({ key: r.id, label: labels[i]!, dx: 0, dy: dys[i]! })),
outputs: rows.map((r, i) => ({ key: r.id, label: labels[i]!, dx: w, dy: dys[i]! })),
}
}
/** Send: the wire comes in on the left into a flag carrying the name. */
function tagShape(node: CircuitNode): Shape {
const w = tagWidth(node)
return { body: { x: 0.5, y: -0.6, w, h: 1.2 }, inputs: [{ key: 'a', label: '', dx: 0, dy: 0 }], outputs: [] }
}
/** Use: a flag with the name, the signal leaves on the right. */
function refShape(node: CircuitNode): Shape {
const w = tagWidth(node)
return { body: { x: 0, y: -0.6, w, h: 1.2 }, inputs: [], outputs: [{ key: 'q', label: '', dx: w + 0.5, dy: 0 }] }
}
// A hex display passes its four bits on, so it can sit in the middle of a bus.
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: ['1', '2', '4', '8'].map((label, i) => ({ key: `q${i}`, label, dx: 3, dy: i })),
}
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 const MAX_BITS = 32
/** Wires in a cable, within range. */
export function cableBits(node: CircuitNode): number {
const n = node.bits ?? 4
return Math.min(MAX_BITS, Math.max(2, Math.round(n)))
}
/** Row of each wire of a cable end below the first: evenly `pitch` apart, or as plugged. */
export function cableOffsets(node: CircuitNode): number[] {
const n = cableBits(node)
const o = node.offsets
if (o?.length === n && o[0] === 0 && o.every((v, i) => i === 0 || v > o[i - 1]!)) return o
const pitch = Math.max(1, Math.min(8, Math.round(node.pitch ?? 1)))
return Array.from({ length: n }, (_, i) => i * pitch)
}
/** Bundle: one input per wire on the left, the cable leaves on the right. Split: the mirror image. */
function cableShape(node: CircuitNode): Shape {
const dys = cableOffsets(node)
const wires = dys.map((dy, i) => ({ key: `b${i}`, label: node.names?.[i] || String(i), dy }))
const last = dys[dys.length - 1]!
const mid = Math.floor(last / 2)
const body = { x: 0, y: -0.5, w: 1, h: last + 1 }
if (node.kind === 'bundle') {
return { body, inputs: wires.map(p => ({ ...p, dx: 0 })), outputs: [{ key: 'q', label: '', dx: 1, dy: mid, bus: true }] }
}
return { body, inputs: [{ key: 'a', label: '', dx: 0, dy: mid, bus: true }], outputs: wires.map(p => ({ ...p, dx: 1 })) }
}
const PIXEL_SHAPE: Shape = {
body: { x: 0, y: -0.5, w: 1, h: 1 },
inputs: [{ key: 'a', label: '', dx: 0, dy: 0 }],
outputs: [],
}
/** Grid offset of every panel row below the first one. */
export function panelOffsets(rows: PanelRow[]): number[] {
const out: number[] = []
for (const r of rows) {
const prev = out.length ? out[out.length - 1]! : -1
out.push(r.dy !== undefined && r.dy > prev ? r.dy : prev + 1)
}
return out
}
/** Name shown next to a panel row: the user's, the driven pin's, or its number. */
export function rowLabel(row: PanelRow, i: number): string {
return row.label?.trim() || row.name?.trim() || String(i + 1)
}
/** Width of the control drawn in each panel row, in grid units. */
export const PANEL_CONTROL_W = 2.2
function panelShape(node: CircuitNode): Shape {
const rows = node.rows ?? []
const dys = panelOffsets(rows)
const labels = rows.map(rowLabel)
const keys = rows.some(r => r.key) ? 0.7 : 0
const w = Math.max(4, Math.ceil(labels.reduce((m, l) => Math.max(m, l.length), 0) * LABEL_CHAR + PANEL_CONTROL_W + 1.1 + keys))
const last = dys.length ? dys[dys.length - 1]! : 0
return {
body: { x: 0, y: -0.5, w, h: last + 1 },
inputs: [],
outputs: rows.map((r, i) => ({ key: r.id, label: labels[i]!, dx: w, dy: dys[i]! })),
}
}
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 'panel':
return panelShape(node)
case 'bundle':
case 'split':
return cableShape(node)
case 'pixel':
return PIXEL_SHAPE
case 'outpanel':
return outPanelShape(node)
case 'tag':
return tagShape(node)
case 'ref':
return refShape(node)
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.design) return designedShape(def, pins, face)
if (def.symbol !== 'box' && !face.items.length && pins.outputs.length === 1 && pins.inputs.length >= 1 && pins.inputs.length <= 16) {
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]
}