From 9754ecc0b4e92abe2d3dc3116c8efb0b581b49d5 Mon Sep 17 00:00:00 2001 From: "Fabian @ Blax Software" Date: Tue, 20 Oct 2026 19:29:16 +0200 Subject: [PATCH] A transistor counts and records, cables, pixels and screens - Every component shows its transistors (CMOS, 4 per NAND, at every depth) in the palette, its settings and the stats. Challenges keep the fewest transistors of a passing solution and announce new records. - Cables: bundle and split parts carry 2 to 32 wires as one thick cable with a width mark; "Bundle into cable" builds one from selected wires, "Remove cable" takes it apart. Cable ends only join cable ends. - Pixel part; pixels inside a component show on its box as one screen without gaps. New examples: Screen 4x4 and Demo: Screen. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 +- app/assets/css/main.css | 103 ++++++++++++++ app/components/editor/Canvas.vue | 52 ++++++-- app/components/editor/Help.vue | 3 +- app/components/editor/Inspector.vue | 33 ++++- app/components/editor/NodeSettings.vue | 33 ++++- app/components/editor/NodeView.vue | 36 ++++- app/components/editor/Palette.vue | 15 ++- app/composables/useEditor.ts | 82 +++++++++++- app/lib/logic/analyze.ts | 39 ++++++ app/lib/logic/cables.ts | 91 +++++++++++++ app/lib/logic/compile.ts | 27 +++- app/lib/logic/examples.ts | 37 +++++ app/lib/logic/geometry.ts | 85 +++++++++++- app/lib/logic/project.ts | 10 ++ app/lib/logic/types.ts | 7 + tests/cables.test.ts | 178 +++++++++++++++++++++++++ 17 files changed, 806 insertions(+), 33 deletions(-) create mode 100644 app/lib/logic/cables.ts create mode 100644 tests/cables.test.ts diff --git a/README.md b/README.md index 7a3f92c..f55ad23 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,10 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n ## What it does -- Parts: NAND, input switch, output pin, lamp, push button, clock, constant 1, ground, hex display, input panel, note. +- Parts: NAND, input switch, output pin, lamp, push button, clock, constant 1, ground, hex display, pixel, cable bundle and split, input panel, note. +- Transistors: every component shows how many it takes, counted as a CMOS NAND (4 transistors) per gate at every depth: in the palette, its settings and the circuit stats. Each challenge keeps your record, the fewest transistors of any passing solution, and says so when you beat it. +- Cables: a bundle gathers 2 to 32 wires into one thick cable, a split fans it out again in the same order; one bundle can feed several splits. Select some wires and press "Bundle into cable" to have both ends placed for you (the cable takes the wires' colour); "Remove cable" turns it back into single wires. A cable end only joins another cable end, and the cable shows its width. +- Pixels and screens: a pixel is a one-grid square that lights at 1, in five colours. Inside a component all pixels show on its box as one screen without gaps (every column and row they sit on becomes one of the screen), so you build your own LCD; see "Screen 4×4" and "Demo: Screen". - Input panel: one part with a column of controls; each row is a switch, button or clock. "Attach input panel" on a placed component docks one to its left with a row per free input, lined up with the pins and named after them. A docked panel moves with its component, gets a row when the component gains an input and loses it when the pin goes; inputs that are wired elsewhere, and rows you remove, are left alone. Inside a component a switch row keeps its position and a button row is 0. - Automatic names: copies continue a series (D0 copied gives D1, D2; A gives B), and so does placing a new input or output after a numbered one. A switch, button, lamp or output pin without a name of its own (or with an automatic one) takes the name of the component pin it gets wired to, made unique (Cin, Cin2); a name typed by hand is kept. - Every circuit is a component. Its input and output nodes become its pins, ordered top to bottom. Double-click a component to open it. @@ -23,7 +26,7 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n - Share links: `/p/`. The creator's changes save to the link automatically. Anyone else who opens it gets their own copy; their first edit detaches it from the link. - Truth table, NAND count, gate delay, and loop detection for the open circuit. The table can go full screen, be downloaded as CSV or copied as a Markdown table; the row the switches are set to is highlighted. - 17 challenges (NOT up to a D flip-flop) checked against a truth table or a step sequence. -- Example library, all built from NAND: NOT, AND, OR, NOR, XOR, XNOR, Mux, Half/Full Adder, SR Latch, D Latch, D Flip-Flop, Register 4, Increment 4, Adder 4, Counter 4, and a counter demo with a hex display. +- Example library, all built from NAND: NOT, AND, OR, NOR, XOR, XNOR, Mux, Half/Full Adder, SR Latch, D Latch, D Flip-Flop, Register 4, Increment 4, Adder 4, Counter 4, a counter demo with a hex display, and a 4×4 pixel screen with a demo. ## How the simulation works @@ -35,6 +38,7 @@ All in [app/lib/logic/](app/lib/logic/), plain TypeScript with no Vue dependency - `analyze.ts` builds truth tables, counts NANDs, computes the longest gate path, and runs challenge tests. - `examples.ts` builds the example library with a small builder; `ops.ts` holds project edits (package selection, copy/paste, prune dangling wires, recursion check). - `routing.ts` lays out all wires of a circuit (free lanes, detours, separation, crossings, and the tidy layout). +- `cables.ts` bundles wires into cables and takes them apart again. - `panels.ts` docks input panels to components and keeps them in step; `labels.ts` does series names and names taken from pins. - `wires.ts` edits wire routes (segment and corner drags, splits, branches); `project.ts` validates project data for both the browser and the server; `storage.ts` is the browser's project library. diff --git a/app/assets/css/main.css b/app/assets/css/main.css index b2bd1a5..2d6c031 100644 --- a/app/assets/css/main.css +++ b/app/assets/css/main.css @@ -369,6 +369,23 @@ kbd { color: var(--accent); } +/* Transistor count next to a component in the palette. */ +.tcount { + font-family: var(--font-mono); + font-size: 10px; + color: var(--muted); + opacity: 0.8; +} + +.comp-row:hover .tcount { + visibility: hidden; +} + +.challenges .best, +.challenge .best { + color: var(--on); +} + .nand-badge { display: inline-grid; place-items: center; @@ -731,6 +748,79 @@ kbd { stroke-width: 3; } +/* A cable: several wires in one thick sleeve. */ +.wire.cable .wire-line { + stroke-width: 6; +} + +.wire.cable.hover .wire-line { + stroke-width: 7; +} + +.wire.cable .wire-halo { + stroke-width: 13; +} + +.cable-mark { + pointer-events: none; +} + +.cable-mark path { + stroke: var(--text); + stroke-width: 1.5; +} + +.cable-mark text { + fill: var(--text); + font-family: var(--font-mono); + font-size: 9px; + font-weight: 600; +} + +/* Bundle and split: the ends of a cable. */ +.node .body.cable-end { + fill: #2a3240; + stroke: #7d8aa0; +} + +.node .cable-fan { + fill: none; + stroke: #7d8aa0; + stroke-width: 1.2; +} + +/* Pixel and pixel screens. */ +.node .pixel { + fill: #141a22; + stroke: #303a48; + stroke-width: 1; +} + +.node .pixel.on { + fill: var(--px, #e8f0f8); + stroke: var(--px, #e8f0f8); +} + +.screen-bg { + fill: #07090c; + stroke: #303a48; + stroke-width: 1; +} + +.screen-px { + fill: #11161d; +} + +.screen-px.on { + fill: var(--px, #e8f0f8); +} + +.px-yellow { --px: #ffd34d; } +.px-red { --px: #ff5a4f; } +.px-green { --px: #3ddc84; } +.px-blue { --px: #4dabff; } +.px-white { --px: #e8f0f8; } + .wire-halo { fill: none; stroke: var(--accent); @@ -1609,3 +1699,16 @@ kbd { .panel-rows input.hz { flex: 0 0 56px; } + +.challenge .score { + display: flex; + align-items: center; + gap: 6px; + margin-top: 8px; + font-size: 12px; + color: var(--muted); +} + +.challenge .score strong { + color: var(--on); +} diff --git a/app/components/editor/Canvas.vue b/app/components/editor/Canvas.vue index 355b3b4..6316677 100644 --- a/app/components/editor/Canvas.vue +++ b/app/components/editor/Canvas.vue @@ -1,5 +1,6 @@ @@ -105,6 +110,7 @@ const started = computed(() => new Map(ed.project.value.components.filter(d => d {{ d.name }} editing + {{ shortCount(ed.transistors(d.id)) }}T

{{ c.goal }}

-

{{ c.inputs.join(', ') }} → {{ c.outputs.join(', ') }}

+

+ {{ c.inputs.join(', ') }} → {{ c.outputs.join(', ') }} + + · best {{ best[c.id]!.toLocaleString() }} transistors + +

diff --git a/app/composables/useEditor.ts b/app/composables/useEditor.ts index 7af2a26..d79005b 100644 --- a/app/composables/useEditor.ts +++ b/app/composables/useEditor.ts @@ -2,10 +2,11 @@ // history, share links and the running simulation of the open circuit. // One shared instance for the whole page. -import { runSteps, stats, tableCsv, truthTable, type Stats, type TestResult, type TruthTable } from '~/lib/logic/analyze' +import { nandCounts, runSteps, stats, tableCsv, TRANSISTORS_PER_NAND, truthTable, type Stats, type TestResult, type TruthTable } from '~/lib/logic/analyze' +import { bundleWires, dissolveCable } from '~/lib/logic/cables' import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges' import { compile, rowSource } from '~/lib/logic/compile' -import { shapeOf, type Pt } from '~/lib/logic/geometry' +import { MAX_BITS, shapeOf, type Pt } from '~/lib/logic/geometry' import { adoptName, continueSeries, newPinLabel } from '~/lib/logic/labels' import { attachPanel, detachPanel, dockedPanels, newPanelRows, removeRow, syncPanels } from '~/lib/logic/panels' import { @@ -51,6 +52,15 @@ import { } from '~/lib/logic/storage' import type { CircuitNode, NodeKind, PanelControl, PanelRow, PinRef, Project, WireColor } from '~/lib/logic/types' +/** A challenge check plus how many transistors the solution uses. */ +export interface ChallengeCheck extends TestResult { + transistors: number + /** Fewest transistors of any passing solution so far, this one included. */ + best?: number + /** Set when this one beat an earlier record: that record. */ + record?: number +} + /** One pin waiting to be wired in "connect one by one". */ export interface LinkEnd { node: string @@ -377,6 +387,7 @@ function create() { } if (p.kind === 'note') node.label = 'Note' if (p.kind === 'panel') node.rows = newPanelRows() + if (p.kind === 'bundle' || p.kind === 'split') node.bits = 4 def.value.nodes.push(node) selection.value = [node.id] wireSel.value = [] @@ -388,8 +399,19 @@ function create() { return !containsDef(project.value, chipId, def.value.id) } + /** True when the pin is a cable end (bundle output, split input). */ + function isBus(nodeId: string, pin: string, dir: 'in' | 'out'): boolean { + const n = def.value.nodes.find(x => x.id === nodeId) + if (!n) return false + const s = shapeOf(n, getDef.value) + return !!(dir === 'in' ? s.inputs : s.outputs).find(p => p.key === pin)?.bus + } + function connect(from: PinRef, to: PinRef, pts?: Pt[]) { const d = def.value + if (isBus(from.node, from.pin, 'out') !== isBus(to.node, to.pin, 'in')) { + return notify('A cable runs from a bundle to a split; single wires go to the bundle’s and split’s side pins', 'error') + } const old = d.wires.find(w => w.to.node === to.node && w.to.pin === to.pin) d.wires = d.wires.filter(w => w !== old) const wire: (typeof d.wires)[number] = { id: uid('w'), from, to } @@ -678,15 +700,58 @@ function create() { open(d.id) } - function checkChallenge(): TestResult | null { + function checkChallenge(): ChallengeCheck | null { const c = CHALLENGES.find(c => c.id === def.value.challenge) if (!c) return null const res = runSteps(getDef.value, def.value.id, challengeSteps(c)) - if (res.pass && !project.value.solved.includes(c.id)) { + const used = transistors(def.value.id) + const before = project.value.best?.[c.id] + if (!res.pass) return { ...res, transistors: used, best: before } + let changed = false + if (!project.value.solved.includes(c.id)) { project.value.solved.push(c.id) - commit(false) + changed = true } - return res + const record = before === undefined || used < before + if (record) { + project.value.best = { ...project.value.best, [c.id]: used } + changed = true + } + if (changed) { + commit(false) + persist() + } + return { ...res, transistors: used, best: record ? used : before, record: record && before !== undefined ? before : undefined } + } + + // ── Transistors ─────────────────────────────────────────────────── + const nands = computed(() => nandCounts(project.value.components)) + + /** Transistors in a component at every depth, 4 per NAND gate. */ + function transistors(defId: string): number { + return (nands.value.get(defId) ?? 0) * TRANSISTORS_PER_NAND + } + + // ── Cables ──────────────────────────────────────────────────────── + function bundleSelected() { + const res = bundleWires(def.value, wireSel.value, getDef.value) + if (!res.ok) return notify(res.error, 'error') + selection.value = [res.bundle.id, res.split.id] + wireSel.value = [] + commit() + notify(`${res.bundle.bits} wires bundled into one cable`) + } + + function removeCable(bundleId: string) { + const n = dissolveCable(def.value, bundleId) + clearSelection() + commit() + notify(n ? `Cable removed; ${n} wire${n === 1 ? '' : 's'} run on their own again` : 'Cable removed') + } + + function setBits(node: CircuitNode, bits: number) { + node.bits = Math.min(MAX_BITS, Math.max(2, Math.round(bits) || 2)) + commit() } function table(): TruthTable | { error: string } { @@ -1301,6 +1366,11 @@ function create() { setTidy, tidyAll, exportTable, + transistors, + isBus, + bundleSelected, + removeCable, + setBits, swap, unlink, unpack, diff --git a/app/lib/logic/analyze.ts b/app/lib/logic/analyze.ts index dd7d9d9..4bf2185 100644 --- a/app/lib/logic/analyze.ts +++ b/app/lib/logic/analyze.ts @@ -4,6 +4,7 @@ import { compile, type Netlist } from './compile' import { chipPins, type DefLookup } from './geometry' import { Simulator } from './sim' +import type { ComponentDef } from './types' const SETTLE_BUDGET = 2_000_000 @@ -60,6 +61,44 @@ export function tableMarkdown(t: TruthTable): string { return `${lines.join('\n')}\n` } +/** A CMOS NAND gate with two inputs: two transistors in parallel to the supply, two in series to ground. */ +export const TRANSISTORS_PER_NAND = 4 + +/** + * NAND gates per component, counting everything inside it at every depth. + * Switches, lamps, displays and cables need no gates. Shared work is cached, + * so a whole library costs one pass; a component that contains itself counts 0. + */ +export function nandCounts(components: ComponentDef[]): Map { + const byId = new Map(components.map(d => [d.id, d])) + const memo = new Map() + const busy = new Set() + const count = (id: string): number => { + const known = memo.get(id) + if (known !== undefined) return known + const def = byId.get(id) + if (!def || busy.has(id)) return 0 + busy.add(id) + let n = 0 + for (const node of def.nodes) { + if (node.kind === 'nand') n++ + else if (node.kind === 'chip' && node.chip) n += count(node.chip) + } + busy.delete(id) + memo.set(id, n) + return n + } + for (const d of components) count(d.id) + return memo +} + +/** "1,234 transistors" in short form for tight spots: 1.2k. */ +export function shortCount(n: number): string { + if (n < 1000) return String(n) + if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0).replace(/\.0$/, '')}k` + return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M` +} + export interface Stats { nands: number /** Has feedback loops, so it can store state (latch, flip-flop, counter). */ diff --git a/app/lib/logic/cables.ts b/app/lib/logic/cables.ts new file mode 100644 index 0000000..03f0f3f --- /dev/null +++ b/app/lib/logic/cables.ts @@ -0,0 +1,91 @@ +// 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 } 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: a bundle just after their sources, + * a split just before their targets, wires in the order of the targets top + * to bottom. Returns the new parts, or a reason it can't. + */ +export function bundleWires(def: ComponentDef, wireIds: string[], get: DefLookup): { 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)) + const bx = right + 2 + const sx = Math.max(bx + 4, left - 3) + const color = wires.find(w => w.color)?.color + const bundle: CircuitNode = { id: uid('n'), kind: 'bundle', bits: n, x: bx, y: mean(ends.map(e => e.a.y)) - mid } + const split: CircuitNode = { id: uid('n'), kind: 'split', bits: n, x: sx, y: mean(ends.map(e => e.b.y)) - mid } + 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 } : {}) }) + }) + def.wires.push({ id: uid('w'), from: { node: bundle.id, pin: 'q' }, to: { node: split.id, pin: 'a' }, ...(color ? { color } : {}) }) + return { ok: true, bundle, split } +} + +/** + * 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 +} diff --git a/app/lib/logic/compile.ts b/app/lib/logic/compile.ts index 04fc895..f1ebd65 100644 --- a/app/lib/logic/compile.ts +++ b/app/lib/logic/compile.ts @@ -2,7 +2,7 @@ // nets. Chip boundaries and input/output pins disappear: they are aliases, // merged with union-find. Net 0 is constant LOW, net 1 constant HIGH. -import { chipPins, type ChipPins, type DefLookup } from './geometry' +import { cableBits, chipPins, type ChipPins, type DefLookup } from './geometry' import type { CircuitNode, ComponentDef, Wire } from './types' export const LOW = 0 @@ -40,9 +40,13 @@ export function inputKeys(node: CircuitNode, pins?: ChipPins): string[] { return ['a', 'b'] case 'output': case 'lamp': + case 'pixel': + case 'split': return ['a'] case 'hex': return ['b0', 'b1', 'b2', 'b3'] + case 'bundle': + return cableKeys(node) case 'chip': return pins ? pins.inputs.map(p => p.key) : [] default: @@ -63,11 +67,20 @@ export function outputKeys(node: CircuitNode, pins?: ChipPins): string[] { return pins ? pins.outputs.map(p => p.key) : [] case 'panel': return (node.rows ?? []).map(r => r.id) + case 'bundle': + return ['q'] + case 'split': + return cableKeys(node) default: return [] } } +/** Pin keys of the single wires on a bundle or split: b0, b1, … */ +export function cableKeys(node: CircuitNode): string[] { + return Array.from({ length: cableBits(node) }, (_, i) => `b${i}`) +} + /** Key of a panel row in the simulator's sources, like a switch's node id. */ export const rowSource = (nodeId: string, rowId: string) => `${nodeId}:${rowId}` @@ -133,6 +146,7 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole const wiresTo = new Map() for (const w of def.wires) wiresTo.set(`${w.to.node}:${w.to.pin}`, w) + const nodeById = new Map(def.nodes.map(n => [n.id, n])) const outNet = new Map() for (const n of def.nodes) { @@ -168,6 +182,15 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole case 'clock': clocks.push({ net: q, hz: n.hz ?? 0, key: path + n.id }) break + case 'split': { + // Wire i of the cable is whatever drives input i of the bundle at its other end. + const w = wiresTo.get(`${n.id}:a`) + const src = w && nodeById.get(w.from.node) + if (src?.kind !== 'bundle') break + const count = Math.min(cableBits(n), cableBits(src)) + for (let i = 0; i < count; i++) union(outNet.get(`${n.id}:b${i}`)!, inNet(src.id, `b${i}`)) + break + } case 'panel': // In the open circuit the rows are switches and buttons you use; // inside a component a switch row keeps its position, a button is 0. @@ -199,7 +222,7 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole if (stack.length === 1) { for (const n of def.nodes) { - if (n.kind === 'lamp' || n.kind === 'hex') for (const k of inputKeys(n)) rawFace.set(`${path}${n.id}:${k}`, inNet(n.id, k)) + if (n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel') for (const k of inputKeys(n)) rawFace.set(`${path}${n.id}:${k}`, inNet(n.id, k)) } } diff --git a/app/lib/logic/examples.ts b/app/lib/logic/examples.ts index 242a881..be863f8 100644 --- a/app/lib/logic/examples.ts +++ b/app/lib/logic/examples.ts @@ -81,6 +81,20 @@ export class Builder { note(x: number, y: number, text: string) { this.add({ kind: 'note', x, y, label: text }) } + + pixel(x: number, y: number, src: Src) { + const id = this.add({ kind: 'pixel', x, y }) + this.link(src, { node: id, pin: 'a' }) + } + + /** An input panel docked to a placed part, a switch per input, set to `on`. */ + panel(chip: Src, on: boolean[]) { + const node = this.def.nodes.find(n => n.id === chip.node)! + const pins = chipPins(this.lib.get(node.chip!)!).inputs + const rows = pins.map((p, i) => ({ id: p.key, type: 'switch' as const, name: p.label, dy: i, ...(on[i] ? { on: true } : {}) })) + const id = this.add({ kind: 'panel', x: node.x - 8, y: node.y, attach: node.id, rows }) + for (const p of pins) this.link({ node: id, pin: p.key }, { node: node.id, pin: p.key }) + } } export function exampleLibrary(): ComponentDef[] { @@ -263,6 +277,29 @@ export function exampleLibrary(): ComponentDef[] { b.hex(24, 2, Q) }) + make( + { + id: 'ex-screen4', + name: 'Screen 4×4', + group: 'Displays', + description: 'An LCD made of 16 pixels: P0 is the top left, P3 the top right, P15 the bottom right. Its box shows them as one screen.', + }, + b => { + b.note(0, -4, 'Pixels are spaced out here so they can be wired.\nOn the component box they sit side by side as one screen.') + for (let r = 0; r < 4; r++) { + for (let c = 0; c < 4; c++) b.pixel(10 + 3 * c, 5 * r + 1, b.input(`P${4 * r + c}`, 0, 5 * r + c)) + } + }, + ) + + make({ id: 'ex-demo-screen', name: 'Demo: Screen', group: 'Demos', description: 'An input panel drives the 4×4 screen. Flip its switches to draw.' }, b => { + b.note(0, -3, 'Flip the switches on the panel to draw on the screen.') + b.chip('ex-screen4', 12, 0) + const screen = b.def.nodes.at(-1)! + // Smiley: eyes, then the mouth. + b.panel({ node: screen.id, pin: '' }, [1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0].map(Boolean)) + }) + return [...lib.values()] } diff --git a/app/lib/logic/geometry.ts b/app/lib/logic/geometry.ts index c60e186..c42645f 100644 --- a/app/lib/logic/geometry.ts +++ b/app/lib/logic/geometry.ts @@ -10,6 +10,8 @@ export interface PinInfo { label: string dx: number dy: number + /** A cable pin: only joins another cable pin. */ + bus?: boolean } export interface Shape { @@ -24,10 +26,21 @@ export interface Shape { face?: FaceItem[] } -export interface FaceItem { - /** Node id inside the component. */ +export interface ScreenPixel { + /** Pixel node id inside the component. */ id: string - kind: 'lamp' | 'hex' + 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. */ @@ -67,7 +80,6 @@ export function faceLayout(def: ComponentDef): { items: FaceItem[]; w: number; h 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] @@ -92,9 +104,43 @@ export function faceLayout(def: ComponentDef): { items: FaceItem[]; w: number; h 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) { @@ -174,6 +220,32 @@ const CLOCK_SHAPE: Shape = { 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))) +} + +/** Bundle: one input per wire on the left, the cable leaves on the right. Split: the mirror image. */ +function cableShape(node: CircuitNode): Shape { + const n = cableBits(node) + const wires = Array.from({ length: n }, (_, i) => ({ key: `b${i}`, label: String(i), dy: i })) + const mid = Math.floor((n - 1) / 2) + const body = { x: 0, y: -0.5, w: 1, h: n } + 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[] = [] @@ -231,6 +303,11 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape { return HEX_SHAPE case 'panel': return panelShape(node) + case 'bundle': + case 'split': + return cableShape(node) + case 'pixel': + return PIXEL_SHAPE case 'note': { const lines = noteLines(node) const k = noteScale(node) diff --git a/app/lib/logic/project.ts b/app/lib/logic/project.ts index 1d0547e..29e063d 100644 --- a/app/lib/logic/project.ts +++ b/app/lib/logic/project.ts @@ -10,6 +10,7 @@ function cleanNode(n: CircuitNode) { if (n.key !== undefined && !(typeof n.key === 'string' && n.key.length === 1)) delete n.key if (n.size !== undefined && !['sm', 'md', 'lg'].includes(n.size)) delete n.size if (n.autoLabel !== undefined && n.autoLabel !== true) delete n.autoLabel + if (n.bits !== undefined && !(Number.isInteger(n.bits) && n.bits >= 2 && n.bits <= 32)) delete n.bits if (n.attach !== undefined && typeof n.attach !== 'string') delete n.attach if (n.skip !== undefined) { if (Array.isArray(n.skip)) n.skip = n.skip.filter(k => typeof k === 'string').slice(0, MAX_ROWS) @@ -66,9 +67,18 @@ export function toProject(data: unknown): Project { ...(p.settings?.tidy === true ? { tidy: true } : {}), }, solved: Array.isArray(p.solved) ? p.solved.filter(s => typeof s === 'string') : [], + ...(bestOf(p.best) ? { best: bestOf(p.best)! } : {}), } } +/** Challenge records: challenge id → fewest transistors, whole non-negative numbers only. */ +function bestOf(raw: unknown): Record | null { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null + const out: Record = {} + for (const [k, v] of Object.entries(raw)) if (typeof v === 'number' && Number.isInteger(v) && v >= 0 && k.length <= 64) out[k] = v + return Object.keys(out).length ? out : null +} + export function parseProject(json: string): Project { if (json.length > LIMITS.bytes) throw new Error('File too large') let data: unknown diff --git a/app/lib/logic/types.ts b/app/lib/logic/types.ts index 07c6d88..a71eb8f 100644 --- a/app/lib/logic/types.ts +++ b/app/lib/logic/types.ts @@ -14,6 +14,9 @@ export type BuiltinKind = | 'hex' // 4-bit hex display | 'note' // text annotation, no pins | 'panel' // column of switches, buttons and clocks, one output per row + | 'bundle' // gathers several wires into one cable + | 'split' // fans a cable out into its wires again + | 'pixel' // one square of a screen; inside a component, pixels form a screen on its box export type NodeKind = BuiltinKind | 'chip' @@ -40,6 +43,8 @@ export interface CircuitNode { size?: NoteSize /** Set while the label was given automatically, so a new connection may rename it. */ autoLabel?: boolean + /** Number of wires in the cable of a bundle or split. */ + bits?: number /** Rows of a panel, top to bottom. */ rows?: PanelRow[] /** Panel docked to a component: the id of that chip node. Its rows follow the chip's input pins. */ @@ -128,4 +133,6 @@ export interface Project { settings: Settings /** Challenge ids the user has passed. */ solved: string[] + /** Fewest transistors a passing solution used, per challenge id. */ + best?: Record } diff --git a/tests/cables.test.ts b/tests/cables.test.ts new file mode 100644 index 0000000..368d8af --- /dev/null +++ b/tests/cables.test.ts @@ -0,0 +1,178 @@ +import { describe, expect, it } from 'vitest' +import { nandCounts, shortCount, stats, TRANSISTORS_PER_NAND } from '../app/lib/logic/analyze' +import { bundleWires, cableOf, dissolveCable } from '../app/lib/logic/cables' +import { compile } from '../app/lib/logic/compile' +import { faceLayout, screenLayout, shapeOf } from '../app/lib/logic/geometry' +import { createProject, lookup, pruneWires } from '../app/lib/logic/ops' +import { toProject } from '../app/lib/logic/project' +import { Simulator } from '../app/lib/logic/sim' +import type { ComponentDef, Project } from '../app/lib/logic/types' + +/** Four switches wired straight to four lamps. */ +function lamps(): { p: Project; def: ComponentDef } { + const p = createProject({ examples: false }) + const def: ComponentDef = { + id: 'root', + name: 'Root', + symbol: 'box', + nodes: [ + ...[0, 1, 2, 3].map(i => ({ id: `s${i}`, kind: 'input' as const, x: 0, y: i * 2, label: `S${i}` })), + ...[0, 1, 2, 3].map(i => ({ id: `l${i}`, kind: 'lamp' as const, x: 30, y: 10 + i * 2 })), + ], + wires: [0, 1, 2, 3].map(i => ({ id: `w${i}`, from: { node: `s${i}`, pin: 'q' }, to: { node: `l${i}`, pin: 'a' }, ...(i === 0 ? { color: 'blue' as const } : {}) })), + } + p.components.push(def) + return { p, def } +} + +/** Lamp values for every switch pattern, as strings like "1010". */ +function behaviour(p: Project, def: ComponentDef): string[] { + const out: string[] = [] + for (let m = 0; m < 16; m++) { + const s = new Simulator(compile(lookup(p), def.id)) + for (let i = 0; i < 4; i++) s.setSource(`s${i}`, ((m >> i) & 1) === 1) + s.run() + out.push([0, 1, 2, 3].map(i => s.pin(`l${i}`, 'a')).join('')) + } + return out +} + +describe('cables', () => { + it('bundling wires into a cable keeps every signal on its own wire', () => { + const { p, def } = lamps() + const before = behaviour(p, def) + const res = bundleWires(def, ['w0', 'w1', 'w2', 'w3'], lookup(p)) + if (!res.ok) throw new Error(res.error) + expect(res.bundle.bits).toBe(4) + expect(def.wires.filter(w => w.from.node === res.bundle.id)).toHaveLength(1) + expect(def.wires).toHaveLength(9) + expect(behaviour(p, def)).toEqual(before) + // The cable takes the colour of the wires. + expect(def.wires.find(w => w.from.node === res.bundle.id)!.color).toBe('blue') + // Both ends sit between sources and targets. + expect(res.bundle.x).toBeGreaterThan(2) + expect(res.split.x).toBeLessThan(30) + }) + + it('takes a cable apart again into the same connections', () => { + const { p, def } = lamps() + const res = bundleWires(def, ['w0', 'w1', 'w2', 'w3'], lookup(p)) + if (!res.ok) throw new Error(res.error) + const cable = def.wires.find(w => w.from.node === res.bundle.id)! + expect(cableOf(def, cable)?.id).toBe(res.bundle.id) + expect(dissolveCable(def, res.bundle.id)).toBe(4) + expect(def.nodes.some(n => n.kind === 'bundle' || n.kind === 'split')).toBe(false) + expect(def.wires.map(w => `${w.from.node}>${w.to.node}`).sort()).toEqual(['s0>l0', 's1>l1', 's2>l2', 's3>l3']) + expect(behaviour(p, def)).toEqual(behaviourOfFresh()) + }) + + it('a cable can fan out to two splits, and a narrower split takes the first wires', () => { + const { p, def } = lamps() + const res = bundleWires(def, ['w0', 'w1', 'w2', 'w3'], lookup(p)) + if (!res.ok) throw new Error(res.error) + def.nodes.push({ id: 'sp2', kind: 'split', bits: 2, x: 20, y: 30 }, { id: 'x0', kind: 'lamp', x: 30, y: 30 }, { id: 'x1', kind: 'lamp', x: 30, y: 31 }) + def.wires.push( + { id: 'c2', from: { node: res.bundle.id, pin: 'q' }, to: { node: 'sp2', pin: 'a' } }, + { id: 'o0', from: { node: 'sp2', pin: 'b0' }, to: { node: 'x0', pin: 'a' } }, + { id: 'o1', from: { node: 'sp2', pin: 'b1' }, to: { node: 'x1', pin: 'a' } }, + ) + const s = new Simulator(compile(lookup(p), def.id)) + s.setSource('s1', true) + s.run() + expect([s.pin('x0', 'a'), s.pin('x1', 'a')]).toEqual([0, 1]) + }) + + it('refuses one wire, and cables inside cables', () => { + const { p, def } = lamps() + expect(bundleWires(def, ['w0'], lookup(p)).ok).toBe(false) + const res = bundleWires(def, ['w0', 'w1'], lookup(p)) + if (!res.ok) throw new Error(res.error) + const cable = def.wires.find(w => w.from.node === res.bundle.id)! + expect(bundleWires(def, [cable.id, 'w2'], lookup(p)).ok).toBe(false) + }) + + it('narrowing a cable end drops the wires on pins that are gone', () => { + const { p, def } = lamps() + const res = bundleWires(def, ['w0', 'w1', 'w2', 'w3'], lookup(p)) + if (!res.ok) throw new Error(res.error) + res.split.bits = 2 + pruneWires(p) + expect(def.wires.filter(w => w.from.node === res.split.id).map(w => w.from.pin).sort()).toEqual(['b0', 'b1']) + expect(shapeOf(res.split, lookup(p)).outputs).toHaveLength(2) + }) +}) + +function behaviourOfFresh() { + const { p, def } = lamps() + return behaviour(p, def) +} + +describe('transistors', () => { + it('counts 4 per NAND through every level, the same as the compiled circuit', () => { + const p = createProject({ examples: true }) + const counts = nandCounts(p.components) + for (const d of p.components) expect(counts.get(d.id), d.name).toBe(stats(compile(lookup(p), d.id)).nands) + expect(counts.get('ex-not')! * TRANSISTORS_PER_NAND).toBe(4) + expect(counts.get('ex-xor')! * TRANSISTORS_PER_NAND).toBe(16) + expect(counts.get('ex-fa')).toBeGreaterThan(counts.get('ex-ha')!) + }) + + it('does not hang on a component that contains itself', () => { + const loop: ComponentDef = { id: 'a', name: 'A', symbol: 'box', nodes: [{ id: 'x', kind: 'chip', chip: 'a', x: 0, y: 0 }, { id: 'n', kind: 'nand', x: 0, y: 0 }], wires: [] } + expect(nandCounts([loop]).get('a')).toBe(1) + }) + + it('shortens big numbers', () => { + expect(shortCount(36)).toBe('36') + expect(shortCount(1234)).toBe('1.2k') + expect(shortCount(56_000)).toBe('56k') + expect(shortCount(2_500_000)).toBe('2.5M') + }) + + it('keeps challenge records through validation and drops nonsense', () => { + const p = createProject({ examples: false }) + const data = JSON.parse(JSON.stringify({ ...p, best: { xor: 16, and: -2, or: 'x', nor: 3.5 } })) + expect(toProject(data).best).toEqual({ xor: 16 }) + expect(toProject(JSON.parse(JSON.stringify(p))).best).toBeUndefined() + }) +}) + +describe('pixel screens', () => { + it('packs spaced-out pixels into one screen without gaps', () => { + const def: ComponentDef = { + id: 's', + name: 'S', + symbol: 'box', + nodes: [ + { id: 'a', kind: 'pixel', x: 10, y: 1 }, + { id: 'b', kind: 'pixel', x: 13, y: 1 }, + { id: 'c', kind: 'pixel', x: 10, y: 6, color: 'green' }, + ], + wires: [], + } + const screen = screenLayout(def)! + expect(screen.pixels).toEqual([ + { id: 'a', col: 0, row: 0, color: undefined }, + { id: 'b', col: 1, row: 0, color: undefined }, + { id: 'c', col: 0, row: 1, color: 'green' }, + ]) + expect([screen.w, screen.h]).toEqual([2, 2]) + expect(faceLayout(def).items.map(i => i.kind)).toEqual(['screen']) + }) + + it('the example screen shows what its inputs say, on the chip box', () => { + const p = createProject({ examples: true }) + const get = lookup(p) + const demo = get('ex-demo-screen')! + const chip = demo.nodes.find(n => n.kind === 'chip')! + const shape = shapeOf(chip, get) + const face = shape.face!.find(f => f.kind === 'screen')! + expect(face.pixels).toHaveLength(16) + const s = new Simulator(compile(get, demo.id)) + const panel = demo.nodes.find(n => n.kind === 'panel')! + for (const r of panel.rows!) s.setSource(`${panel.id}:${r.id}`, !!r.on) + s.run() + const lit = face.pixels!.map(px => s.face(chip.id, px.id, 'a')) + expect(lit.join('')).toBe('1001000010010110') + }) +})