From e55bd4731004e816971b460154357cbde7da59a0 Mon Sep 17 00:00:00 2001 From: "Fabian @ Blax Software" Date: Mon, 26 Oct 2026 18:09:18 +0100 Subject: [PATCH] A memory that stays: circuits keep their bits across visits and saves; Power off and on What latches, flip-flops, registers and RAM built from NANDs hold is no longer lost when you go into a component and come back, reload the page or open the project on another computer. Leaving a circuit puts its bits in the project, and opening it starts from them. Only the gates on feedback loops can hold a bit, so only those that are 1 are kept, plus the clocks that are high: each node id once, each gate as the path levels it shares with the gate before plus the rest. 1,024 flip-flops take about 30 KB. Restoring runs the gates in the order signals flow, so the gates in front of a latch are right before it reads them; gates that no longer exist after an edit are ignored. The bits go with every save, file, share link and account upload. Between saves (a clock running, a button pressed) they are put in this browser's copy every 30 seconds and when the page is left, without counting as a change: no sync, savegame or undo step of their own, and never over a save made in another tab. Projects without them start from all zeros as before. "Power off and on" in the menu on the circuit's name, or with Space, starts the open circuit again from all zeros. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + app/components/editor/Help.vue | 1 + app/components/editor/QuickAdd.vue | 1 + app/components/editor/Toolbar.vue | 9 + app/composables/useEditor.ts | 63 +++++- app/lib/logic/project.ts | 16 ++ app/lib/logic/sim.ts | 7 +- app/lib/logic/state.ts | 137 +++++++++++++ app/lib/logic/types.ts | 17 ++ tests/state.test.ts | 297 +++++++++++++++++++++++++++++ 10 files changed, 543 insertions(+), 7 deletions(-) create mode 100644 app/lib/logic/state.ts create mode 100644 tests/state.test.ts diff --git a/README.md b/README.md index f5f4f59..b66dc47 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n - Saves are handled like a game: the main menu's "Load game" lists every save (open, rename, copy, delete, savegames, recently deleted, new, open a file), and in the editor Esc (with nothing selected) or the project button opens the pause menu: Resume, Save, Save as copy, Load, Settings, How to play, Main menu. Export a project file, open a file as a new project, or add the components of a file to the open project. - Accounts: email and password. Signed in, every project in the browser is also kept in the account and synced in both directions (on sign-in, on focus, every minute, and two seconds after a change). One save per project on every device: if two computers changed the same project, the newer save wins everywhere and the other one is kept as a savegame of that project (never as a second project). A new browser keeps its starter project unsaved until something changes in it, and while signed in the main menu waits for the account's saves before anything can be started, so a second device never makes a twin. - 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. +- Memory that stays: what latches, flip-flops, registers and RAM built from NANDs hold is kept per circuit, like a memory chip. Going into a component and back, reloading, or opening the project on another computer, a circuit starts from the bits it held. They are saved with the project (only the gates on feedback loops that are 1, plus the clocks that are high: 1,024 flip-flops take about 30 KB), whenever it is saved anyway. Between saves (a clock running, a button pressed) they go into this browser's copy every 30 seconds and when the page is left, without counting as a change, so they never start a sync or a savegame of their own; the account gets them with the next save. "Power off and on" (menu on the circuit's name, or Space) starts the circuit again from all zeros. Switches keep their positions as before; buttons are let go. - 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, a counter demo with a hex display, and a 4×4 pixel screen with a demo. @@ -48,6 +49,7 @@ All in [app/lib/logic/](app/lib/logic/), plain TypeScript with no Vue dependency - `compile.ts` flattens the component tree into a list of NAND gates over numbered nets. Chip boundaries and pins are aliases, merged with union-find. Net 0 is constant 0, net 1 constant 1. - `sim.ts` is event-driven: a net change queues the gates that read it, and gates run in FIFO order on the newest values. NAND latches settle deterministically; a loop with an odd number of inversions never settles and the top bar shows "Oscillating". - Gate outputs are keyed by their path ("chipNode/chipNode/nand"), so latch state survives editing. +- `state.ts` finds the gates on feedback loops (strongly connected gates, Tarjan) and packs those that are 1 for the project: each node id once, each gate as the path levels it shares with the gate before plus the rest. Restoring runs the gates in the order signals flow, so the gates in front of a latch are right before the latch reads them; ids that no longer exist are ignored. - `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). diff --git a/app/components/editor/Help.vue b/app/components/editor/Help.vue index f10e5ef..56bc5ac 100644 --- a/app/components/editor/Help.vue +++ b/app/components/editor/Help.vue @@ -26,6 +26,7 @@ const SHORTCUTS: [string, string][] = [ ['N, I, O, L, B, C, H, T, P, X', 'Place NAND, input, output, lamp, button, clock, hex display, note, input panel, pixel'], ['Bar at the bottom', 'Point at a kind of part to see them all; click to place, drag onto the canvas, pin the ones you use most to the bar itself (right-click a pinned part to unpin it)'], ['Main (top bar)', 'Back to the main circuit; the names after it lead back to each component you entered'], + ['Power off and on (circuit name in the top bar, or Space)', 'Latches, flip-flops and memory keep their bits when you go into a component and back, and in the saved project; this starts the circuit again from all zeros'], ['[', 'Hide or show the panel on the left (This and Pins)'], ['Connectors (bottom bar)', 'Make a cable type of your own (HDMI, RJ45): its lines; place its Out and In ports; one cable joins them'], ['Select wires, Ctrl+G', 'Bundle them into one cable; an end whose wires all meet one part plugs straight into it'], diff --git a/app/components/editor/QuickAdd.vue b/app/components/editor/QuickAdd.vue index a43ab8d..988369d 100644 --- a/app/components/editor/QuickAdd.vue +++ b/app/components/editor/QuickAdd.vue @@ -44,6 +44,7 @@ const ACTIONS: Action[] = [ { id: 'tidy-all', label: 'Tidy every circuit', icon: 'lucide:sparkles', aka: 'wires clean route layout all components', run: () => ed.tidyEverything() }, { id: 'examples', label: 'Add example parts', icon: 'lucide:book-open', aka: 'library not and or adder counter', run: () => ed.loadExamples() }, { id: 'connector', label: 'New connector type', icon: 'lucide:plug', aka: 'cable hdmi rj45 bus port', when: () => ed.canPlaceKind('portin'), run: () => ed.addConnector() }, + { id: 'power', label: 'Power off and on', icon: 'lucide:power', aka: 'reset state memory bits clear zero restart', when: () => ed.circuitStats.value.sequential, run: () => ed.resetState() }, { id: 'undo', label: 'Undo', icon: 'lucide:undo-2', keys: 'Ctrl+Z', when: () => ed.canUndo.value, run: () => ed.undo() }, { id: 'print', label: 'Print or save as PDF', icon: 'lucide:printer', keys: 'Ctrl+P', aka: 'sheet export', run: () => ed.exportSheet('print') }, { id: 'settings', label: 'Settings', icon: 'lucide:settings', aka: 'symbols sound wires options', run: () => (ed.dialog.value = 'settings') }, diff --git a/app/components/editor/Toolbar.vue b/app/components/editor/Toolbar.vue index 39c2a01..0e7ebb0 100644 --- a/app/components/editor/Toolbar.vue +++ b/app/components/editor/Toolbar.vue @@ -40,6 +40,15 @@ const circuitEntries = computed(() => { { label: 'Tidy this circuit', icon: 'lucide:wand-sparkles', disabled: !d.wires.length, run: () => ed.tidyAll() }, { label: 'Tidy every circuit', icon: 'lucide:sparkles', run: () => ed.tidyEverything() }, 'sep', + { head: 'Memory' }, + { + label: 'Power off and on', + icon: 'lucide:power', + disabled: !ed.circuitStats.value.sequential, + note: ed.circuitStats.value.sequential ? 'every bit back to 0' : 'no memory here', + run: () => ed.resetState(), + }, + 'sep', { head: 'As a part' }, { label: 'Design its box…', icon: 'lucide:pen-tool', run: () => ed.designFace(d.id) }, { label: 'Duplicate', icon: 'lucide:copy', run: () => ed.copyComponent(d.id) }, diff --git a/app/composables/useEditor.ts b/app/composables/useEditor.ts index acf6975..408f2da 100644 --- a/app/composables/useEditor.ts +++ b/app/composables/useEditor.ts @@ -55,6 +55,7 @@ import { import { arrangeNodes, byPosition, numberedNames, seriesLinks, type Arrange, type Link } from '~/lib/logic/bulk' import { parseProject, toProject } from '~/lib/logic/project' import { Simulator } from '~/lib/logic/sim' +import { packState, stateCarry } from '~/lib/logic/state' import { cachedAccount, currentId, @@ -72,7 +73,7 @@ import { type AccountUser, type ProjectMeta, } from '~/lib/logic/storage' -import type { CircuitNode, ConnectorType, LampColor, NodeKind, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types' +import type { CircuitNode, ConnectorType, HeldState, LampColor, NodeKind, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types' /** A challenge check plus how many transistors the solution uses. */ /** How everyone did on a puzzle, from the server. */ @@ -213,6 +214,7 @@ function create() { saveTimer = undefined // An untouched starter project is not saved (see initial()). if (placeholder) return + keepState() meta.value = { ...meta.value, name: project.value.name, @@ -322,7 +324,9 @@ function create() { const d = def.value const nl = compile(getDef.value, d.id) const key = `${meta.value.id}/${d.id}` - const carry = sim.value && simRoot === key ? sim.value.carry() : undefined + // The circuit running goes on as it is; one opened starts from what it held when it was last open. + const held = project.value.state?.[d.id] + const carry = sim.value && simRoot === key ? sim.value.carry() : held && stateCarry(held, nl) const s = new Simulator(nl, carry) for (const n of d.nodes) { if (n.kind === 'input') s.setSource(n.id, !!n.on) @@ -344,6 +348,53 @@ function create() { tick.value++ } + /** + * Puts what the open circuit holds (its latches, flip-flops and memory) in + * the project, so it starts from there when it is opened again, here or + * after loading. Not an undo step. True when that changed. + */ + function keepState(): boolean { + const s = sim.value + const id = def.value.id + if (!s || simRoot !== `${meta.value.id}/${id}`) return false + const held = packState(s) + if (JSON.stringify(held) === JSON.stringify(project.value.state?.[id])) return false + setHeld(id, held) + return true + } + + /** What a circuit holds in the project; undefined forgets it. */ + function setHeld(id: string, held: HeldState | undefined) { + const state = { ...project.value.state } + if (held) state[id] = held + else delete state[id] + if (Object.keys(state).length) project.value.state = state + else delete project.value.state + } + + /** + * What the open circuit holds, put in this browser's copy between saves + * (a clock running, a button pressed) without counting as a change, so it + * never starts a save or a sync of its own; the account gets it with the + * next save. A save that is due happens now instead. A save made since in + * another tab is never overwritten for the bits alone. + */ + function saveState() { + if (saveTimer) return persistNow() + const saved = listProjects().find(m => m.id === meta.value.id) + if (placeholder || saved?.updated !== meta.value.updated || !keepState()) return + saveProject(toRaw(meta.value), toRaw(project.value)) + } + + /** Power off and on: the open circuit forgets what it held and starts again from all zeros. */ + function resetState() { + setHeld(def.value.id, undefined) + simRoot = '' + rebuild() + persist() + notify('Powered off and on: every bit starts from 0 again') + } + let rebuildQueued = false function scheduleRebuild() { if (rebuildQueued) return @@ -445,6 +496,7 @@ function create() { // ── Navigation ──────────────────────────────────────────────────── function open(id: string, push = true) { if (id === def.value.id || !getDef.value(id)) return + keepState() if (push) nav.value.push(def.value.id) project.value.openId = id clearSelection() @@ -1950,9 +2002,9 @@ function create() { } } - window.addEventListener('beforeunload', () => { - if (saveTimer) persistNow() - }) + window.addEventListener('beforeunload', saveState) + document.addEventListener('visibilitychange', () => document.visibilityState === 'hidden' && saveState()) + setInterval(saveState, 30_000) // ── Account ─────────────────────────────────────────────────────── // Signed in, every project in this browser is also kept in the account and @@ -2307,6 +2359,7 @@ function create() { startLoop, step, rebuild, + resetState, open, back, mainId, diff --git a/app/lib/logic/project.ts b/app/lib/logic/project.ts index 734befc..964c0bb 100644 --- a/app/lib/logic/project.ts +++ b/app/lib/logic/project.ts @@ -12,6 +12,7 @@ import { type ComponentDef, type ConnectorType, type FaceDesign, + type HeldState, type PanelRow, type Project, type PuzzleSpec, @@ -145,9 +146,24 @@ export function toProject(data: unknown): Project { ...(p.mode === 'campaign' || p.mode === 'challenges' ? { mode: p.mode } : {}), ...(puzzlesOf(p.puzzles) ? { puzzles: puzzlesOf(p.puzzles)! } : {}), ...(connectorsOf(p.connectors) ? { connectors: connectorsOf(p.connectors)! } : {}), + ...(stateOf(p.state, p.components) ? { state: stateOf(p.state, p.components)! } : {}), } } +/** Bits the circuits held: only for circuits of the project, names and gates as text; broken entries are dropped. */ +function stateOf(raw: unknown, components: ComponentDef[]): Record | null { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null + const ids = new Set(components.map(d => d.id)) + const out: Record = {} + for (const [id, s] of Object.entries(raw as Record>)) { + if (!ids.has(id) || !s || typeof s.on !== 'string' || !Array.isArray(s.names) || !s.names.every(n => typeof n === 'string')) continue + const clocks = Array.isArray(s.clocks) ? s.clocks.filter(k => typeof k === 'string') : [] + if (!s.on && !clocks.length) continue + out[id] = { names: s.names, on: s.on, ...(clocks.length ? { clocks } : {}) } + } + return Object.keys(out).length ? out : null +} + /** 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 diff --git a/app/lib/logic/sim.ts b/app/lib/logic/sim.ts index 5eedb3a..e00c7fc 100644 --- a/app/lib/logic/sim.ts +++ b/app/lib/logic/sim.ts @@ -5,7 +5,9 @@ // "oscillating". import { HIGH, type Netlist } from './compile' +import { flow } from './state' +/** Gate outputs and clock levels to start from, by key (see state.ts for what is saved). */ export interface SimCarry { gates: Map /** Level of all clocks when they ran in lockstep; per-clock levels win. */ @@ -38,8 +40,9 @@ export class Simulator { } this.clock = carry.clock nl.clocks.forEach((c, i) => (this.values[c] = carry.clocks?.get(nl.clockKeys[i]!) ?? carry.clock)) - } - for (let i = 0; i < gates; i++) this.push(i) + // Gates run in the order signals flow, so a latch reads its inputs only once they are right and keeps its bit. + for (const g of flow(nl).order) this.push(g) + } else for (let i = 0; i < gates; i++) this.push(i) } private push(g: number) { diff --git a/app/lib/logic/state.ts b/app/lib/logic/state.ts new file mode 100644 index 0000000..32035b6 --- /dev/null +++ b/app/lib/logic/state.ts @@ -0,0 +1,137 @@ +// What a circuit remembers between visits and saves, like the contents of a +// memory chip. Only gates on feedback loops (latches, flip-flops, registers, +// RAM built from NANDs) can hold a bit; every other gate follows from its +// inputs. So only the loop gates that are 1 are kept, plus the clocks that +// are high, written small enough to save with the project. + +import type { Netlist } from './compile' +import type { SimCarry, Simulator } from './sim' +import type { HeldState } from './types' + +export interface Flow { + /** Every gate once, each after the gates that feed it; the gates of a loop after what feeds the loop. */ + order: Int32Array + /** 1 for gates on a feedback loop. */ + loop: Uint8Array +} + +const flows = new WeakMap() + +/** Which gates sit on a loop, and the order signals flow in. Tarjan's method without recursion, so a CPU can't run out of stack; kept per netlist. */ +export function flow(nl: Netlist): Flow { + const known = flows.get(nl) + if (known) return known + const { gateA, gateB, gateOut, fanStart, fanList } = nl + const n = gateOut.length + const index = new Int32Array(n).fill(-1) + const low = new Int32Array(n) + const onStack = new Uint8Array(n) + const stack = new Int32Array(n) + const path = new Int32Array(n) + const edge = new Int32Array(n) + const loop = new Uint8Array(n) + // A group of gates is finished after every group it feeds, so the order fills from the back. + const order = new Int32Array(n) + let done = n + let sp = 0 + let next = 0 + for (let root = 0; root < n; root++) { + if (index[root]! >= 0) continue + let depth = 0 + path[0] = root + index[root] = low[root] = next++ + stack[sp++] = root + onStack[root] = 1 + edge[root] = fanStart[gateOut[root]!]! + while (depth >= 0) { + const g = path[depth]! + if (edge[g]! < fanStart[gateOut[g]! + 1]!) { + const r = fanList[edge[g]!++]! + if (index[r]! < 0) { + index[r] = low[r] = next++ + stack[sp++] = r + onStack[r] = 1 + edge[r] = fanStart[gateOut[r]!]! + path[++depth] = r + } else if (onStack[r]) low[g] = Math.min(low[g]!, index[r]!) + continue + } + if (low[g] === index[g]) { + const end = done + let r: number + do { + r = stack[--sp]! + onStack[r] = 0 + order[--done] = r + } while (r !== g) + if (end - done > 1) { + // Inside a loop the gates keep the order they were placed in, which decides how a new latch starts (see ex-sr). + order.subarray(done, end).sort() + for (let i = done; i < end; i++) loop[order[i]!] = 1 + } else if (gateA[g] === gateOut[g] || gateB[g] === gateOut[g]) { + // A gate on its own is a loop when it reads its own output. + loop[g] = 1 + } + } + depth-- + if (depth >= 0) low[path[depth]!] = Math.min(low[path[depth]!]!, low[g]!) + } + } + const res = { order, loop } + flows.set(nl, res) + return res +} + +/** + * What the circuit holds right now, ready to save; undefined when nothing is 1. + * A gate's key is its path of node ids ("chipNode/chipNode/nand"): each id goes + * in `names` once, and a gate is written as how many levels of its path it + * shares with the gate before it, then the indexes of the rest. Gates come + * chip by chip, so most share all but the last level or two. + */ +export function packState(sim: Simulator): HeldState | undefined { + const { nl, values } = sim + const { loop } = flow(nl) + const names: string[] = [] + const index = new Map() + const on: string[] = [] + let prev: string[] = [] + for (let g = 0; g < loop.length; g++) { + if (!loop[g] || !values[nl.gateOut[g]!]) continue + const path = nl.gateKeys[g]!.split('/') + let shared = 0 + while (shared < path.length - 1 && path[shared] === prev[shared]) shared++ + const rest = path.slice(shared).map(id => { + let i = index.get(id) + if (i === undefined) { + i = names.push(id) - 1 + index.set(id, i) + } + return i.toString(36) + }) + on.push(`${shared.toString(36)}:${rest.join('.')}`) + prev = path + } + const clocks = nl.clockKeys.filter((_, i) => values[nl.clocks[i]!]) + if (!on.length && !clocks.length) return undefined + const held: HeldState = { names, on: on.join(' ') } + if (clocks.length) held.clocks = clocks + return held +} + +/** Saved bits as the simulator's carry for this netlist: loop gates not named are 0, and so are clocks. */ +export function stateCarry(held: HeldState, nl: Netlist): SimCarry { + const gates = new Map() + let prev: string[] = [] + for (const gate of held.on.split(' ')) { + const [shared, rest] = gate.split(':') + if (!shared || !rest) continue + // A broken entry makes a key no gate has, which is ignored like one that no longer exists. + const path = [...prev.slice(0, parseInt(shared, 36)), ...rest.split('.').map(i => held.names[parseInt(i, 36)] ?? '')] + gates.set(path.join('/'), 1) + prev = path + } + const high = new Set(held.clocks ?? []) + const clocks = new Map(nl.clockKeys.map(k => [k, high.has(k) ? 1 : 0])) + return { gates, clock: high.size ? 1 : 0, clocks } +} diff --git a/app/lib/logic/types.ts b/app/lib/logic/types.ts index 49c9547..49833c6 100644 --- a/app/lib/logic/types.ts +++ b/app/lib/logic/types.ts @@ -226,6 +226,23 @@ export interface Project { puzzles?: PuzzleSpec[] /** Connector types made in this project (HDMI, RJ45, your own buses): their lines and colour. */ connectors?: ConnectorType[] + /** What each circuit held when it was last open (latches, flip-flops, memory), by circuit id. Empty: it starts from all zeros. */ + state?: Record +} + +/** + * The bits a circuit holds, like the contents of a memory chip: the NANDs on + * feedback loops that are 1, and the clocks that are high. Everything else + * follows from the inputs. Gates are known by their path through the chips + * ("chipNode/chipNode/nand"); one that no longer exists is ignored. + */ +export interface HeldState { + /** Node ids on the gates' paths, each once. */ + names: string[] + /** The gates that are 1, separated by spaces: ":.…" in base 36 (see state.ts). */ + on: string + /** Keys of the clocks that are high. */ + clocks?: string[] } /** A puzzle someone published: what to build, without their solution. */ diff --git a/tests/state.test.ts b/tests/state.test.ts new file mode 100644 index 0000000..7b09319 --- /dev/null +++ b/tests/state.test.ts @@ -0,0 +1,297 @@ +import { readFileSync } from 'node:fs' +import { describe, expect, it } from 'vitest' +import { compile, type Netlist } from '../app/lib/logic/compile' +import { chipPins } from '../app/lib/logic/geometry' +import { createProject, lookup } from '../app/lib/logic/ops' +import { parseProject, toProject } from '../app/lib/logic/project' +import { Simulator } from '../app/lib/logic/sim' +import { flow, packState, stateCarry } from '../app/lib/logic/state' +import type { CircuitNode, ComponentDef, Project } from '../app/lib/logic/types' + +/** A D latch from the examples between two switches and an output pin, open as the circuit. */ +function memory(): Project { + const p = createProject({ examples: true }) + const pins = chipPins(lookup(p)('ex-dlatch')!) + const pin = (label: string) => pins.inputs.find(x => x.label === label)!.key + p.components.push({ + id: 'mem', + name: 'Memory', + symbol: 'box', + nodes: [ + { id: 'd', kind: 'input', x: 0, y: 0, label: 'D' }, + { id: 'e', kind: 'input', x: 0, y: 4, label: 'E' }, + { id: 'u', kind: 'chip', chip: 'ex-dlatch', x: 6, y: 0 }, + { id: 'q', kind: 'output', x: 20, y: 0, label: 'Q' }, + ], + wires: [ + { id: 'w1', from: { node: 'd', pin: 'q' }, to: { node: 'u', pin: pin('D') } }, + { id: 'w2', from: { node: 'e', pin: 'q' }, to: { node: 'u', pin: pin('E') } }, + { id: 'w3', from: { node: 'u', pin: pins.outputs[0]!.key }, to: { node: 'q', pin: 'a' } }, + ], + }) + p.openId = 'mem' + return p +} + +/** Opens a circuit the way the editor does: from what it held last, with its switches as they are set. */ +function open(p: Project, id: string): Simulator { + const nl = compile(lookup(p), id) + const held = p.state?.[id] + const s = new Simulator(nl, held && stateCarry(held, nl)) + for (const n of lookup(p)(id)!.nodes) if (n.kind === 'input') s.setSource(n.id, !!n.on) + s.run() + return s +} + +/** Leaves a circuit (or saves): what it holds goes into the project. */ +function leave(p: Project, id: string, s: Simulator) { + const held = packState(s) + p.state = { ...p.state } + if (held) p.state[id] = held + else delete p.state[id] +} + +/** Flips switches as clicks do, letting the circuit settle after each. */ +function flip(p: Project, s: Simulator, steps: [string, boolean][]) { + const nodes = new Map(p.components.flatMap(d => d.nodes).map(n => [n.id, n])) + for (const [id, on] of steps) { + nodes.get(id)!.on = on + s.setSource(id, on) + expect(s.run()).toBe(true) + } +} + +const store1 = (p: Project, s: Simulator) => flip(p, s, [['d', true], ['e', true], ['e', false], ['d', false]]) + +describe('what a circuit holds', () => { + it('is only the gates on loops: the latch, not the gates in front of it', () => { + const p = memory() + const nl = compile(lookup(p), 'mem') + const { loop, order } = flow(nl) + const looped = nl.gateKeys.filter((_, g) => loop[g]) + // The SR latch inside the D latch: its two cross-coupled NANDs. + expect(looped).toHaveLength(2) + expect(looped.every(k => k.startsWith('u/'))).toBe(true) + // Every gate once, each after the gates that feed it. + expect([...order].sort((a, b) => a - b)).toEqual(nl.gateKeys.map((_, g) => g)) + const at = new Map([...order].map((g, i) => [g, i])) + nl.gateOut.forEach((out, g) => { + for (let j = nl.fanStart[out]!; j < nl.fanStart[out + 1]!; j++) { + const r = nl.fanList[j]! + if (!loop[r] || !loop[g]) expect(at.get(g)!).toBeLessThan(at.get(r)!) + } + }) + }) + + it('packs the gates that are 1 by their path, and unpacks them again', () => { + const p = memory() + const s = open(p, 'mem') + store1(p, s) + expect(s.pin('q', 'a')).toBe(1) + const held = packState(s)! + const key = s.nl.gateKeys.find((k, g) => flow(s.nl).loop[g] && s.values[s.nl.gateOut[g]!])! + expect(key.split('/')).toHaveLength(3) + expect(held).toEqual({ names: key.split('/'), on: '0:0.1.2' }) + const back = JSON.parse(JSON.stringify(held)) + const carry = stateCarry(back, s.nl) + expect([...carry.gates]).toEqual([[key, 1]]) + expect(open(p, 'mem').pin('q', 'a')).toBe(0) + p.state = { mem: back } + expect(open(p, 'mem').pin('q', 'a')).toBe(1) + }) + + it('writes each gate as the levels it shares with the one before and the rest of its path', () => { + const keys = ['a/b/c/x', 'a/b/c/y', 'a/b/d/x', 'a/e/c/x', 'z', 'a/b/c~in'] + // Gates that each read their own output: all on a loop, all set to 1. + const out = Int32Array.from(keys, (_, i) => i + 2) + const nl: Netlist = { + netCount: keys.length + 2, + gateA: out, + gateB: out, + gateOut: out, + gateKeys: keys, + fanStart: Int32Array.from({ length: keys.length + 3 }, (_, n) => Math.max(0, n - 2)), + fanList: Int32Array.from(keys, (_, i) => i), + pinNet: new Map(), + facePinNet: new Map(), + outputs: new Map(), + sources: new Map(), + clocks: new Int32Array(0), + clockHz: new Float64Array(0), + clockKeys: [], + errors: [], + } + const s = new Simulator(nl) + s.values.fill(1) + const held = packState(s)! + expect(held.names).toEqual(['a', 'b', 'c', 'x', 'y', 'd', 'e', 'z', 'c~in']) + expect(held.on).toBe('0:0.1.2.3 3:4 2:5.3 1:6.2.3 0:7 0:0.1.8') + expect([...stateCarry(held, nl).gates.keys()]).toEqual(keys) + }) + + it('is nothing to keep for a circuit without loops', () => { + const p = createProject({ examples: true }) + expect(packState(open(p, 'ex-add4'))).toBeUndefined() + }) + + it('keeps a latch’s bit when you go into a component and come back', () => { + const p = memory() + let s = open(p, 'mem') + store1(p, s) + expect(s.pin('q', 'a')).toBe(1) + // Into the D latch itself: it runs on its own, with its own switches. + leave(p, 'mem', s) + const inside = open(p, 'ex-dlatch') + leave(p, 'ex-dlatch', inside) + s = open(p, 'mem') + expect(s.pin('q', 'a')).toBe(1) + // And a 0 stays a 0 while D is already 1 again. + flip(p, s, [['e', true], ['e', false], ['d', true]]) + expect(s.pin('q', 'a')).toBe(0) + leave(p, 'mem', s) + expect(open(p, 'mem').pin('q', 'a')).toBe(0) + }) + + it('a memory placed while the circuit runs starts at 0, and the rest keeps its bits', () => { + const p = memory() + const s = open(p, 'mem') + store1(p, s) + lookup(p)('mem')!.nodes.push({ id: 'r', kind: 'chip', chip: 'ex-reg4', x: 30, y: 0 }) + // What the editor does after a change: the same circuit goes on from all its gates. + const again = new Simulator(compile(lookup(p), 'mem'), s.carry()) + again.run() + expect(again.pin('q', 'a')).toBe(1) + for (const out of chipPins(lookup(p)('ex-reg4')!).outputs) expect(again.pin('r', out.key)).toBe(0) + }) + + it('starts from all zeros again after power off and on', () => { + const p = memory() + const s = open(p, 'mem') + store1(p, s) + leave(p, 'mem', s) + delete p.state!.mem + expect(open(p, 'mem').pin('q', 'a')).toBe(0) + }) + + it('is not upset by the gates in front of a latch that were placed after it', () => { + // The latch NANDs come first, their inverting inputs last: run in placing order from saved bits, the latch would flip. + const nand = (id: string, x: number): CircuitNode => ({ id, kind: 'nand', x, y: 0 }) + const def: ComponentDef = { + id: 'sr', + name: 'SR', + symbol: 'box', + nodes: [nand('q', 10), nand('nq', 10), nand('is', 5), nand('ir', 5), { id: 's', kind: 'input', x: 0, y: 0 }, { id: 'r', kind: 'input', x: 0, y: 4 }], + wires: [ + { id: 'w1', from: { node: 's', pin: 'q' }, to: { node: 'is', pin: 'a' } }, + { id: 'w2', from: { node: 's', pin: 'q' }, to: { node: 'is', pin: 'b' } }, + { id: 'w3', from: { node: 'r', pin: 'q' }, to: { node: 'ir', pin: 'a' } }, + { id: 'w4', from: { node: 'r', pin: 'q' }, to: { node: 'ir', pin: 'b' } }, + { id: 'w5', from: { node: 'is', pin: 'q' }, to: { node: 'q', pin: 'a' } }, + { id: 'w6', from: { node: 'nq', pin: 'q' }, to: { node: 'q', pin: 'b' } }, + { id: 'w7', from: { node: 'q', pin: 'q' }, to: { node: 'nq', pin: 'a' } }, + { id: 'w8', from: { node: 'ir', pin: 'q' }, to: { node: 'nq', pin: 'b' } }, + ], + } + const p = createProject({ examples: false }) + p.components.push(def) + for (const bit of [1, 0]) { + const s = open(p, 'sr') + flip(p, s, bit ? [['s', true], ['s', false]] : [['r', true], ['r', false]]) + expect(s.pin('q', 'q')).toBe(bit) + leave(p, 'sr', s) + expect(p.state!.sr).toEqual({ names: [bit ? 'q' : 'nq'], on: '0:0' }) + const again = open(p, 'sr') + expect([again.pin('q', 'q'), again.pin('nq', 'q')]).toEqual([bit, 1 - bit]) + } + }) + + it('keeps clock levels: high ones high, the others low', () => { + const p = createProject({ examples: false }) + p.components.push({ + id: 'clk', + name: 'Clocks', + symbol: 'box', + nodes: [ + { id: 'c1', kind: 'clock', x: 0, y: 0 }, + { id: 'c2', kind: 'clock', x: 0, y: 4, hz: 10 }, + { id: 'l1', kind: 'lamp', x: 6, y: 0 }, + { id: 'l2', kind: 'lamp', x: 6, y: 4 }, + ], + wires: [ + { id: 'w1', from: { node: 'c1', pin: 'q' }, to: { node: 'l1', pin: 'a' } }, + { id: 'w2', from: { node: 'c2', pin: 'q' }, to: { node: 'l2', pin: 'a' } }, + ], + }) + const s = open(p, 'clk') + s.toggleClock(1) + s.run() + leave(p, 'clk', s) + expect(p.state!.clk).toEqual({ names: [], on: '', clocks: ['c2'] }) + const again = open(p, 'clk') + expect([again.pin('l1', 'a'), again.pin('l2', 'a')]).toEqual([0, 1]) + expect(again.clock).toBe(1) + }) + + it('stays small for a lot of memory: 64 flip-flops', () => { + const p = createProject({ examples: true }) + const reg = chipPins(lookup(p)('ex-reg4')!) + const nodes: CircuitNode[] = [{ id: 'one', kind: 'high', x: 0, y: 0 }, { id: 'clk', kind: 'input', x: 0, y: 4 }] + const wires: ComponentDef['wires'] = [] + for (let i = 0; i < 16; i++) { + nodes.push({ id: `reg${i}`, kind: 'chip', chip: 'ex-reg4', x: 10, y: 20 * i }) + reg.inputs.forEach((pin, k) => wires.push({ id: `w${i}-${k}`, from: { node: pin.label === 'CLK' ? 'clk' : 'one', pin: 'q' }, to: { node: `reg${i}`, pin: pin.key } })) + } + p.components.push({ id: 'ram', name: 'RAM', symbol: 'box', nodes, wires }) + const s = open(p, 'ram') + flip(p, s, [['clk', true], ['clk', false]]) + const nl = s.nl + expect(flow(nl).loop.reduce((n, v) => n + v, 0)).toBe(64 * 4) + leave(p, 'ram', s) + const size = JSON.stringify(p.state!.ram).length + // 128 latches hold a 1 (master and slave of each flip-flop): about ten characters each. + expect(size).toBeLessThan(128 * 12) + const again = open(p, 'ram') + for (let i = 0; i < 16; i++) for (const out of reg.outputs) expect(again.pin(`reg${i}`, out.key)).toBe(1) + }) +}) + +describe('saving what circuits hold', () => { + it('goes with the project through a file or the server and comes back', () => { + const p = memory() + const s = open(p, 'mem') + store1(p, s) + leave(p, 'mem', s) + const loaded = parseProject(JSON.stringify(p)) + expect(loaded.state).toEqual(p.state) + expect(toProject(JSON.parse(JSON.stringify(loaded))).state).toEqual(p.state) + expect(open(loaded, 'mem').pin('q', 'a')).toBe(1) + }) + + it('is absent in projects saved before it, which start from zeros as they always did', () => { + const p = parseProject(readFileSync('tests/fixtures/v1-project.json', 'utf8')) + expect(p.state).toBeUndefined() + for (const d of p.components) open(p, d.id) + }) + + it('drops entries for circuits that are gone and broken ones; names that no longer exist are ignored', () => { + const p = memory() + const s = open(p, 'mem') + store1(p, s) + leave(p, 'mem', s) + const data = JSON.parse(JSON.stringify(p)) + data.state.gone = { names: ['n1'], on: '0:0' } + data.state['ex-sr'] = { names: ['n1'], on: ['0:0'] } + data.state['ex-dlatch'] = { names: [7], on: '0:0' } + data.state['ex-dff'] = 'bits' + data.state['ex-not'] = { names: [], on: '', clocks: [3, 'c'] } + data.state['ex-and'] = { names: [], on: '' } + // Gates of an old version, and garbage: they match no gate. + data.state.mem.names.push('old') + data.state.mem.on += ' 1:3 0:z.q 9 :' + const back = toProject(data) + expect(Object.keys(back.state!).sort()).toEqual(['ex-not', 'mem']) + expect(back.state!['ex-not']).toEqual({ names: [], on: '', clocks: ['c'] }) + expect(open(back, 'mem').pin('q', 'a')).toBe(1) + expect(toProject({ ...data, state: [1, 2] }).state).toBeUndefined() + }) +})