logigate/app/lib/logic/bulk.ts

135 lines
5.3 KiB
TypeScript
Raw Normal View History

// Working on many parts at once: grouping a selection, numbered names,
// the list of a circuit's inputs and outputs, where its transistors are,
// and lining parts up.
import { TRANSISTORS_PER_NAND } from './analyze'
import type { DefLookup } from './geometry'
import { SINK_KINDS, SOURCE_KINDS } from './ops'
import type { CircuitNode, ComponentDef, PanelRow } from './types'
/** Top to bottom, then left to right: the order pins and names follow. */
export const byPosition = (a: CircuitNode, b: CircuitNode) => a.y - b.y || a.x - b.x
/**
* Names for `count` parts from a pattern. Each run of # becomes a number
* counting up from `start`, padded to the run's length (D# → D0, D1;
* Q## → Q00, Q01). Without #, several parts get the number appended.
*/
export function numberedNames(pattern: string, count: number, start = 0): string[] {
const p = pattern.trim()
return Array.from({ length: count }, (_, i) => {
const n = start + i
if (p.includes('#')) return p.replace(/#+/g, run => String(n).padStart(run.length, '0'))
return count === 1 ? p : `${p}${n}`
})
}
/** What sort of part a node is: its kind, or the component it places. */
export const typeKey = (n: CircuitNode) => (n.kind === 'chip' ? `chip:${n.chip}` : n.kind)
export type Family = 'logic' | 'source' | 'sink'
/** The swap family all nodes share (they can all become the same part), or null. */
export function sharedFamily(nodes: CircuitNode[]): Family | null {
const fam = (n: CircuitNode): Family | null =>
n.kind === 'nand' || n.kind === 'chip' ? 'logic' : SOURCE_KINDS.includes(n.kind) ? 'source' : SINK_KINDS.includes(n.kind) ? 'sink' : null
const first = nodes[0] && fam(nodes[0])
return first && nodes.every(n => fam(n) === first) ? first : null
}
export interface IoEntry {
node: CircuitNode
/** For a panel: the row this entry stands for. */
row?: PanelRow
/** Pins are what the circuit shows when used as a component; the rest stays inside. */
pin: boolean
}
/**
* A circuit's inputs and outputs, for renaming them in one place. Pins come
* first, in pin order (top to bottom), then switches, buttons, clocks and
* panel rows that stay inside, then lamps and displays.
*/
export function ioList(def: ComponentDef): { inputs: IoEntry[]; outputs: IoEntry[] } {
const of = (kinds: string[]) => def.nodes.filter(n => kinds.includes(n.kind)).sort(byPosition)
const inputs: IoEntry[] = [
...of(['input']).map(node => ({ node, pin: true })),
...of(['button', 'clock']).map(node => ({ node, pin: false })),
...of(['panel']).flatMap(node => (node.rows ?? []).map(row => ({ node, row, pin: false }))),
]
const outputs: IoEntry[] = [...of(['output']).map(node => ({ node, pin: true })), ...of(['lamp', 'hex']).map(node => ({ node, pin: false }))]
return { inputs, outputs }
}
export const entryLabel = (e: IoEntry) => (e.row ? (e.row.label ?? '') : (e.node.label ?? '')).trim()
/** Names that more than one entry uses (pins must be told apart, e.g. for challenges and truth tables). */
export function duplicateNames(entries: IoEntry[]): Set<string> {
const seen = new Set<string>()
const dup = new Set<string>()
for (const e of entries) {
const l = entryLabel(e).toLowerCase()
if (!l) continue
if (seen.has(l)) dup.add(l)
seen.add(l)
}
return dup
}
export interface CostLine {
key: string
name: string
count: number
/** Transistors in one of them. */
each: number
total: number
ids: string[]
}
/**
* Where a circuit's transistors are: its own parts grouped by type, most
* transistors first. Parts without gates (switches, lamps, cables) are left out.
*/
export function transistorBreakdown(def: ComponentDef, nandsPerDef: Map<string, number>, get: DefLookup): CostLine[] {
const lines = new Map<string, CostLine>()
for (const n of def.nodes) {
let each = 0
let name = ''
if (n.kind === 'nand') {
each = TRANSISTORS_PER_NAND
name = 'NAND'
} else if (n.kind === 'chip' && n.chip) {
each = (nandsPerDef.get(n.chip) ?? 0) * TRANSISTORS_PER_NAND
name = get(n.chip)?.name ?? 'Missing component'
}
if (!each) continue
const key = typeKey(n)
const line = lines.get(key) ?? { key, name, count: 0, each, total: 0, ids: [] }
line.count++
line.total += each
line.ids.push(n.id)
lines.set(key, line)
}
return [...lines.values()].sort((a, b) => b.total - a.total || a.name.localeCompare(b.name))
}
export type Arrange = 'left' | 'right' | 'top' | 'bottom' | 'spread-x' | 'spread-y'
/** Lines parts up on their left/right/top/bottom position, or spreads them evenly between the outermost two. */
export function arrangeNodes(nodes: CircuitNode[], how: Arrange): void {
if (nodes.length < 2) return
const xs = nodes.map(n => n.x)
const ys = nodes.map(n => n.y)
if (how === 'left') for (const n of nodes) n.x = Math.min(...xs)
else if (how === 'right') for (const n of nodes) n.x = Math.max(...xs)
else if (how === 'top') for (const n of nodes) n.y = Math.min(...ys)
else if (how === 'bottom') for (const n of nodes) n.y = Math.max(...ys)
else {
const axis = how === 'spread-x' ? 'x' : 'y'
const sorted = [...nodes].sort((a, b) => a[axis] - b[axis])
const lo = sorted[0]![axis]
const step = (sorted[sorted.length - 1]![axis] - lo) / (sorted.length - 1)
sorted.forEach((n, i) => (n[axis] = Math.round(lo + i * step)))
}
}