diff --git a/app/assets/css/main.css b/app/assets/css/main.css index ff3fd4e..99125fd 100644 --- a/app/assets/css/main.css +++ b/app/assets/css/main.css @@ -5690,117 +5690,6 @@ button.tile:hover { stroke-dasharray: 3 2; } -/* Logic analyzer: above the bottom bar, as wide as it. */ -.analyzer { - position: absolute; - left: var(--bar-x); - width: var(--bar-w); - bottom: 76px; - z-index: 19; - display: flex; - flex-direction: column; - max-height: 40vh; - background: rgb(19 24 31 / 0.97); - border: 1px solid var(--border); - border-radius: 12px; - box-shadow: 0 10px 30px rgb(0 0 0 / 0.4); - font-size: 12px; -} - -.analyzer-head { - display: flex; - align-items: center; - gap: 8px; - padding: 6px 8px 6px 12px; - border-bottom: 1px solid var(--border); -} - -.analyzer-empty { - padding: 12px; -} - -.analyzer-body { - display: flex; - overflow-y: auto; - min-height: 0; -} - -.analyzer-names { - flex: none; - border-right: 1px solid var(--border); -} - -.analyzer-names li { - display: flex; - align-items: center; - gap: 6px; - padding: 0 4px 0 12px; - border-bottom: 1px solid rgb(37 46 58 / 0.5); -} - -.analyzer-names li > .truncate { - flex: 1; - min-width: 0; -} - -.analyzer-val { - color: var(--on); - font-family: var(--font-mono); - font-size: 11px; -} - -.analyzer-wave { - position: relative; - flex: 1; - min-width: 0; - overflow: hidden; - cursor: crosshair; -} - -.analyzer-wave svg { - display: block; -} - -.analyzer-bit { - fill: none; - stroke: var(--on); - stroke-width: 1.5; -} - -.analyzer-bus { - fill: var(--on-dim); - stroke: var(--on); - stroke-width: 1; -} - -.analyzer-bus-text { - fill: var(--text); - font-family: var(--font-mono); - font-size: 10px; -} - -.analyzer-mark { - stroke: var(--border); - stroke-width: 1; -} - -.analyzer-cursor { - stroke: var(--accent); - stroke-width: 1; -} - -.analyzer-cycle { - position: absolute; - right: 6px; - top: 2px; - color: var(--muted); - font-size: 10px; - pointer-events: none; -} - -.analyzer-head .hint { - margin: 0; -} .node .pixel-rgb { fill: #5a6779; @@ -6373,3 +6262,55 @@ button.tile:hover { .bench-empty { margin-top: 12px; } + +/* Logic analyzer part */ +.node .scope-body { + fill: #10161d; + stroke: #3b4554; +} + +.node .scope-lane { + fill: #0a0f14; +} + +.node .scope-mark { + stroke: #1f2833; + stroke-width: 1; +} + +.node .scope-wave { + fill: none; + stroke: var(--on); + stroke-width: 1.5; + pointer-events: none; +} + +.node .scope-bus { + fill: var(--on-dim); + stroke: var(--on); + stroke-width: 1; + pointer-events: none; +} + +.node .scope-bus-text, +.node .scope-value { + fill: var(--text); + font-family: var(--font-mono); + font-size: 9.5px; + pointer-events: none; +} + +.node .scope-value { + fill: var(--on); +} + +.scope-chan { + display: flex; + align-items: center; + gap: 4px; + margin-bottom: 4px; +} + +.scope-chan .scope-bits { + width: 52px; +} diff --git a/app/components/editor/Analyzer.vue b/app/components/editor/Analyzer.vue deleted file mode 100644 index 0297c8a..0000000 --- a/app/components/editor/Analyzer.vue +++ /dev/null @@ -1,145 +0,0 @@ - - - - - - - Logic analyzer - {{ total }} {{ total === 1 ? 'step' : 'steps' }} · {{ back }} back - Now - - - - - - Right-click a wire, a cable or a pin and choose Watch in analyzer. Then run the clock, step it, or flip switches. - - - - - {{ name(i) }} - {{ valueText(i) }} - - - - - - - - - - - - {{ hexOf(r.v, bits(i)) }} - - - - - - tick {{ shown.cycle }} - - - - diff --git a/app/components/editor/App.vue b/app/components/editor/App.vue index 90452c6..15e08ab 100644 --- a/app/components/editor/App.vue +++ b/app/components/editor/App.vue @@ -45,7 +45,6 @@ watch( - diff --git a/app/components/editor/Canvas.vue b/app/components/editor/Canvas.vue index 0891c4c..0d500d7 100644 --- a/app/components/editor/Canvas.vue +++ b/app/components/editor/Canvas.vue @@ -10,7 +10,6 @@ import { dropLinks, dropPins, fitStart, type DropPin } from '~/lib/logic/fit' import type { CanvasOps, MenuEntry } from '~/composables/useMenu' import { cableInUse, LANE, plugLayout, ribbon, RIBBON_MAX } from '~/lib/logic/cables' import { latchLayout, latchSeam } from '~/lib/logic/latch' -import { probeAt } from '~/lib/logic/probes' import { keyCode } from '~/lib/logic/devices' import { moveParts, moveStart, type MoveStart } from '~/lib/logic/move' import { wirePath, type HopSpan } from '~/lib/draw' @@ -1174,7 +1173,7 @@ function onPointerUp(e: PointerEvent) { ed.commit(false) } else if (d.moved) { ed.unplugMoved(new Set(d.orig.nodes.keys())) - if (d.node.kind !== 'bench' || !ed.dropBench(d.node)) ed.commit(false) + if ((d.node.kind !== 'bench' && d.node.kind !== 'scope') || !ed.dropBench(d.node)) ed.commit(false) } else if (d.benchHit === 'run') ed.runBenchNow(d.node.id, true) else if (typeof d.benchHit === 'number') ed.applyBenchRow(d.node.id, d.benchHit) else if (d.toggle && d.row) ed.toggleRow(d.node, d.row) @@ -1699,8 +1698,6 @@ function openMenuAt(target: Element, at: Pt, x: number, y: number) { const pull = endActions(n).find(x => x.key === 'pull') if (pull) here.push({ label: 'Pull the cable out', icon: pull.icon, run: () => pull.run(new PointerEvent('pointerdown')) }) } - const probe = p && !p.port ? probeAt(def.value, n, pin, dir, ed.getDef.value) : null - if (probe) here.push({ label: 'Watch in analyzer', icon: 'lucide:activity', run: () => ed.watchSignal(probe) }) if (dir === 'in' && ed.canInvert(n, pin)) { const on = n.invert?.includes(pin) here.push({ label: on ? 'Take the bubble off this input' : 'Invert this input', icon: 'lucide:circle-dot', keys: 'Alt+click', run: () => ed.toggleInvert(n, pin) }) diff --git a/app/components/editor/NodeSettings.vue b/app/components/editor/NodeSettings.vue index 6f0fa2d..610af55 100644 --- a/app/components/editor/NodeSettings.vue +++ b/app/components/editor/NodeSettings.vue @@ -5,7 +5,7 @@ import { compile } from '~/lib/logic/compile' import { cableOf } from '~/lib/logic/cables' import { INVERTIBLE } from '~/lib/logic/compile' import { cableBits, cableOffsets, chipPins, MAX_BITS, panelOffsets, portName, rowLabel } from '~/lib/logic/geometry' -import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops' +import { SINK_KINDS, SOURCE_KINDS, uid } from '~/lib/logic/ops' import { KIND_NAMES } from '~/lib/logic/progress' import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide' import { LAMP_COLORS, WIRE_COLORS, type CircuitNode, type NodeKind, type PanelControl, type PanelRow } from '~/lib/logic/types' @@ -344,6 +344,21 @@ function setRowHz(row: PanelRow, e: Event) { else delete row.hz ed.commit() } + +/** Logic analyzer channels. */ +function addChannel(bits: number) { + const used = new Set((n.value.scope?.cols ?? []).map(c => c.name)) + let k = 0 + while (used.has(`CH${k}`)) k++ + ed.setScope(n.value.id, cols => cols.push({ id: uid('c'), name: `CH${k}`, bits })) +} +function renameChannel(i: number, name: string) { + if (name.trim()) ed.setScope(n.value.id, cols => (cols[i]!.name = name.trim().slice(0, 40))) +} +function setChannelBits(i: number, v: string) { + const bits = Math.round(Number(v)) + if (bits >= 1 && bits <= 32) ed.setScope(n.value.id, cols => (cols[i]!.bits = bits)) +} @@ -697,6 +712,20 @@ function setRowHz(row: PanelRow, e: Event) { + + Channels: wire to their pins on the left + + + + cols.splice(i, 1))"> + + + Wire + 8-bit bus + Start over + + + sevenSegment([0, 1, 2, 3].reduce((n, i) => n /** The colour of an RGB pixel inside this chip ('' while off). */ const facePx = (inner: string) => rgbHex(fv(inner, 'r'), fv(inner, 'g'), fv(inner, 'b')) const rgbNow = computed(() => (props.node.rgb ? rgbHex(v('r'), v('g'), v('b')) : '')) +// Logic analyzer: its lanes from what the store recorded. +const sl = computed(() => scopeLayout(props.node)) +const scopeView = computed(() => { + const n = props.node + if (n.kind !== 'scope' || props.ghost) return { lanes: [], marks: [] as number[] } + void ed.scopeVersion.value + const all = ed.scopeTraces.value.get(n.id) ?? [] + const list = all.slice(-SCOPE_SAMPLES) + const x0 = sl.value.waveX * G + const marks: number[] = [] + list.forEach((s, k) => k && s.cycle !== list[k - 1]!.cycle && marks.push(x0 + k * SCOPE_CELL)) + const lanes = sl.value.lanes.map((l, i) => { + const top = (l.row - 0.5) * G + 3 + const bottom = (l.row - 0.5 + l.bits) * G - 3 + const hex = (v: number) => `0x${v.toString(16).toUpperCase().padStart(Math.ceil(l.bits / 4), '0')}` + const now = list[list.length - 1]?.vals[i] + const value = now === undefined ? '' : l.bits === 1 ? String(now) : `${now} ${hex(now)}` + let wave = '' + const runs: { d: string; mid: number; label: string }[] = [] + if (l.bits === 1) { + list.forEach((s, k) => { + const y = s.vals[i] ? top : bottom + wave += k ? `V${y}H${x0 + (k + 1) * SCOPE_CELL}` : `M${x0} ${y}H${x0 + SCOPE_CELL}` + }) + } else { + let start = 0 + for (let k = 1; k <= list.length; k++) { + if (k < list.length && list[k]!.vals[i] === list[start]!.vals[i]) continue + const a = x0 + start * SCOPE_CELL + const z = x0 + k * SCOPE_CELL + const m = Math.min(3, (z - a) / 3) + const c = (top + bottom) / 2 + const v = list[start]!.vals[i]! + const label = l.bits <= 4 ? hex(v).slice(2) : hex(v) + runs.push({ d: `M${a} ${c}L${a + m} ${top}H${z - m}L${z} ${c}L${z - m} ${bottom}H${a + m}Z`, mid: (a + z) / 2, label: z - a >= label.length * 6 + 6 ? label : '' }) + start = k + } + } + return { id: l.col.id, row: l.row, bits: l.bits, value, wave, runs } + }) + return { lanes, marks } +}) + // Test bench: the layout of its box, its rows and how they went. interface BenchRowView { i: number @@ -462,6 +506,26 @@ const title = computed(() => { {{ node.conn && !connType ? 'type missing' : 'no lines' }} + + + + {{ node.label?.trim() || 'Logic analyzer' }} + Drop on a component + + + + + + {{ l.value }} + + + + {{ r.label }} + + + {{ p.label }} + + diff --git a/app/components/editor/QuickAdd.vue b/app/components/editor/QuickAdd.vue index e09a103..4d53eda 100644 --- a/app/components/editor/QuickAdd.vue +++ b/app/components/editor/QuickAdd.vue @@ -41,7 +41,6 @@ const ACTIONS: Action[] = [ run: () => ed.packageSelected('Part'), }, { id: 'find', label: 'Find anything in the project', icon: 'lucide:search', keys: 'Ctrl+F', aka: 'search where used', run: () => (ed.dialog.value = 'search') }, - { id: 'analyzer', label: 'Logic analyzer', icon: 'lucide:activity', aka: 'waveform signals scope trace timing', run: () => (ed.analyzerOpen.value = true) }, { id: 'convert', label: 'Converter: text, hex, binary, decimal', icon: 'lucide:arrow-left-right', aka: 'ascii utf8 unicode base64 octal encode decode', run: () => (ed.dialog.value = 'convert') }, { id: 'asm', label: 'Assembler: program to memory words', icon: 'lucide:file-code-2', aka: 'assembly opcode instruction rom program cpu machine code', run: () => (ed.dialog.value = 'asm') }, { id: 'table', label: 'Truth table', icon: 'lucide:table', aka: 'test outputs', run: () => (ed.dialog.value = 'table') }, diff --git a/app/components/editor/Toolbar.vue b/app/components/editor/Toolbar.vue index 41e9ced..3a0fa77 100644 --- a/app/components/editor/Toolbar.vue +++ b/app/components/editor/Toolbar.vue @@ -142,7 +142,6 @@ const linkIcon = computed(() => { // Tools that work beside the circuit. const toolsMenu = ref<{ x: number; y: number } | null>(null) const toolEntries = computed(() => [ - { label: 'Logic analyzer', icon: 'lucide:activity', checked: ed.analyzerOpen.value, note: 'signals over time', run: () => (ed.analyzerOpen.value = !ed.analyzerOpen.value) }, { label: 'Converter…', icon: 'lucide:arrow-left-right', note: 'text, hex, binary', run: () => (ed.dialog.value = 'convert') }, { label: 'Assembler…', icon: 'lucide:file-code-2', note: 'program to memory', run: () => (ed.dialog.value = 'asm') }, ]) @@ -260,7 +259,7 @@ const moreEntries = computed(() => { {{ s.label }} - + diff --git a/app/composables/useEditor.ts b/app/composables/useEditor.ts index 0119d12..7e554f0 100644 --- a/app/composables/useEditor.ts +++ b/app/composables/useEditor.ts @@ -25,9 +25,8 @@ import { challengeName, challengeOpen, defUsable, isCampaign, KIND_NAMES, kindUn import { apiId, makePuzzle, scoreSolution, weekKey, weeklyId } from '~/lib/logic/puzzles' import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide' import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges' -import { probeValue } from '~/lib/logic/probes' import { bitsCode, codeBits, DATA_KEYS, KEY_QUEUE, putChar } from '~/lib/logic/devices' -import { AUTO_TICKS, benchFor, colKeys, HAND_TICKS, parseCell, runBench, upgradeBenches, type BenchResult } from '~/lib/logic/bench' +import { AUTO_TICKS, benchFor, colKeys, groupPins, HAND_TICKS, parseCell, runBench, upgradeBenches, type BenchResult } from '~/lib/logic/bench' import { EXAMPLE as ASM_EXAMPLE, loadIntoPanels } from '~/lib/asm' import { latchedTo, latchInto, latchTarget, syncLatches } from '~/lib/logic/latch' import { cleanBundle, importBundle, importProblem, LIBRARY_LIMITS, libraryBundle, ownedEntry, publishProblem, type LibraryBundle, type LibraryMeta } from '~/lib/logic/library' @@ -84,7 +83,7 @@ import { type AccountUser, type ProjectMeta, } from '~/lib/logic/storage' -import type { AsmDoc, Bench, CircuitNode, ComponentDef, ConnectorType, HeldState, LampColor, LibraryOrigin, NodeKind, Probe, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types' +import type { AsmDoc, Bench, CircuitNode, ComponentDef, ConnectorType, HeldState, LampColor, LibraryOrigin, NodeKind, PanelControl, ScopeCol, 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. */ @@ -650,61 +649,54 @@ function create() { devVersion.value++ } - // ── Logic analyzer ──────────────────────────────────────────────── - /** The analyzer panel is open. */ - const analyzerOpen = ref(false) - /** What the watched signals were, oldest first: one sample per clock half-step, and on every other change. */ - const trace = shallowRef<{ cycle: number; vals: number[]; edge: boolean }[]>([]) - const traceVersion = ref(0) - const TRACE_MAX = 1000 - let traceKey = '' + // ── Logic analyzer parts ────────────────────────────────────────── + /** What each analyzer part saw, oldest first, by part id: one sample per clock half-step, and on every other change. Not saved. */ + const scopeTraces = shallowRef(new Map()) + /** Goes up with every new sample. */ + const scopeVersion = ref(0) + const SCOPE_KEEP = 600 + /** Each part's channels when last sampled: other channels start it over. */ + const scopeKeys = new Map() - /** Takes a sample of the watched signals; without `edge`, only when one of them changed. */ + /** Takes a sample on every analyzer part of the open circuit; without `edge`, only where something changed. */ function sample(edge = false) { const s = sim.value - const d = def.value - const ps = d.probes - if (!s || !ps?.length) return - // Other signals (or another circuit): start over. - const key = `${d.id}|${ps.map(p => `${p.node}:${p.pin}`).join(',')}` - if (key !== traceKey) { - traceKey = key - trace.value = [] + if (!s) return + let changed = false + for (const n of def.value.nodes) { + if (n.kind !== 'scope' || !n.scope?.cols.length) continue + const key = n.scope.cols.map(c => `${c.id}/${c.bits}`).join(',') + let list = scopeTraces.value.get(n.id) + if (!list || scopeKeys.get(n.id) !== key) { + scopeKeys.set(n.id, key) + list = [] + scopeTraces.value.set(n.id, list) + } + const vals = n.scope.cols.map(c => colKeys(c).reduce((v, k, i) => v + (s.pin(n.id, k) ? 2 ** i : 0), 0)) + const last = list[list.length - 1] + if (!edge && last && last.vals.every((v, i) => v === vals[i])) continue + list.push({ cycle: cycles.value, vals }) + if (list.length > SCOPE_KEEP) list.splice(0, list.length - SCOPE_KEEP) + changed = true } - const vals = ps.map(p => probeValue(d, p, (n, pin) => s.pin(n, pin))) - const list = trace.value - const last = list[list.length - 1] - if (!edge && last && last.vals.every((v, i) => v === vals[i])) return - list.push({ cycle: cycles.value, vals, edge }) - if (list.length > TRACE_MAX) list.splice(0, list.length - TRACE_MAX) - traceVersion.value++ + if (changed) scopeVersion.value++ } - function clearTrace() { - trace.value = [] - traceVersion.value++ + function clearScope(id: string) { + scopeTraces.value.set(id, []) + scopeVersion.value++ sample(true) } - /** Watches a signal in the analyzer (and opens it). */ - function watchSignal(p: Probe | null) { - if (!p) return - const d = def.value - if (!(d.probes ?? []).some(x => x.node === p.node && x.pin === p.pin)) { - d.probes = [...(d.probes ?? []), { node: p.node, pin: p.pin }] - commit(false) - } - analyzerOpen.value = true - nextTick(() => sample(true)) + /** An analyzer part's channels changed (an undo step; its pins change). */ + function setScope(id: string, change: (cols: ScopeCol[]) => void) { + const n = def.value.nodes.find(x => x.id === id) + if (!n || n.kind !== 'scope') return + n.scope ??= { cols: [] } + change(n.scope.cols) + commit() } - function unwatch(i: number) { - const d = def.value - if (!d.probes) return - d.probes = d.probes.filter((_, k) => k !== i) - if (!d.probes.length) delete d.probes - commit(false) - } function startLoop() { let lastT = performance.now() @@ -918,12 +910,13 @@ function create() { if (p.kind === 'panel' || p.kind === 'outpanel') node.rows = newPanelRows() if (p.kind === 'bundle' || p.kind === 'split') node.bits = 4 if (p.kind === 'bench') node.bench = { cols: [], rows: [] } + if (p.kind === 'scope') node.scope = { cols: [] } // A new pixel is like the one placed last: building a colour screen, every pixel comes in colour. if (p.kind === 'pixel' && def.value.nodes.findLast(n => n.kind === 'pixel')?.rgb) node.rgb = true def.value.nodes.push(node) // A bench put down on a component: set up for it. - const benchChip = p.kind === 'bench' ? benchSpot(node) : undefined - if (benchChip) benchOnto(node, benchChip) + const benchChip = p.kind === 'bench' || p.kind === 'scope' ? benchSpot(node) : undefined + if (benchChip) (p.kind === 'scope' ? scopeOnto : benchOnto)(node, benchChip) rememberPart(p.kind, p.chip) const swap = (r: PinRef) => (r.node === 'ghost' ? { node: node.id, pin: r.pin } : r) const made = links.filter(l => addWire(swap(l.from), swap(l.to))).length @@ -1456,22 +1449,25 @@ function create() { const benchLive = shallowRef(new Map()) let benchTimer: ReturnType | undefined - /** The component under a bench's middle, or within two squares of it. */ - function benchSpot(bench: CircuitNode): CircuitNode | undefined { - const own = shapeOf(bench, getDef.value).body - const x = bench.x + own.x + own.w / 2 - const y = bench.y + own.y + own.h / 2 + /** The component a bench or analyzer was dropped on: the one its box overlaps most, else the nearest within two squares. */ + function benchSpot(part: CircuitNode): CircuitNode | undefined { + const own = shapeOf(part, getDef.value).body + const ax = part.x + own.x + const ay = part.y + own.y let best: CircuitNode | undefined - let bestD = 2.01 + let bestScore = -2.01 for (const n of def.value.nodes) { - if (n.kind !== 'chip' || n.id === bench.id) continue + if (n.kind !== 'chip' || n.id === part.id) continue const b = shapeOf(n, getDef.value).body - const dx = Math.max(n.x + b.x - x, 0, x - (n.x + b.x + b.w)) - const dy = Math.max(n.y + b.y - y, 0, y - (n.y + b.y + b.h)) - const d = Math.max(dx, dy) - if (d < bestD) { + const bx = n.x + b.x + const by = n.y + b.y + const ox = Math.min(ax + own.w, bx + b.w) - Math.max(ax, bx) + const oy = Math.min(ay + own.h, by + b.h) - Math.max(ay, by) + // Overlapping: by how much; apart: minus the gap. + const score = ox > 0 && oy > 0 ? ox * oy : -Math.max(-ox, -oy, 0) + if (score > bestScore) { best = n - bestD = d + bestScore = score } } return best @@ -1493,13 +1489,30 @@ function create() { return true } - /** A bench let go after a drag: an empty one onto a component is set up for it. */ + /** An empty analyzer part onto a component: a channel for each of its output groups, wired, to the right of it. */ + function scopeOnto(scope: CircuitNode, chip: CircuitNode): boolean { + const chipDef = chip.chip ? getDef.value(chip.chip) : undefined + if (!chipDef || scope.scope?.cols.length) return false + const groups = groupPins(chipPins(chipDef).outputs) + if (!groups.length) return false + scope.scope = { cols: groups.map(g => ({ id: uid('c'), name: g.name, bits: g.keys.length })) } + const b = shapeOf(chip, getDef.value).body + scope.x = chip.x + b.x + b.w + 6 + scope.y = chip.y - 1 + groups.forEach((g, gi) => { + const keys = colKeys(scope.scope!.cols[gi]!) + g.keys.forEach((k, i) => addWire({ node: chip.id, pin: k }, { node: scope.id, pin: keys[i]! })) + }) + return true + } + + /** A bench or analyzer let go after a drag: an empty one onto a component is set up for it. */ function dropBench(bench: CircuitNode) { const chip = benchSpot(bench) - if (!chip || !benchOnto(bench, chip)) return false + if (!chip || !(bench.kind === 'scope' ? scopeOnto(bench, chip) : benchOnto(bench, chip))) return false commit() scheduleBenches() - notify(`Wired to ${getDef.value(chip.chip ?? '')?.name ?? 'the component'}: a column for each of its pins`) + notify(`Wired to ${getDef.value(chip.chip ?? '')?.name ?? 'the component'}: ${bench.kind === 'scope' ? 'a channel for each of its outputs' : 'a column for each of its pins'}`) return true } @@ -3104,12 +3117,10 @@ function create() { val, faceVal, startLoop, - analyzerOpen, - trace, - traceVersion, - clearTrace, - watchSignal, - unwatch, + scopeTraces, + scopeVersion, + clearScope, + setScope, step, rebuild, resetState, diff --git a/app/composables/useMenu.ts b/app/composables/useMenu.ts index 9393944..679296b 100644 --- a/app/composables/useMenu.ts +++ b/app/composables/useMenu.ts @@ -7,7 +7,6 @@ import { cableInUse, cableOf } from '~/lib/logic/cables' import { INVERTIBLE } from '~/lib/logic/compile' import { cableBits, chipPins, portName, type Pt } from '~/lib/logic/geometry' import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops' -import { probeAt, probeOfWire } from '~/lib/logic/probes' import { KIND_NAMES } from '~/lib/logic/progress' import { LAMP_COLORS, WIRE_COLORS, type CircuitNode, type NodeKind } from '~/lib/logic/types' import { baseOf, gateFamily, inputCount } from '~/lib/logic/wide' @@ -147,6 +146,7 @@ export function useMenu() { { label: 'Design its box', icon: 'lucide:pen-tool', run: () => ed.designFace(n.chip!) }, ) } + if (n.kind === 'scope') out.push({ label: 'Start over', icon: 'lucide:eraser', run: () => ed.clearScope(n.id) }) if (n.kind === 'bench') { out.push( { label: 'Columns and rows', icon: 'lucide:table', keys: 'Double-click', run: () => (ed.benchOpen.value = n.id) }, @@ -159,11 +159,6 @@ export function useMenu() { if (ed.keyQueues.value.get(n.id)?.length) out.push({ label: 'Forget the waiting keys', icon: 'lucide:eraser', run: () => ed.clearKeys(n.id) }) } if (n.kind === 'input') out.push({ label: n.on ? 'Switch off' : 'Switch on', icon: n.on ? 'lucide:toggle-right' : 'lucide:toggle-left', run: () => ed.toggleInput(n) }) - if (['input', 'button', 'clock', 'output', 'lamp'].includes(n.kind)) { - const dir = SOURCE_KINDS.includes(n.kind) ? 'out' : 'in' - const pin = dir === 'out' ? ed.shape(n).outputs[0]?.key : ed.shape(n).inputs[0]?.key - if (pin) out.push({ label: 'Watch in analyzer', icon: 'lucide:activity', run: () => ed.watchSignal(probeAt(ed.def.value, n, pin, dir, get)) }) - } if (NAMED.includes(n.kind)) out.push({ label: n.kind === 'note' ? 'Edit text' : 'Rename', icon: 'lucide:pencil', keys: 'Double-click', run: () => rename(n.id) }) const swaps = swapChoices([n]) if (swaps.length) out.push({ label: 'Change to', icon: 'lucide:replace', children: swaps }) @@ -444,8 +439,6 @@ export function useMenu() { { label: 'Place the ends yourself', icon: 'lucide:move', keys: 'Ctrl+Shift+G', run: () => ed.startCable() }, ) } - const signals = [...new Map(list.map(w => [`${w.from.node}:${w.from.pin}`, probeOfWire(w)])).values()] - if (signals.length <= 8) out.push({ label: 'Watch in analyzer', icon: 'lucide:activity', run: () => signals.forEach(p => ed.watchSignal(p)) }) if (list.length === 1) out.push({ label: 'Select the whole signal', icon: 'lucide:git-branch', keys: 'Double-click', run: () => ed.selectNet(list[0]!.id) }) const colors = new Set(list.map(w => w.color)) out.push({ diff --git a/app/composables/useParts.ts b/app/composables/useParts.ts index 1b67d4b..35f85a7 100644 --- a/app/composables/useParts.ts +++ b/app/composables/useParts.ts @@ -65,6 +65,13 @@ export const BASIC_GROUPS: { name: string; parts: BasicPart[] }[] = [ hint: 'A table of tests on its box: its outputs drive what you wire them to, its inputs check what comes back. Drop it on a component to wire it to every pin.', aka: 'test truth table check verify unit', }, + { + kind: 'scope', + name: 'Logic analyzer', + icon: 'lucide:activity', + hint: 'The signals on its inputs over time, on its box. Drop it on a component to watch all its outputs; channels and bits in its settings.', + aka: 'scope waveform oscilloscope signals trace timing probe watch', + }, ], }, { diff --git a/app/lib/logic/benchLayout.ts b/app/lib/logic/benchLayout.ts index 150d27c..1ad88ee 100644 --- a/app/lib/logic/benchLayout.ts +++ b/app/lib/logic/benchLayout.ts @@ -5,10 +5,10 @@ import type { BenchCol, CircuitNode } from './types' /** Pin keys of a column, bit 0 first. */ -export const colKeys = (c: BenchCol) => Array.from({ length: c.bits }, (_, i) => `${c.id}.${i}`) +export const colKeys = (c: Pick) => Array.from({ length: c.bits }, (_, i) => `${c.id}.${i}`) /** A column's pin names: its name, numbered when it has several bits. */ -export const colPinNames = (c: BenchCol) => (c.bits === 1 ? [c.name] : Array.from({ length: c.bits }, (_, i) => `${c.name}${i}`)) +export const colPinNames = (c: Pick) => (c.bits === 1 ? [c.name] : Array.from({ length: c.bits }, (_, i) => `${c.name}${i}`)) /** Rows the box shows; more are in the dialog. */ export const BENCH_ROWS_SHOWN = 24 diff --git a/app/lib/logic/compile.ts b/app/lib/logic/compile.ts index 25c5232..c531b0b 100644 --- a/app/lib/logic/compile.ts +++ b/app/lib/logic/compile.ts @@ -61,6 +61,8 @@ export function inputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup): return ['next'] case 'bench': return (node.bench?.cols ?? []).filter(c => c.dir === 'check').flatMap(colKeys) + case 'scope': + return (node.scope?.cols ?? []).flatMap(colKeys) case 'outpanel': return (node.rows ?? []).map(r => r.id) case 'bundle': diff --git a/app/lib/logic/geometry.ts b/app/lib/logic/geometry.ts index f537a09..51a8a77 100644 --- a/app/lib/logic/geometry.ts +++ b/app/lib/logic/geometry.ts @@ -3,6 +3,7 @@ import type { CircuitNode, ComponentDef, ConnectorType, FaceShape, LampColor, PanelRow, SymbolKind } from './types' import { benchLayout } from './benchLayout' +import { scopeLayout } from './scopeLayout' import { DATA_KEYS, DEVICE_PIN_NAMES } from './devices' export const GRID = 16 @@ -843,6 +844,10 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape { return TERMINAL_SHAPE case 'bench': return benchShape(node) + case 'scope': { + const l = scopeLayout(node) + return { body: { x: 0, y: -0.5, w: l.w, h: l.h }, inputs: l.pins.map(p => ({ key: p.key, label: p.label, dx: 0, dy: p.dy })), outputs: [] } + } case 'keyboard': return KEYBOARD_SHAPE case 'outpanel': diff --git a/app/lib/logic/labels.ts b/app/lib/logic/labels.ts index af2bb88..9db15aa 100644 --- a/app/lib/logic/labels.ts +++ b/app/lib/logic/labels.ts @@ -85,9 +85,9 @@ export function pinName(node: CircuitNode, pin: string, get: DefLookup): string // A wire of a cable carries the name of its signal (the cable pin itself has none). if (node.kind === 'bundle' || node.kind === 'split') return /^b\d+$/.test(pin) ? node.names?.[Number(pin.slice(1))]?.trim() || undefined : undefined if (node.kind === 'terminal' || node.kind === 'keyboard') return DEVICE_PIN_NAMES[pin] - if (node.kind === 'bench') { + if (node.kind === 'bench' || node.kind === 'scope') { const [id, bit] = pin.split('.') - const c = node.bench?.cols?.find(x => x.id === id) + const c = (node.kind === 'bench' ? node.bench?.cols : node.scope?.cols)?.find(x => x.id === id) return c ? colPinNames(c)[Number(bit)] : undefined } if (node.kind !== 'chip' || !node.chip) return undefined diff --git a/app/lib/logic/probes.ts b/app/lib/logic/probes.ts deleted file mode 100644 index 67aa069..0000000 --- a/app/lib/logic/probes.ts +++ /dev/null @@ -1,55 +0,0 @@ -// The logic analyzer's signals: wires and cables of a circuit you watch. -// Each is a pin of a part there (an output, or an input's wire); a cable -// pin reads its whole cable as one number, wire 0 the lowest bit. - -import { cableBits, shapeOf, type DefLookup } from './geometry' -import { pinName } from './labels' -import type { CircuitNode, ComponentDef, Probe } from './types' - -/** How many bits a signal has: 1 for a wire, the cable's wires for a cable pin. */ -export function probeBits(def: ComponentDef, p: Probe): number { - const n = def.nodes.find(x => x.id === p.node) - if ((n?.kind === 'bundle' && p.pin === 'q') || (n?.kind === 'split' && p.pin === 'a')) return cableBits(n) - return 1 -} - -/** A signal's value now, read with \`pin(node, pin)\` (the simulator's). */ -export function probeValue(def: ComponentDef, p: Probe, pin: (node: string, pin: string) => number): number { - const n = def.nodes.find(x => x.id === p.node) - if (n && ((n.kind === 'bundle' && p.pin === 'q') || (n.kind === 'split' && p.pin === 'a'))) { - // A cable: its wires as they leave the bundle (a split reads the bundle that feeds it). - const bundle = n.kind === 'bundle' ? n : def.nodes.find(x => x.id === def.wires.find(w => w.to.node === n.id && w.to.pin === 'a')?.from.node) - if (!bundle || bundle.kind !== 'bundle') return 0 - let v = 0 - for (let i = 0; i < cableBits(n); i++) if (pin(bundle.id, `b${i}`)) v += 2 ** i - return v - } - return pin(p.node, p.pin) -} - -/** What a signal is called: its own name, else the pin's or the part's. */ -export function probeName(def: ComponentDef, p: Probe, get: DefLookup): string { - if (p.label?.trim()) return p.label.trim() - const n = def.nodes.find(x => x.id === p.node) - if (!n) return '?' - const own = n.label?.trim() && !n.autoLabel ? n.label.trim() : '' - const pin = pinName(n, p.pin, get) - const part = own || (n.kind === 'chip' ? (n.chip && get(n.chip)?.name) || 'Component' : n.kind) - if (n.kind === 'bundle' || n.kind === 'split') return own || `Cable ${probeBits(def, p)}` - if (['input', 'button', 'clock', 'output', 'lamp'].includes(n.kind)) return own || part - return pin ? `${part} ${pin}` : part -} - -/** The signal a wire carries: the pin it comes from. */ -export const probeOfWire = (w: { from: { node: string; pin: string } }): Probe => ({ node: w.from.node, pin: w.from.pin }) - -/** - * The signal at a pin: an output itself, an input by the wire into it (or, - * with none, the pin, which reads 0). - */ -export function probeAt(def: ComponentDef, node: CircuitNode, pin: string, dir: 'in' | 'out', get: DefLookup): Probe | null { - if (dir === 'out') return { node: node.id, pin } - const w = def.wires.find(x => x.to.node === node.id && x.to.pin === pin) - if (w) return probeOfWire(w) - return shapeOf(node, get).inputs.some(p => p.key === pin) ? { node: node.id, pin } : null -} diff --git a/app/lib/logic/progress.ts b/app/lib/logic/progress.ts index fe9eb18..4708d24 100644 --- a/app/lib/logic/progress.ts +++ b/app/lib/logic/progress.ts @@ -31,6 +31,7 @@ export const KIND_NAMES: Partial> = { terminal: 'Terminal', keyboard: 'Keyboard', bench: 'Test bench', + scope: 'Logic analyzer', } /** Challenges each one builds on. */ diff --git a/app/lib/logic/project.ts b/app/lib/logic/project.ts index e7017eb..f2113d4 100644 --- a/app/lib/logic/project.ts +++ b/app/lib/logic/project.ts @@ -49,6 +49,15 @@ function cleanNode(n: CircuitNode) { if (n.inner !== undefined && n.inner !== true) delete n.inner if (n.screen !== undefined && typeof n.screen !== 'string') delete n.screen if (n.rgb !== undefined && n.rgb !== true) delete n.rgb + if (n.scope !== undefined) { + const cols = Array.isArray(n.scope?.cols) ? n.scope.cols : [] + n.scope = { + cols: cols + .filter(c => c && typeof c.id === 'string' && typeof c.name === 'string') + .slice(0, 32) + .map(c => ({ id: c.id, name: c.name.slice(0, 40), bits: Number.isInteger(c.bits) && c.bits >= 1 && c.bits <= 32 ? c.bits : 1 })), + } + } if (n.bench !== undefined) { const b = n.bench as Partial const cells = (r: unknown) => (r && typeof r === 'object' && !Array.isArray(r) ? Object.fromEntries(Object.entries(r).filter(([, v]) => typeof v === 'string').slice(0, 256)) : undefined) diff --git a/app/lib/logic/scopeLayout.ts b/app/lib/logic/scopeLayout.ts new file mode 100644 index 0000000..e888935 --- /dev/null +++ b/app/lib/logic/scopeLayout.ts @@ -0,0 +1,47 @@ +// The logic analyzer part's box: an input pin per bit down the left, the +// title bar on top, and a lane per channel beside its pins, the channel's +// value now and its wave over the last samples. + +import { colKeys, colPinNames } from './benchLayout' +import type { CircuitNode, ScopeCol } from './types' + +/** Samples a lane shows, and pixels each. */ +export const SCOPE_SAMPLES = 96 +export const SCOPE_CELL = 4 +const CHAR = 0.4 + +export interface ScopeLane { + col: ScopeCol + /** First pin row and how many. */ + row: number + bits: number +} + +export interface ScopeLayout { + w: number + h: number + pins: { key: string; label: string; dy: number }[] + lanes: ScopeLane[] + /** Where the value column and the waves start, in grid units. */ + valueX: number + waveX: number +} + +export function scopeLayout(node: CircuitNode): ScopeLayout { + const cols = node.scope?.cols ?? [] + const pins: ScopeLayout['pins'] = [] + const lanes: ScopeLane[] = [] + let row = 1 + for (const c of cols) { + const names = colPinNames(c) + colKeys(c).forEach((key, i) => pins.push({ key, label: names[i]!, dy: row + i })) + lanes.push({ col: c, row, bits: c.bits }) + row += c.bits + } + const lw = pins.length ? Math.max(...pins.map(p => p.label.length)) * CHAR + 0.7 : 0.4 + const valueX = lw + 0.2 + const valueW = Math.max(2, ...cols.map(c => (c.bits === 1 ? 1 : String(2 ** c.bits - 1).length + Math.ceil(c.bits / 4) + 4))) * CHAR + 0.4 + const waveX = valueX + valueW + const w = cols.length ? Math.ceil(waveX + (SCOPE_SAMPLES * SCOPE_CELL) / 16 + 0.4) : 12 + return { w, h: Math.max(row + 0.5, 2.5), pins, lanes, valueX, waveX } +} diff --git a/app/lib/logic/types.ts b/app/lib/logic/types.ts index 2ee49c7..b96ed7e 100644 --- a/app/lib/logic/types.ts +++ b/app/lib/logic/types.ts @@ -25,6 +25,7 @@ export type BuiltinKind = | 'terminal' // a text screen: writes the character on D0–D7 at a rising WR, clears at a rising CLR | 'keyboard' // the keys you type: the first waiting one on D0–D7, RDY while one waits, a rising NEXT takes it | 'bench' // a table of tests: drives the circuit from its outputs, checks what comes back on its inputs + | 'scope' // logic analyzer: the signals on its inputs over time, drawn on its box export type NodeKind = BuiltinKind | 'chip' @@ -79,8 +80,10 @@ export interface CircuitNode { screen?: string /** Pixel with three inputs, red, green and blue: eight colours. */ rgb?: boolean - /** Test bench: its tests and the component it tests. */ + /** Test bench: its columns and tests. */ bench?: Bench + /** Logic analyzer: its channels. */ + scope?: { cols: ScopeCol[] } /** Component: its connector ports (port node ids inside) shown split on this box, with a pin per line to wire by hand. */ splitPorts?: string[] } @@ -103,6 +106,13 @@ export interface BenchCol { dir: 'drive' | 'check' } +/** A channel of a logic analyzer: as many input pins as bits, read as one number. */ +export interface ScopeCol { + id: string + name: string + bits: number +} + export interface BenchRow { /** Cells of the drive columns by column id: a number, P for a pulse; empty leaves it. */ set?: Record diff --git a/tests/probes.test.ts b/tests/probes.test.ts deleted file mode 100644 index 457adde..0000000 --- a/tests/probes.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { bundleWires } from '../app/lib/logic/cables' -import { compile } from '../app/lib/logic/compile' -import { createProject, lookup } from '../app/lib/logic/ops' -import { probeAt, probeBits, probeName, probeOfWire, probeValue } from '../app/lib/logic/probes' -import { toProject } from '../app/lib/logic/project' -import { Simulator } from '../app/lib/logic/sim' -import type { ComponentDef } from '../app/lib/logic/types' - -/** Four switches into a cable, the cable to four lamps. */ -function setup() { - 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' } })), - } - p.components.push(def) - const res = bundleWires(def, ['w0', 'w1', 'w2', 'w3'], lookup(p)) - if (!res.ok) throw new Error(res.error) - return { p, def } -} - -describe('analyzer signals', () => { - it('a cable reads as one number, wire 0 the lowest bit; a wire as 0 or 1', () => { - const { p, def } = setup() - const s = new Simulator(compile(lookup(p), def.id)) - s.setSource('s0', true) - s.setSource('s2', true) - s.run() - const cable = def.wires.find(w => def.nodes.find(n => n.id === w.from.node)?.kind === 'bundle')! - const cp = probeOfWire(cable) - expect(probeBits(def, cp)).toBe(4) - expect(probeValue(def, cp, (n, pin) => s.pin(n, pin))).toBe(5) - const lamp = def.nodes.find(n => n.id === 'l2')! - const lp = probeAt(def, lamp, 'a', 'in', lookup(p))! - expect(probeBits(def, lp)).toBe(1) - expect(probeValue(def, lp, (n, pin) => s.pin(n, pin))).toBe(1) - expect(probeName(def, { node: 's1', pin: 'q' }, lookup(p))).toBe('S1') - expect(probeName(def, cp, lookup(p))).toBe('Cable 4') - }) - - it('watched signals are saved with the circuit and survive loading', () => { - const { p, def } = setup() - def.probes = [{ node: 's0', pin: 'q' }, { node: 'x', pin: 'q', label: 'mine' }] - const back = toProject(JSON.parse(JSON.stringify(p)))! - expect(back.components.find(c => c.id === 'root')!.probes).toEqual(def.probes) - }) -}) diff --git a/tests/scope.test.ts b/tests/scope.test.ts new file mode 100644 index 0000000..dcb0414 --- /dev/null +++ b/tests/scope.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest' +import { compile } from '../app/lib/logic/compile' +import { shapeOf } from '../app/lib/logic/geometry' +import { createProject, lookup } from '../app/lib/logic/ops' +import { toProject } from '../app/lib/logic/project' +import { scopeLayout } from '../app/lib/logic/scopeLayout' +import type { CircuitNode } from '../app/lib/logic/types' + +/** A channel as it comes back from loading a project. */ +function clean(col: unknown) { + const p = createProject({ examples: false }) + p.components[0]!.nodes.push({ id: 's', kind: 'scope', x: 0, y: 0, scope: { cols: [col as never] } }) + return toProject(JSON.parse(JSON.stringify(p))).components[0]!.nodes.find(n => n.id === 's')!.scope!.cols[0] +} + +describe('logic analyzer part', () => { + it('a pin per bit down the left, a lane per channel beside its pins', () => { + const p = createProject({ examples: false }) + const n: CircuitNode = { id: 's', kind: 'scope', x: 0, y: 0, scope: { cols: [{ id: 'a', name: 'CLK', bits: 1 }, { id: 'b', name: 'D', bits: 4 }] } } + const shape = shapeOf(n, lookup(p)) + expect(shape.inputs.map(i => [i.label, i.dy])).toEqual([['CLK', 1], ['D0', 2], ['D1', 3], ['D2', 4], ['D3', 5]]) + expect(scopeLayout(n).lanes.map(l => [l.row, l.bits])).toEqual([[1, 1], [2, 4]]) + p.components[0]!.nodes.push(n) + expect(compile(lookup(p), p.components[0]!.id).errors).toEqual([]) + }) + + it('its channels are saved and cleaned on loading', () => { + expect(clean({ id: 'a', name: 'X'.repeat(50), bits: 99 })).toEqual({ id: 'a', name: 'X'.repeat(40), bits: 1 }) + }) +})
- Right-click a wire, a cable or a pin and choose Watch in analyzer. Then run the clock, step it, or flip switches. -