R logic analyzer is a wired part: channels as input pins, waves on its box; dropped on a component it watches all its outputs. Drops the floating panel and Watch in analyzer

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-28 13:35:04 +01:00
parent 0d6758c8c9
commit 87272ff555
22 changed files with 346 additions and 457 deletions

View File

@ -5690,117 +5690,6 @@ button.tile:hover {
stroke-dasharray: 3 2; 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 { .node .pixel-rgb {
fill: #5a6779; fill: #5a6779;
@ -6373,3 +6262,55 @@ button.tile:hover {
.bench-empty { .bench-empty {
margin-top: 12px; 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;
}

View File

@ -1,145 +0,0 @@
<script setup lang="ts">
// The logic analyzer: the watched signals of the open circuit over time, a
// lane each. A wire is a square wave, a cable a bus with its value. One
// step per clock half-cycle while the clock runs, and one for every other
// change. Point at the waves to read every value at that moment; the wheel
// scrolls back through time.
import { probeBits, probeName } from '~/lib/logic/probes'
const ed = useEditor()
const def = ed.def
const probes = computed(() => def.value.probes ?? [])
const CELL = 10 // pixels per sample
const NAME_W = 150
const LANE_H = 26
const wave = ref<HTMLElement>()
const width = ref(600)
let ro: ResizeObserver | undefined
onMounted(() => {
ro = new ResizeObserver(() => (width.value = wave.value?.clientWidth ?? 600))
if (wave.value) ro.observe(wave.value)
})
onBeforeUnmount(() => ro?.disconnect())
// The trace grows in place: a new object each time, so what reads it follows.
const samples = computed(() => ({ v: ed.traceVersion.value, list: ed.trace.value }))
const total = computed(() => samples.value.list.length)
/** How far back from the newest sample the view is (0: following the newest). */
const back = ref(0)
const count = computed(() => Math.max(1, Math.floor(width.value / CELL)))
const view = computed(() => {
const all = samples.value.list
const end = Math.max(0, all.length - back.value)
const start = Math.max(0, end - count.value)
return { start, list: all.slice(start, end) }
})
function onWheel(e: WheelEvent) {
const step = Math.round((Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY) / 20) || Math.sign(e.deltaY)
back.value = Math.max(0, Math.min(Math.max(0, total.value - count.value), back.value + step))
}
/** The sample pointed at (in the view), else the newest. */
const at = ref<number | null>(null)
function onMove(e: PointerEvent) {
const r = wave.value!.getBoundingClientRect()
const i = Math.floor((e.clientX - r.left) / CELL)
at.value = i >= 0 && i < view.value.list.length ? i : null
}
const shown = computed(() => view.value.list[at.value ?? view.value.list.length - 1])
const bits = (i: number) => probeBits(def.value, probes.value[i]!)
const hexOf = (v: number, b: number) => (b === 1 ? String(v) : `0x${v.toString(16).toUpperCase().padStart(Math.ceil(b / 4), '0')}`)
const valueText = (i: number) => {
const s = shown.value
if (!s) return '–'
const v = s.vals[i] ?? 0
const b = bits(i)
return b === 1 ? String(v) : `${v} · ${hexOf(v, b)}`
}
/** A wire's square wave. */
function square(i: number): string {
const top = 5
const low = LANE_H - 5
let d = ''
view.value.list.forEach((s, k) => {
const y = s.vals[i] ? top : low
d += k ? `L${k * CELL} ${y}H${(k + 1) * CELL}` : `M0 ${y}H${CELL}`
})
return d
}
/** A cable's runs of one value: a long hexagon each, named by its value when there is room. */
function runs(i: number): { x: number; w: number; v: number }[] {
const out: { x: number; w: number; v: number }[] = []
view.value.list.forEach((s, k) => {
const v = s.vals[i] ?? 0
const last = out[out.length - 1]
if (last && last.v === v) last.w += CELL
else out.push({ x: k * CELL, w: CELL, v })
})
return out
}
const hexagon = (r: { x: number; w: number }) => {
const m = Math.min(3, r.w / 3)
const t = 5
const b = LANE_H - 5
const c = LANE_H / 2
return `M${r.x} ${c}L${r.x + m} ${t}H${r.x + r.w - m}L${r.x + r.w} ${c}L${r.x + r.w - m} ${b}H${r.x + m}Z`
}
/** Clock steps: where a new clock cycle began, numbered now and then. */
const marks = computed(() => {
const out: { x: number; n?: number }[] = []
view.value.list.forEach((s, k) => {
const prev = view.value.list[k - 1]
if (prev && s.cycle !== prev.cycle) out.push({ x: k * CELL, ...(s.cycle % 5 === 0 ? { n: s.cycle } : {}) })
})
return out
})
const name = (i: number) => probeName(def.value, probes.value[i]!, ed.getDef.value)
</script>
<template>
<section class="analyzer" aria-label="Logic analyzer">
<header class="analyzer-head">
<Icon name="lucide:activity" class="size-4 text-(--accent)" />
<span class="font-semibold">Logic analyzer</span>
<span class="hint">{{ total }} {{ total === 1 ? 'step' : 'steps' }}<template v-if="back"> · {{ back }} back</template></span>
<button v-if="back" class="btn-sm" title="Follow the newest again" @click="back = 0"><Icon name="lucide:chevrons-right" class="size-3.5" /> Now</button>
<span class="grow" />
<button class="icon-btn" title="Start over" :disabled="!total" @click="ed.clearTrace()"><Icon name="lucide:eraser" class="size-4" /></button>
<button class="icon-btn" title="Close (the signals stay watched)" @click="ed.analyzerOpen.value = false"><Icon name="lucide:x" class="size-4" /></button>
</header>
<p v-if="!probes.length" class="hint analyzer-empty">
Right-click a wire, a cable or a pin and choose <strong>Watch in analyzer</strong>. Then run the clock, step it, or flip switches.
</p>
<div v-else class="analyzer-body">
<ul class="analyzer-names" :style="{ width: `${NAME_W}px` }">
<li v-for="(p, i) in probes" :key="`${p.node}:${p.pin}`" :style="{ height: `${LANE_H}px` }">
<span class="truncate" :title="name(i)">{{ name(i) }}</span>
<span class="analyzer-val tabular-nums">{{ valueText(i) }}</span>
<button class="icon-btn" title="Stop watching" @click="ed.unwatch(i)"><Icon name="lucide:x" class="size-3" /></button>
</li>
</ul>
<div ref="wave" class="analyzer-wave" @wheel.prevent="onWheel" @pointermove="onMove" @pointerleave="at = null">
<svg :width="view.list.length * CELL" :height="probes.length * LANE_H">
<line v-for="(m, k) in marks" :key="`m${k}`" :x1="m.x" :x2="m.x" y1="0" :y2="probes.length * LANE_H" class="analyzer-mark" />
<g v-for="(p, i) in probes" :key="`${p.node}:${p.pin}`" :transform="`translate(0 ${i * LANE_H})`">
<path v-if="bits(i) === 1" :d="square(i)" class="analyzer-bit" />
<template v-else>
<template v-for="(r, k) in runs(i)" :key="k">
<path :d="hexagon(r)" class="analyzer-bus" />
<text v-if="r.w >= 26" :x="r.x + r.w / 2" :y="LANE_H / 2 + 3.5" text-anchor="middle" class="analyzer-bus-text">{{ hexOf(r.v, bits(i)) }}</text>
</template>
</template>
</g>
<line v-if="at !== null" :x1="at * CELL + CELL / 2" :x2="at * CELL + CELL / 2" y1="0" :y2="probes.length * LANE_H" class="analyzer-cursor" />
</svg>
<span v-if="shown" class="analyzer-cycle tabular-nums">tick {{ shown.cycle }}</span>
</div>
</div>
</section>
</template>

View File

@ -45,7 +45,6 @@ watch(
</main> </main>
<EditorSelectionPanel v-if="hasSelection" /> <EditorSelectionPanel v-if="hasSelection" />
<EditorToolbar /> <EditorToolbar />
<EditorAnalyzer v-if="ed.analyzerOpen.value" />
<EditorBottomBar /> <EditorBottomBar />
</div> </div>
</template> </template>

View File

@ -10,7 +10,6 @@ import { dropLinks, dropPins, fitStart, type DropPin } from '~/lib/logic/fit'
import type { CanvasOps, MenuEntry } from '~/composables/useMenu' import type { CanvasOps, MenuEntry } from '~/composables/useMenu'
import { cableInUse, LANE, plugLayout, ribbon, RIBBON_MAX } from '~/lib/logic/cables' import { cableInUse, LANE, plugLayout, ribbon, RIBBON_MAX } from '~/lib/logic/cables'
import { latchLayout, latchSeam } from '~/lib/logic/latch' import { latchLayout, latchSeam } from '~/lib/logic/latch'
import { probeAt } from '~/lib/logic/probes'
import { keyCode } from '~/lib/logic/devices' import { keyCode } from '~/lib/logic/devices'
import { moveParts, moveStart, type MoveStart } from '~/lib/logic/move' import { moveParts, moveStart, type MoveStart } from '~/lib/logic/move'
import { wirePath, type HopSpan } from '~/lib/draw' import { wirePath, type HopSpan } from '~/lib/draw'
@ -1174,7 +1173,7 @@ function onPointerUp(e: PointerEvent) {
ed.commit(false) ed.commit(false)
} else if (d.moved) { } else if (d.moved) {
ed.unplugMoved(new Set(d.orig.nodes.keys())) 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 (d.benchHit === 'run') ed.runBenchNow(d.node.id, true)
else if (typeof d.benchHit === 'number') ed.applyBenchRow(d.node.id, d.benchHit) 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) 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') 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')) }) 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)) { if (dir === 'in' && ed.canInvert(n, pin)) {
const on = n.invert?.includes(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) }) 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) })

View File

@ -5,7 +5,7 @@ import { compile } from '~/lib/logic/compile'
import { cableOf } from '~/lib/logic/cables' import { cableOf } from '~/lib/logic/cables'
import { INVERTIBLE } from '~/lib/logic/compile' import { INVERTIBLE } from '~/lib/logic/compile'
import { cableBits, cableOffsets, chipPins, MAX_BITS, panelOffsets, portName, rowLabel } from '~/lib/logic/geometry' 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 { KIND_NAMES } from '~/lib/logic/progress'
import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide' 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' 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 else delete row.hz
ed.commit() 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))
}
</script> </script>
<template> <template>
@ -697,6 +712,20 @@ function setRowHz(row: PanelRow, e: Event) {
<input :value="n.key ?? ''" readonly placeholder="Click, then press a key" class="key-input field-input" @keydown="setKey" /> <input :value="n.key ?? ''" readonly placeholder="Click, then press a key" class="key-input field-input" @keydown="setKey" />
</EditorFold> </EditorFold>
<div v-if="n.kind === 'scope'" class="field">
<span>Channels: wire to their pins on the left</span>
<div v-for="(c, i) in n.scope?.cols ?? []" :key="c.id" class="scope-chan">
<input class="field-input" :value="c.name" spellcheck="false" @change="renameChannel(i, ($event.target as HTMLInputElement).value)" />
<input class="field-input scope-bits" type="number" min="1" max="32" :value="c.bits" title="Bits: one pin each, read as one number" @change="setChannelBits(i, ($event.target as HTMLInputElement).value)" />
<button class="icon-btn" title="Remove the channel" @click="ed.setScope(n.id, cols => cols.splice(i, 1))"><Icon name="lucide:trash-2" class="size-3.5" /></button>
</div>
<div class="flex gap-2">
<button class="btn-sm" @click="addChannel(1)"><Icon name="lucide:plus" class="size-3.5" /> Wire</button>
<button class="btn-sm" @click="addChannel(8)"><Icon name="lucide:plus" class="size-3.5" /> 8-bit bus</button>
<button class="btn-sm" @click="ed.clearScope(n.id)"><Icon name="lucide:eraser" class="size-3.5" /> Start over</button>
</div>
</div>
<EditorFold v-if="n.kind === 'pixel'" id="pixel-screen" title="Screen on the box" :note="n.screen ?? ''"> <EditorFold v-if="n.kind === 'pixel'" id="pixel-screen" title="Screen on the box" :note="n.screen ?? ''">
<input <input
class="field-input" class="field-input"

View File

@ -4,6 +4,7 @@ import { LANE, nameTags, RIBBON_MAX } from '~/lib/logic/cables'
import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide' import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide'
import { faceTransform, GRID as G, noteLines, noteScale, PANEL_CONTROL_W, portLines, rgbHex, shapeTransform, type Shape } from '~/lib/logic/geometry' import { faceTransform, GRID as G, noteLines, noteScale, PANEL_CONTROL_W, portLines, rgbHex, shapeTransform, type Shape } from '~/lib/logic/geometry'
import { benchLayout } from '~/lib/logic/benchLayout' import { benchLayout } from '~/lib/logic/benchLayout'
import { SCOPE_CELL, SCOPE_SAMPLES, scopeLayout } from '~/lib/logic/scopeLayout'
import { keyLabel, TERMINAL_COLS, TERMINAL_LINES } from '~/lib/logic/devices' import { keyLabel, TERMINAL_COLS, TERMINAL_LINES } from '~/lib/logic/devices'
import type { CircuitNode } from '~/lib/logic/types' import type { CircuitNode } from '~/lib/logic/types'
@ -173,6 +174,49 @@ const faceHex = (inner: string) => sevenSegment([0, 1, 2, 3].reduce((n, i) => n
/** The colour of an RGB pixel inside this chip ('' while off). */ /** 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 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')) : '')) 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. // Test bench: the layout of its box, its rows and how they went.
interface BenchRowView { interface BenchRowView {
i: number i: number
@ -462,6 +506,26 @@ const title = computed(() => {
<text v-if="!lines.length" :x="(b.w * G) / 2" :y="G + 3.5" text-anchor="middle" class="pin-label">{{ node.conn && !connType ? 'type missing' : 'no lines' }}</text> <text v-if="!lines.length" :x="(b.w * G) / 2" :y="G + 3.5" text-anchor="middle" class="pin-label">{{ node.conn && !connType ? 'type missing' : 'no lines' }}</text>
</template> </template>
<!-- Logic analyzer: a lane per channel, its value now and its wave -->
<template v-else-if="node.kind === 'scope'">
<rect x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="4" class="body scope-body" />
<text :x="0.4 * G" :y="0.1 * G" class="bench-title">{{ node.label?.trim() || 'Logic analyzer' }}</text>
<text v-if="!sl.lanes.length" :x="0.4 * G" :y="1.3 * G" class="bench-line">Drop on a component</text>
<g v-for="(m, k) in scopeView.marks" :key="`m${k}`">
<line :x1="m" :x2="m" :y1="0.5 * G" :y2="(b.y + b.h) * G - 2" class="scope-mark" />
</g>
<g v-for="l in scopeView.lanes" :key="l.id">
<rect :x="sl.waveX * G" :y="(l.row - 0.5) * G + 1" :width="SCOPE_SAMPLES * SCOPE_CELL" :height="l.bits * G - 2" rx="2" class="scope-lane" />
<text :x="sl.valueX * G + 2" :y="(l.row - 0.5 + l.bits / 2) * G + 3.5" class="scope-value">{{ l.value }}</text>
<path v-if="l.bits === 1" :d="l.wave" class="scope-wave" />
<template v-else>
<path v-for="(r, k) in l.runs" :key="k" :d="r.d" class="scope-bus" />
<text v-for="(r, k) in l.runs.filter(x => x.label)" :key="`t${k}`" :x="r.mid" :y="(l.row - 0.5 + l.bits / 2) * G + 3.5" text-anchor="middle" class="scope-bus-text">{{ r.label }}</text>
</template>
</g>
<text v-for="p in shape.inputs" :key="p.key" :x="4" :y="p.dy * G + 3" class="pin-label tiny">{{ p.label }}</text>
</template>
<!-- Test bench: its table on the box, run button in the title bar --> <!-- Test bench: its table on the box, run button in the title bar -->
<template v-else-if="node.kind === 'bench'"> <template v-else-if="node.kind === 'bench'">
<rect x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="4" class="body bench-body" :class="bench.state" /> <rect x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="4" class="body bench-body" :class="bench.state" />

View File

@ -41,7 +41,6 @@ const ACTIONS: Action[] = [
run: () => ed.packageSelected('Part'), 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: '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: '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: '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') }, { id: 'table', label: 'Truth table', icon: 'lucide:table', aka: 'test outputs', run: () => (ed.dialog.value = 'table') },

View File

@ -142,7 +142,6 @@ const linkIcon = computed(() => {
// Tools that work beside the circuit. // Tools that work beside the circuit.
const toolsMenu = ref<{ x: number; y: number } | null>(null) const toolsMenu = ref<{ x: number; y: number } | null>(null)
const toolEntries = computed<MenuEntry[]>(() => [ const toolEntries = computed<MenuEntry[]>(() => [
{ 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: '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') }, { label: 'Assembler…', icon: 'lucide:file-code-2', note: 'program to memory', run: () => (ed.dialog.value = 'asm') },
]) ])
@ -260,7 +259,7 @@ const moreEntries = computed<MenuEntry[]>(() => {
<select v-model.number="ed.hz.value" class="tb-select" title="Clock speed" :disabled="!hasClock"> <select v-model.number="ed.hz.value" class="tb-select" title="Clock speed" :disabled="!hasClock">
<option v-for="s in SPEEDS" :key="s.value" :value="s.value">{{ s.label }}</option> <option v-for="s in SPEEDS" :key="s.value" :value="s.value">{{ s.label }}</option>
</select> </select>
<button class="bar-btn" :class="{ active: ed.analyzerOpen.value, open: !!toolsMenu }" title="Tools: logic analyzer, converter, assembler" @click="toolsMenu = toolsMenu ? null : below($event)"> <button class="bar-btn" :class="{ open: !!toolsMenu }" title="Tools: converter, assembler" @click="toolsMenu = toolsMenu ? null : below($event)">
<Icon name="lucide:wrench" class="size-4" /> <Icon name="lucide:wrench" class="size-4" />
</button> </button>
<EditorContextMenu v-if="toolsMenu" :x="toolsMenu.x" :y="toolsMenu.y" :entries="toolEntries" @close="toolsMenu = null" /> <EditorContextMenu v-if="toolsMenu" :x="toolsMenu.x" :y="toolsMenu.y" :entries="toolEntries" @close="toolsMenu = null" />

View File

@ -25,9 +25,8 @@ import { challengeName, challengeOpen, defUsable, isCampaign, KIND_NAMES, kindUn
import { apiId, makePuzzle, scoreSolution, weekKey, weeklyId } from '~/lib/logic/puzzles' import { apiId, makePuzzle, scoreSolution, weekKey, weeklyId } from '~/lib/logic/puzzles'
import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide' import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide'
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges' 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 { 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 { EXAMPLE as ASM_EXAMPLE, loadIntoPanels } from '~/lib/asm'
import { latchedTo, latchInto, latchTarget, syncLatches } from '~/lib/logic/latch' 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' 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 AccountUser,
type ProjectMeta, type ProjectMeta,
} from '~/lib/logic/storage' } 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. */ /** A challenge check plus how many transistors the solution uses. */
/** How everyone did on a puzzle, from the server. */ /** How everyone did on a puzzle, from the server. */
@ -650,61 +649,54 @@ function create() {
devVersion.value++ devVersion.value++
} }
// ── Logic analyzer ──────────────────────────────────────────────── // ── Logic analyzer parts ──────────────────────────────────────────
/** The analyzer panel is open. */ /** What each analyzer part saw, oldest first, by part id: one sample per clock half-step, and on every other change. Not saved. */
const analyzerOpen = ref(false) const scopeTraces = shallowRef(new Map<string, { cycle: number; vals: number[] }[]>())
/** What the watched signals were, oldest first: one sample per clock half-step, and on every other change. */ /** Goes up with every new sample. */
const trace = shallowRef<{ cycle: number; vals: number[]; edge: boolean }[]>([]) const scopeVersion = ref(0)
const traceVersion = ref(0) const SCOPE_KEEP = 600
const TRACE_MAX = 1000 /** Each part's channels when last sampled: other channels start it over. */
let traceKey = '' const scopeKeys = new Map<string, string>()
/** 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) { function sample(edge = false) {
const s = sim.value const s = sim.value
const d = def.value if (!s) return
const ps = d.probes let changed = false
if (!s || !ps?.length) return for (const n of def.value.nodes) {
// Other signals (or another circuit): start over. if (n.kind !== 'scope' || !n.scope?.cols.length) continue
const key = `${d.id}|${ps.map(p => `${p.node}:${p.pin}`).join(',')}` const key = n.scope.cols.map(c => `${c.id}/${c.bits}`).join(',')
if (key !== traceKey) { let list = scopeTraces.value.get(n.id)
traceKey = key if (!list || scopeKeys.get(n.id) !== key) {
trace.value = [] scopeKeys.set(n.id, key)
list = []
scopeTraces.value.set(n.id, list)
} }
const vals = ps.map(p => probeValue(d, p, (n, pin) => s.pin(n, pin))) const vals = n.scope.cols.map(c => colKeys(c).reduce((v, k, i) => v + (s.pin(n.id, k) ? 2 ** i : 0), 0))
const list = trace.value
const last = list[list.length - 1] const last = list[list.length - 1]
if (!edge && last && last.vals.every((v, i) => v === vals[i])) return if (!edge && last && last.vals.every((v, i) => v === vals[i])) continue
list.push({ cycle: cycles.value, vals, edge }) list.push({ cycle: cycles.value, vals })
if (list.length > TRACE_MAX) list.splice(0, list.length - TRACE_MAX) if (list.length > SCOPE_KEEP) list.splice(0, list.length - SCOPE_KEEP)
traceVersion.value++ changed = true
}
if (changed) scopeVersion.value++
} }
function clearTrace() { function clearScope(id: string) {
trace.value = [] scopeTraces.value.set(id, [])
traceVersion.value++ scopeVersion.value++
sample(true) sample(true)
} }
/** Watches a signal in the analyzer (and opens it). */ /** An analyzer part's channels changed (an undo step; its pins change). */
function watchSignal(p: Probe | null) { function setScope(id: string, change: (cols: ScopeCol[]) => void) {
if (!p) return const n = def.value.nodes.find(x => x.id === id)
const d = def.value if (!n || n.kind !== 'scope') return
if (!(d.probes ?? []).some(x => x.node === p.node && x.pin === p.pin)) { n.scope ??= { cols: [] }
d.probes = [...(d.probes ?? []), { node: p.node, pin: p.pin }] change(n.scope.cols)
commit(false) commit()
}
analyzerOpen.value = true
nextTick(() => sample(true))
} }
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() { function startLoop() {
let lastT = performance.now() let lastT = performance.now()
@ -918,12 +910,13 @@ function create() {
if (p.kind === 'panel' || p.kind === 'outpanel') node.rows = newPanelRows() if (p.kind === 'panel' || p.kind === 'outpanel') node.rows = newPanelRows()
if (p.kind === 'bundle' || p.kind === 'split') node.bits = 4 if (p.kind === 'bundle' || p.kind === 'split') node.bits = 4
if (p.kind === 'bench') node.bench = { cols: [], rows: [] } 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. // 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 if (p.kind === 'pixel' && def.value.nodes.findLast(n => n.kind === 'pixel')?.rgb) node.rgb = true
def.value.nodes.push(node) def.value.nodes.push(node)
// A bench put down on a component: set up for it. // A bench put down on a component: set up for it.
const benchChip = p.kind === 'bench' ? benchSpot(node) : undefined const benchChip = p.kind === 'bench' || p.kind === 'scope' ? benchSpot(node) : undefined
if (benchChip) benchOnto(node, benchChip) if (benchChip) (p.kind === 'scope' ? scopeOnto : benchOnto)(node, benchChip)
rememberPart(p.kind, p.chip) rememberPart(p.kind, p.chip)
const swap = (r: PinRef) => (r.node === 'ghost' ? { node: node.id, pin: r.pin } : r) 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 const made = links.filter(l => addWire(swap(l.from), swap(l.to))).length
@ -1456,22 +1449,25 @@ function create() {
const benchLive = shallowRef(new Map<string, number>()) const benchLive = shallowRef(new Map<string, number>())
let benchTimer: ReturnType<typeof setTimeout> | undefined let benchTimer: ReturnType<typeof setTimeout> | undefined
/** The component under a bench's middle, or within two squares of it. */ /** The component a bench or analyzer was dropped on: the one its box overlaps most, else the nearest within two squares. */
function benchSpot(bench: CircuitNode): CircuitNode | undefined { function benchSpot(part: CircuitNode): CircuitNode | undefined {
const own = shapeOf(bench, getDef.value).body const own = shapeOf(part, getDef.value).body
const x = bench.x + own.x + own.w / 2 const ax = part.x + own.x
const y = bench.y + own.y + own.h / 2 const ay = part.y + own.y
let best: CircuitNode | undefined let best: CircuitNode | undefined
let bestD = 2.01 let bestScore = -2.01
for (const n of def.value.nodes) { 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 b = shapeOf(n, getDef.value).body
const dx = Math.max(n.x + b.x - x, 0, x - (n.x + b.x + b.w)) const bx = n.x + b.x
const dy = Math.max(n.y + b.y - y, 0, y - (n.y + b.y + b.h)) const by = n.y + b.y
const d = Math.max(dx, dy) const ox = Math.min(ax + own.w, bx + b.w) - Math.max(ax, bx)
if (d < bestD) { 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 best = n
bestD = d bestScore = score
} }
} }
return best return best
@ -1493,13 +1489,30 @@ function create() {
return true 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) { function dropBench(bench: CircuitNode) {
const chip = benchSpot(bench) 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() commit()
scheduleBenches() 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 return true
} }
@ -3104,12 +3117,10 @@ function create() {
val, val,
faceVal, faceVal,
startLoop, startLoop,
analyzerOpen, scopeTraces,
trace, scopeVersion,
traceVersion, clearScope,
clearTrace, setScope,
watchSignal,
unwatch,
step, step,
rebuild, rebuild,
resetState, resetState,

View File

@ -7,7 +7,6 @@ import { cableInUse, cableOf } from '~/lib/logic/cables'
import { INVERTIBLE } from '~/lib/logic/compile' import { INVERTIBLE } from '~/lib/logic/compile'
import { cableBits, chipPins, portName, type Pt } from '~/lib/logic/geometry' import { cableBits, chipPins, portName, type Pt } from '~/lib/logic/geometry'
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops' import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
import { probeAt, probeOfWire } from '~/lib/logic/probes'
import { KIND_NAMES } from '~/lib/logic/progress' import { KIND_NAMES } from '~/lib/logic/progress'
import { LAMP_COLORS, WIRE_COLORS, type CircuitNode, type NodeKind } from '~/lib/logic/types' import { LAMP_COLORS, WIRE_COLORS, type CircuitNode, type NodeKind } from '~/lib/logic/types'
import { baseOf, gateFamily, inputCount } from '~/lib/logic/wide' 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!) }, { 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') { if (n.kind === 'bench') {
out.push( out.push(
{ label: 'Columns and rows', icon: 'lucide:table', keys: 'Double-click', run: () => (ed.benchOpen.value = n.id) }, { 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 (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 (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) }) 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]) const swaps = swapChoices([n])
if (swaps.length) out.push({ label: 'Change to', icon: 'lucide:replace', children: swaps }) 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() }, { 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) }) 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)) const colors = new Set(list.map(w => w.color))
out.push({ out.push({

View File

@ -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.', 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', 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',
},
], ],
}, },
{ {

View File

@ -5,10 +5,10 @@
import type { BenchCol, CircuitNode } from './types' import type { BenchCol, CircuitNode } from './types'
/** Pin keys of a column, bit 0 first. */ /** 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<BenchCol, 'id' | 'bits'>) => Array.from({ length: c.bits }, (_, i) => `${c.id}.${i}`)
/** A column's pin names: its name, numbered when it has several bits. */ /** 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<BenchCol, 'name' | 'bits'>) => (c.bits === 1 ? [c.name] : Array.from({ length: c.bits }, (_, i) => `${c.name}${i}`))
/** Rows the box shows; more are in the dialog. */ /** Rows the box shows; more are in the dialog. */
export const BENCH_ROWS_SHOWN = 24 export const BENCH_ROWS_SHOWN = 24

View File

@ -61,6 +61,8 @@ export function inputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup):
return ['next'] return ['next']
case 'bench': case 'bench':
return (node.bench?.cols ?? []).filter(c => c.dir === 'check').flatMap(colKeys) return (node.bench?.cols ?? []).filter(c => c.dir === 'check').flatMap(colKeys)
case 'scope':
return (node.scope?.cols ?? []).flatMap(colKeys)
case 'outpanel': case 'outpanel':
return (node.rows ?? []).map(r => r.id) return (node.rows ?? []).map(r => r.id)
case 'bundle': case 'bundle':

View File

@ -3,6 +3,7 @@
import type { CircuitNode, ComponentDef, ConnectorType, FaceShape, LampColor, PanelRow, SymbolKind } from './types' import type { CircuitNode, ComponentDef, ConnectorType, FaceShape, LampColor, PanelRow, SymbolKind } from './types'
import { benchLayout } from './benchLayout' import { benchLayout } from './benchLayout'
import { scopeLayout } from './scopeLayout'
import { DATA_KEYS, DEVICE_PIN_NAMES } from './devices' import { DATA_KEYS, DEVICE_PIN_NAMES } from './devices'
export const GRID = 16 export const GRID = 16
@ -843,6 +844,10 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
return TERMINAL_SHAPE return TERMINAL_SHAPE
case 'bench': case 'bench':
return benchShape(node) 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': case 'keyboard':
return KEYBOARD_SHAPE return KEYBOARD_SHAPE
case 'outpanel': case 'outpanel':

View File

@ -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). // 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 === '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 === '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 [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 return c ? colPinNames(c)[Number(bit)] : undefined
} }
if (node.kind !== 'chip' || !node.chip) return undefined if (node.kind !== 'chip' || !node.chip) return undefined

View File

@ -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
}

View File

@ -31,6 +31,7 @@ export const KIND_NAMES: Partial<Record<NodeKind, string>> = {
terminal: 'Terminal', terminal: 'Terminal',
keyboard: 'Keyboard', keyboard: 'Keyboard',
bench: 'Test bench', bench: 'Test bench',
scope: 'Logic analyzer',
} }
/** Challenges each one builds on. */ /** Challenges each one builds on. */

View File

@ -49,6 +49,15 @@ function cleanNode(n: CircuitNode) {
if (n.inner !== undefined && n.inner !== true) delete n.inner if (n.inner !== undefined && n.inner !== true) delete n.inner
if (n.screen !== undefined && typeof n.screen !== 'string') delete n.screen if (n.screen !== undefined && typeof n.screen !== 'string') delete n.screen
if (n.rgb !== undefined && n.rgb !== true) delete n.rgb 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) { if (n.bench !== undefined) {
const b = n.bench as Partial<Bench> const b = n.bench as Partial<Bench>
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) 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)

View File

@ -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 }
}

View File

@ -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 | '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 | '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 | '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' export type NodeKind = BuiltinKind | 'chip'
@ -79,8 +80,10 @@ export interface CircuitNode {
screen?: string screen?: string
/** Pixel with three inputs, red, green and blue: eight colours. */ /** Pixel with three inputs, red, green and blue: eight colours. */
rgb?: boolean rgb?: boolean
/** Test bench: its tests and the component it tests. */ /** Test bench: its columns and tests. */
bench?: Bench 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. */ /** Component: its connector ports (port node ids inside) shown split on this box, with a pin per line to wire by hand. */
splitPorts?: string[] splitPorts?: string[]
} }
@ -103,6 +106,13 @@ export interface BenchCol {
dir: 'drive' | 'check' 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 { export interface BenchRow {
/** Cells of the drive columns by column id: a number, P for a pulse; empty leaves it. */ /** Cells of the drive columns by column id: a number, P for a pulse; empty leaves it. */
set?: Record<string, string> set?: Record<string, string>

View File

@ -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)
})
})

30
tests/scope.test.ts Normal file
View File

@ -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 })
})
})