A compact tidy wiring, pass-through lamps and outputs, gates with up to 16 inputs

- Tidy wiring orders all wires entering one column together and lays
  them out as one compact staircase a grid step apart, sliding only
  within that gap to avoid running along other signals. Separate
  bundles into the same part no longer cross each other.
- Lamps and output pins get a pin on the right that carries the same
  signal on; labels move above when it is wired.
- AND, OR, XOR, NAND and NOR (built in, examples or your own, detected
  from the truth table) take 2 to 16 inputs. The wide version is a
  balanced tree of the two-input gate, so transistors count honestly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-20 20:09:23 +02:00
parent 2edb458372
commit 5663685505
12 changed files with 388 additions and 24 deletions

View File

@ -7,6 +7,8 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
## What it does
- Parts: NAND, input switch, output pin, lamp, push button, clock, constant 1, ground, hex display, pixel, cable bundle and split, input panel, note.
- Lamps and output pins pass their signal on: the pin on their right carries the same value, so a lamp can sit in the middle of a wire.
- Gates with more inputs: a placed AND, OR, XOR, NAND or NOR (built in, from the examples, or your own) has an "Inputs" setting from 2 to 16. The wide version is a component built as a balanced tree of the two-input gate (NAND and NOR as the plain gate plus a final inverted one), made once per gate and width in "Wide gates" and reused; transistors count honestly and changes to the two-input gate carry through. Which gates qualify is read off their truth table ([app/lib/logic/wide.ts](app/lib/logic/wide.ts)).
- Campaign (Projects → New campaign): you start with NAND, inputs, outputs, lamps and notes, and no examples. Each challenge opens once the ones it builds on are solved (NOT → AND, OR, SR Latch → …), and your own solution becomes a part you can place. Other basic parts unlock on the way: constants with NOT, the input panel with AND, hex display and pixel with the decoder, cables with Adder 2, the button with the SR latch, the clock with the D latch. Rules in [app/lib/logic/progress.ts](app/lib/logic/progress.ts). Sandbox projects keep everything open.
- Puzzles: "Publish as puzzle" (This circuit) turns a circuit into a link `/puzzle/<id>`. Only its behaviour is published, as a truth table, or for circuits with memory as a run of input changes from power-on; the circuit stays private. Whoever opens the link gets the puzzle in their project, sees the target and the author's transistor count, and after a pass their solution goes to the server, which re-runs the checks and counts the transistors itself (with a fixed work budget) and keeps each player's best. The board shows everyone's transistor counts and your place. The puzzle of the week is generated from the ISO week, the same for everyone: three or four inputs, one or two outputs, each depending on every input. Players are anonymous ids per browser.
- Sound (speaker in the top bar; volume and clock ticks under Display): clicks for placing, wiring, switches and buttons, a tick per clock cycle up to 8 Hz (off by default), and jingles for a solve, a failed check, unlocks and new records. All synthesised with Web Audio, no sound files ([app/lib/audio.ts](app/lib/audio.ts)).
@ -22,7 +24,7 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
- Gate symbols in IEC 60617 (DIN, default) or ANSI. A component with one output can be drawn as a gate symbol.
- Wires of different signals never share a line: auto-routed wires pick a free column or a detour, and anything still clashing (hand-placed bends) is drawn on its own lane. Crossings are drawn as a bow, triangle, bridge, gap or plain crossing (Display settings on the right with nothing selected). Clicking a junction dot selects its whole signal.
- Connecting: drag from a pin, or click a pin and then the other one. While a wire is drawn, every pin it can go to is ringed (dashed when it already has a wire, which would be replaced); dropping it on a part uses that part's next free pin. "Connect one by one" (W, or the button with several parts selected; on a component "Wire one by one: Inputs / Outputs") numbers the pins of the selection top to bottom and wires them in turn, one click each; clicking the same component again and again fills its pins in order.
- Tidy wiring (Display settings, or "Tidy all wires", which also drops hand-placed bends): every forward wire takes its vertical step in the free gap right in front of the part it feeds, wires sharing a gap get their own evenly spaced column in the order that crosses least, and one signal shares one trunk. On the 4-bit adder without hand routing this cuts crossings from 32 to 18.
- Tidy wiring (Display settings, or "Tidy all wires", which also drops hand-placed bends): every forward wire takes its vertical step in the free gap right in front of the part it feeds. All wires entering parts at the same column are ordered together (each goes where it adds the fewest crossings) and laid out as one compact staircase a grid step apart, slid sideways to where it runs along no other signal; one signal shares one trunk. Only the columns of that gap are looked at, so it stays cheap. On the 4-bit adder without hand routing this cuts crossings from 32 to 18.
- Wire editing: drag any segment (a stub keeps the pin end straight), drag corner squares, Alt+drag to pull out a new bend, Ctrl+drag to branch a new wire off a signal, double-click to select the whole signal, Shift+click and box selection for several wires, arrow keys to shift them, six colour tags.
- Several projects per browser (Projects dialog: open, rename, duplicate, delete). Export a project file, open a file as a new project, or add the components of a file to the open project.
- Accounts: email and password. Signed in, every project in the browser is also kept in the account and synced in both directions (on sign-in, on focus, every minute, and two seconds after a change). If two computers changed the same project, both versions are kept. The untouched starter project of a new browser is not uploaded; signing in there opens your latest project instead.

View File

@ -828,6 +828,7 @@ defineExpose({ fit, zoomAt })
:node="n"
:shape="shapes.get(n.id)!"
:selected="selected.has(n.id)"
:through="linked.out.has(`${n.id}:q`) && (n.kind === 'lamp' || n.kind === 'output')"
/>
<rect

View File

@ -5,6 +5,7 @@ import { cableOf } from '~/lib/logic/cables'
import { cableBits, chipPins, MAX_BITS, rowLabel } from '~/lib/logic/geometry'
import { SINK_KINDS, SOURCE_KINDS } 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, type CircuitNode, type NodeKind, type PanelControl, type PanelRow } from '~/lib/logic/types'
const props = defineProps<{ node: CircuitNode }>()
@ -130,6 +131,13 @@ const dock = computed(() => {
return chip ? chip.label?.trim() || (chip.chip ? ed.getDef.value(chip.chip)?.name : undefined) || 'component' : null
})
/** Gates that can take more inputs (AND, OR, XOR, NAND, NOR and their wide versions). */
const widens = computed(() => {
const base = baseOf(n.value, ed.getDef.value)
return !!base && !!gateFamily(ed.getDef.value, base)
})
const inputs = computed(() => inputCount(n.value, ed.getDef.value))
/** The bundle of the cable this bundle or split belongs to. */
const cableBundle = computed(() => {
if (n.value.kind === 'bundle') return n.value
@ -178,6 +186,19 @@ function setRowHz(row: PanelRow, e: Event) {
</label>
<p v-if="logic || family.length" class="hint -mt-1">Swapping keeps the wires on the pins in the same position.</p>
<label v-if="widens" class="field">
<span>Inputs</span>
<input
type="number"
min="2"
:max="MAX_GATE_INPUTS"
step="1"
:value="inputs"
@change="ed.setInputs(n, Number(($event.target as HTMLInputElement).value))"
/>
</label>
<p v-if="widens && inputs > 2" class="hint -mt-1">Built from {{ inputs - 1 }} two-input gates in a tree, so the transistors count honestly.</p>
<label v-if="hasLabel" class="field">
<span>{{ n.kind === 'note' ? 'Text' : n.kind === 'chip' ? 'Name on the canvas' : 'Label' }}</span>
<textarea v-if="n.kind === 'note'" ref="labelInput" v-model="n.label" rows="3" @change="ed.commit(false)" />

View File

@ -8,6 +8,8 @@ const props = defineProps<{
shape: Shape
selected: boolean
ghost?: boolean
/** The pass-through pin of a lamp or output is wired: its label moves out of the wire's way. */
through?: boolean
}>()
const ed = useEditor()
@ -106,7 +108,7 @@ const title = computed(() => {
<template v-else-if="node.kind === 'output'">
<path :d="`M0 0H${0.4 * G}`" class="stub" />
<path :d="`M${0.4 * G} ${-0.6 * G}H${1.5 * G}L${2 * G} 0L${1.5 * G} ${0.6 * G}H${0.4 * G}Z`" class="terminal" :class="{ on: lit }" />
<text :x="2 * G + 6" :y="4" class="io-label">{{ node.label }}</text>
<text :x="through ? G : 2 * G + 6" :y="through ? -0.75 * G - 4 : 4" :text-anchor="through ? 'middle' : 'start'" class="io-label">{{ node.label }}</text>
</template>
<!-- Lamp: IEC symbol, circle with a cross -->
@ -114,7 +116,7 @@ const title = computed(() => {
<path :d="`M0 0H${0.35 * G}`" class="stub" />
<circle :cx="G" cy="0" :r="0.65 * G" class="lamp" :class="[node.color ? `l-${node.color}` : '', { on: lit }]" />
<path :d="`M${G - 0.46 * G} ${-0.46 * G}L${G + 0.46 * G} ${0.46 * G}M${G + 0.46 * G} ${-0.46 * G}L${G - 0.46 * G} ${0.46 * G}`" class="lamp-cross" :class="{ on: lit }" />
<text v-if="node.label" :x="2 * G + 4" :y="4" class="io-label">{{ node.label }}</text>
<text v-if="node.label" :x="through ? G : 2 * G + 4" :y="through ? -0.75 * G - 4 : 4" :text-anchor="through ? 'middle' : 'start'" class="io-label">{{ node.label }}</text>
</template>
<!-- Constant 1 -->

View File

@ -7,6 +7,7 @@ import { bundleWires, dissolveCable } from '~/lib/logic/cables'
import { loadSoundSettings, saveSoundSettings, sfx, type Sound, type SoundSettings } from '~/lib/audio'
import { challengeName, challengeOpen, defUsable, isCampaign, KIND_NAMES, kindUnlocked, NEEDS, unlockedBy } from '~/lib/logic/progress'
import { apiId, makePuzzle, scoreSolution } 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 { compile, rowSource } from '~/lib/logic/compile'
import { MAX_BITS, shapeOf, type Pt } from '~/lib/logic/geometry'
@ -518,6 +519,18 @@ function create() {
if (removed) notify(`Swapped. ${removed} wire${removed === 1 ? '' : 's'} had no matching pin and were removed.`)
}
/** Gives a placed gate `n` inputs, by swapping in its wide version (made on first use). */
function setInputs(node: CircuitNode, n: number) {
const base = baseOf(node, getDef.value)
if (!base) return
if (base !== NAND_BASE && containsDef(project.value, base, def.value.id)) return notify('A component cannot contain itself', 'error')
const target = wideGate(project.value, base, Math.round(n))
if (!target) return notify(`Gates can have 2 to ${MAX_GATE_INPUTS} inputs`, 'error')
if (target.kind === 'chip' && target.chip === node.chip) return
if (target.kind === 'nand' && node.kind === 'nand') return
swap(node.id, target)
}
function unlink(ids: string[]) {
const n = unlinkWires(def.value, new Set(ids))
commit()
@ -1509,6 +1522,7 @@ function create() {
exportTable,
transistors,
canPlaceKind,
setInputs,
sound,
setSound,
play,

View File

@ -56,6 +56,9 @@ export function inputKeys(node: CircuitNode, pins?: ChipPins): string[] {
export function outputKeys(node: CircuitNode, pins?: ChipPins): string[] {
switch (node.kind) {
case 'output':
case 'lamp':
return ['q']
case 'nand':
case 'input':
case 'high':
@ -203,6 +206,11 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
break
case 'output':
result.set(n.id, inNet(n.id, 'a'))
union(q, inNet(n.id, 'a'))
break
case 'lamp':
// A lamp passes its signal on to whatever its right pin feeds.
union(q, inNet(n.id, 'a'))
break
case 'chip': {
const child = n.chip ? getDef(n.chip) : undefined

View File

@ -200,10 +200,11 @@ const SOURCE_SHAPE: Shape = {
outputs: [{ key: 'q', label: '', dx: 2, dy: 0 }],
}
// Output pins and lamps pass their signal on: the pin on the right carries the same value.
const SINK_SHAPE: Shape = {
body: { x: 0, y: -0.75, w: 2, h: 1.5 },
inputs: [{ key: 'a', label: '', dx: 0, dy: 0 }],
outputs: [],
outputs: [{ key: 'q', label: '', dx: 2, dy: 0 }],
}
const HEX_SHAPE: Shape = {
@ -319,7 +320,7 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
if (!def) return MISSING_SHAPE
const pins = chipPins(def)
const face = faceLayout(def)
if (def.symbol !== 'box' && !face.items.length && pins.outputs.length === 1 && pins.inputs.length >= 1 && pins.inputs.length <= 8) {
if (def.symbol !== 'box' && !face.items.length && pins.outputs.length === 1 && pins.inputs.length >= 1 && pins.inputs.length <= 16) {
return gateShape(def.symbol, pins.inputs, pins.outputs[0]!)
}
return boxShape(def.name, pins, face)

View File

@ -52,6 +52,7 @@ export function toProject(data: unknown): Project {
}
nodes += d.nodes.length
d.symbol ??= 'box'
if (d.wide !== undefined && !(d.wide && typeof d.wide.base === 'string' && Number.isInteger(d.wide.n) && d.wide.n >= 2 && d.wide.n <= 16)) delete d.wide
for (const n of d.nodes) cleanNode(n)
for (const w of d.wires) if (w.color && !WIRE_COLORS.includes(w.color)) delete w.color
}

View File

@ -360,33 +360,60 @@ function crossings(a: TidyNet, b: TidyNet): number {
return n
}
/** Columns for k signals in the gap lo+1 .. hi-1, as far from other signals' columns as it gets. */
function columns(k: number, lo: number, hi: number, spans: TidyNet[], occ: Occupancy): number[] {
/**
* Left-to-right order of the signals in one gap: each one goes where it
* adds the fewest crossings with those placed so far. A few signals per
* gap, so this stays cheap.
*/
function order(nets: TidyNet[]): TidyNet[] {
const out: TidyNet[] = []
for (const n of [...nets].sort((a, b) => a.y1 - b.y1 || a.min - b.min)) {
let best = 0
let bestCost = Infinity
for (let at = 0; at <= out.length; at++) {
let c = 0
for (let i = 0; i < out.length; i++) c += i < at ? crossings(out[i]!, n) : crossings(n, out[i]!)
if (c < bestCost) {
bestCost = c
best = at
}
}
out.splice(best, 0, n)
}
return out
}
/**
* Columns for the ordered signals: one compact staircase, a grid step
* apart, in the middle of the gap lo+1 .. hi-1. The block slides sideways
* to the nearest spot where no column runs along another signal's line;
* only the columns of this gap are looked at.
*/
function columns(nets: TidyNet[], lo: number, hi: number, occ: Occupancy): number[] {
const k = nets.length
const width = hi - lo - 1
if (k > width) return Array.from({ length: k }, (_, i) => lo + 1 + Math.floor((i * width) / k))
const step = width >= 2 * k + 1 ? 2 : 1
const block = (k - 1) * step + 1
const center = lo + 1 + Math.floor((width - block) / 2)
const center = lo + 1 + Math.floor((width - k) / 2)
let best: number[] = []
let bestCost = Infinity
for (let d = 0; d <= width; d++) {
for (const start of d ? [center - d, center + d] : [center]) {
if (start < lo + 1 || start + block - 1 > hi - 1) continue
const cols = Array.from({ length: k }, (_, i) => start + i * step)
if (start < lo + 1 || start + k - 1 > hi - 1) continue
let c = 0
cols.forEach((x, i) => (c += occ.overlap([x, spans[i]!.min], [x, spans[i]!.max], spans[i]!.net)))
nets.forEach((n, i) => (c += occ.overlap([start + i, n.min], [start + i, n.max], n.net)))
if (c < bestCost) {
best = cols
best = nets.map((_, i) => start + i)
bestCost = c
}
if (c === 0) return cols
if (c === 0) return best
}
}
return best
}
function tidyRoutes(inputs: RouteInput[], boxes: Box[], occ: Occupancy, bodies: BodyIndex, pins: Set<number>, grid: Map<string, Pt[]>) {
const gaps = new Map<string, { lo: number; hi: number; nets: Map<string, TidyNet> }>()
// One gap per target column: everything that enters parts at that x is
// sorted together, so separate bundles can't end up crossing each other.
const gaps = new Map<number, { hi: number; nets: Map<string, TidyNet & { lo: number }> }>()
for (const w of inputs) {
if (grid.has(w.id)) continue
const [x1, y1] = w.a
@ -406,21 +433,30 @@ function tidyRoutes(inputs: RouteInput[], boxes: Box[], occ: Occupancy, bodies:
if (right > lo && right < x2 && b.y < max && b.y + b.h > min) lo = Math.ceil(right)
}
if (lo + 1 > x2 - 1) continue
const key = `${lo},${x2}`
const gap = gaps.get(key) ?? gaps.set(key, { lo, hi: x2, nets: new Map() }).get(key)!
const gap = gaps.get(x2) ?? gaps.set(x2, { hi: x2, nets: new Map() }).get(x2)!
const net = gap.nets.get(w.net)
if (net) {
net.ys.push(y2)
net.min = Math.min(net.min, y2)
net.max = Math.max(net.max, y2)
net.lo = Math.max(net.lo, lo)
net.wires.push(w)
} else gap.nets.set(w.net, { net: w.net, y1, ys: [y2], min, max, wires: [w] })
} else gap.nets.set(w.net, { net: w.net, y1, ys: [y2], min, max, lo, wires: [w] })
}
const ordered = [...gaps.values()].sort((p, q) => p.hi - q.hi || p.lo - q.lo)
for (const gap of ordered) {
const nets = [...gap.nets.values()].sort((a, b) => crossings(a, b) - crossings(b, a) || a.y1 - b.y1 || a.min - b.min)
const cols = columns(nets.length, gap.lo, gap.hi, nets, occ)
for (const gap of [...gaps.values()].sort((p, q) => p.hi - q.hi)) {
// The block must fit right of every member's nearest obstacle; a signal
// whose obstacle leaves too little room routes the usual way instead.
let members = [...gap.nets.values()]
for (;;) {
const lo = Math.max(...members.map(n => n.lo))
if (!members.length || gap.hi - lo - 1 >= members.length) break
members = members.filter(n => n.lo !== lo)
}
if (!members.length) continue
const lo = Math.max(...members.map(n => n.lo))
const nets = order(members)
const cols = columns(nets, lo, gap.hi, occ)
nets.forEach((n, i) => {
const x = cols[i]!
for (const w of n.wires) {

View File

@ -109,6 +109,8 @@ export interface ComponentDef {
wires: Wire[]
/** Set when the component was started from a challenge. */
challenge?: string
/** A gate with more inputs, built from a two-input gate (a component id, or "nand"). */
wide?: { base: string; n: number }
}
export interface Settings {

156
app/lib/logic/wide.ts Normal file
View File

@ -0,0 +1,156 @@
// Gates with more inputs. A two-input gate that can be chained (AND, OR,
// XOR) or is the inverse of one (NAND, NOR) gets a wide version with up to
// 16 inputs, built as a balanced tree of the two-input gate itself. So the
// transistor count stays honest, and a change to your AND reaches every
// wide AND built from it. Wide versions are ordinary components, made once
// per gate and width and reused.
import { compile } from './compile'
import { chipPins, type DefLookup } from './geometry'
import { lookup, uid, uniqueName } from './ops'
import { Simulator } from './sim'
import type { CircuitNode, ComponentDef, Project, SymbolKind, Wire } from './types'
export const MAX_GATE_INPUTS = 16
/** The NAND primitive as a base, where a component id would go. */
export const NAND_BASE = 'nand'
/**
* How a two-input, one-output gate widens: "chain" when f(f(a,b),c) is
* f(a,f(b,c)) and f(0,0) = 0 (AND, OR, XOR); "inverted" when it is the
* NOT of such a gate and f(x,x) = NOT x (NAND, NOR); otherwise null.
*/
export type Family = 'chain' | 'inverted'
function table(get: DefLookup, base: string): number[] | null {
if (base === NAND_BASE) return [1, 1, 1, 0]
const def = get(base)
if (!def) return null
const pins = chipPins(def)
if (pins.inputs.length !== 2 || pins.outputs.length !== 1) return null
const nl = compile(get, base)
if (nl.errors.length || nl.clocks.length) return null
const sim = new Simulator(nl)
const out: number[] = []
for (let i = 0; i < 4; i++) {
sim.setSource(pins.inputs[0]!.key, (i & 2) !== 0)
sim.setSource(pins.inputs[1]!.key, (i & 1) !== 0)
if (!sim.run(200_000)) return null
out.push(sim.pin(pins.outputs[0]!.key, 'a'))
}
return out
}
const chains = (t: number[]) => {
const f = (a: number, b: number) => t[a * 2 + b]!
if (t[1] !== t[2] || t[0] !== 0) return false
for (let i = 0; i < 8; i++) {
const [a, b, c] = [(i >> 2) & 1, (i >> 1) & 1, i & 1]
if (f(f(a, b), c) !== f(a, f(b, c))) return false
}
return true
}
export function gateFamily(get: DefLookup, base: string): Family | null {
const t = table(get, base)
if (!t) return null
if (chains(t)) return 'chain'
if (t[0] === 1 && t[3] === 0 && chains(t.map(v => v ^ 1))) return 'inverted'
return null
}
/** The two-input gate behind a placed part: itself, or the gate its wide version is built from. */
export function baseOf(node: CircuitNode, get: DefLookup): string | null {
if (node.kind === 'nand') return NAND_BASE
if (node.kind !== 'chip' || !node.chip) return null
return get(node.chip)?.wide?.base ?? node.chip
}
/** Number of inputs of a placed gate. */
export function inputCount(node: CircuitNode, get: DefLookup): number {
if (node.kind === 'nand') return 2
const def = node.chip ? get(node.chip) : undefined
return def ? chipPins(def).inputs.length : 0
}
const LETTERS = 'ABCDEFGHIJKLMNOP'
/** Builds the wide version of a gate with `n` inputs. */
function buildWide(project: Project, base: string, n: number, family: Family): ComponentDef {
const get = lookup(project)
const baseDef = base === NAND_BASE ? undefined : get(base)
const pins = baseDef ? chipPins(baseDef) : { inputs: [{ key: 'a' }, { key: 'b' }], outputs: [{ key: 'q' }] }
const [inA, inB] = [pins.inputs[0]!.key, pins.inputs[1]!.key]
const out = pins.outputs[0]!.key
const nodes: CircuitNode[] = []
const wires: Wire[] = []
interface Sig {
node: string
pin: string
col: number
y: number
}
const gate = (a: Sig, b: Sig): Sig => {
const col = Math.max(a.col, b.col) + 1
const y = Math.round((a.y + b.y) / 2)
const id = uid('n')
nodes.push(base === NAND_BASE ? { id, kind: 'nand', x: col * 8, y } : { id, kind: 'chip', chip: base, x: col * 8, y })
wires.push({ id: uid('w'), from: { node: a.node, pin: a.pin }, to: { node: id, pin: inA } })
wires.push({ id: uid('w'), from: { node: b.node, pin: b.pin }, to: { node: id, pin: inB } })
return { node: id, pin: out, col, y }
}
// "Inverted" gates (NAND, NOR) make the plain one first: the gate, then the gate as a NOT.
const plain = (a: Sig, b: Sig): Sig => {
const g = gate(a, b)
return family === 'chain' ? g : gate(g, g)
}
const tree = (list: Sig[]): Sig => {
if (list.length === 1) return list[0]!
const mid = Math.ceil(list.length / 2)
return plain(tree(list.slice(0, mid)), tree(list.slice(mid)))
}
const ins: Sig[] = []
for (let i = 0; i < n; i++) {
const id = uid('n')
nodes.push({ id, kind: 'input', x: 0, y: i * 3, label: LETTERS[i]! })
ins.push({ node: id, pin: 'q', col: 0, y: i * 3 })
}
const mid = Math.ceil(n / 2)
const left = tree(ins.slice(0, mid))
const right = tree(ins.slice(mid))
// The root is the gate itself, so NAND and NOR stay inverted.
const root = gate(left, right)
const qid = uid('n')
nodes.push({ id: qid, kind: 'output', x: (root.col + 1) * 8, y: root.y, label: 'Q' })
wires.push({ id: uid('w'), from: { node: root.node, pin: root.pin }, to: { node: qid, pin: 'a' } })
const name = baseDef?.name ?? 'NAND'
const symbol: SymbolKind = baseDef?.symbol ?? 'nand'
return {
id: uid('c'),
name: uniqueName(project, `${name} ×${n}`),
symbol,
group: 'Wide gates',
description: `${name} with ${n} inputs, built from ${name} gates with two inputs.`,
wide: { base, n },
nodes,
wires,
}
}
/**
* The component to place for a gate with `n` inputs: the base itself for 2,
* otherwise its wide version, made now if the project has none yet.
* Returns null when the gate can't be widened.
*/
export function wideGate(project: Project, base: string, n: number): { kind: 'nand' } | { kind: 'chip'; chip: string } | null {
const get = lookup(project)
const family = gateFamily(get, base)
if (!family || n < 2 || n > MAX_GATE_INPUTS) return null
if (n === 2) return base === NAND_BASE ? { kind: 'nand' } : { kind: 'chip', chip: base }
const existing = project.components.find(d => d.wide?.base === base && d.wide.n === n)
if (existing) return { kind: 'chip', chip: existing.id }
const def = buildWide(project, base, n, family)
project.components.push(def)
return { kind: 'chip', chip: def.id }
}

120
tests/wide.test.ts Normal file
View File

@ -0,0 +1,120 @@
import { describe, expect, it } from 'vitest'
import { nandCounts, truthTable } from '../app/lib/logic/analyze'
import { compile } from '../app/lib/logic/compile'
import { shapeOf } from '../app/lib/logic/geometry'
import { createProject, lookup } from '../app/lib/logic/ops'
import { Simulator } from '../app/lib/logic/sim'
import type { ComponentDef } from '../app/lib/logic/types'
import { gateFamily, NAND_BASE, wideGate } from '../app/lib/logic/wide'
const FNS: Record<string, (bits: number[]) => number> = {
'ex-and': b => +b.every(Boolean),
'ex-or': b => +b.some(Boolean),
'ex-xor': b => b.reduce((x, y) => x ^ y, 0),
'ex-nor': b => +!b.some(Boolean),
[NAND_BASE]: b => +!b.every(Boolean),
}
describe('gates with more inputs', () => {
it('knows which gates can widen', () => {
const p = createProject({ examples: true })
const get = lookup(p)
expect(gateFamily(get, 'ex-and')).toBe('chain')
expect(gateFamily(get, 'ex-or')).toBe('chain')
expect(gateFamily(get, 'ex-xor')).toBe('chain')
expect(gateFamily(get, NAND_BASE)).toBe('inverted')
expect(gateFamily(get, 'ex-nor')).toBe('inverted')
expect(gateFamily(get, 'ex-xnor')).toBeNull()
expect(gateFamily(get, 'ex-mux')).toBeNull()
expect(gateFamily(get, 'ex-not')).toBeNull()
})
for (const [base, fn] of Object.entries(FNS)) {
it(`builds ${base} with 3 to 9 inputs that does the right thing`, () => {
const p = createProject({ examples: true })
for (const n of [3, 4, 5, 8, 9]) {
const target = wideGate(p, base, n)
if (target?.kind !== 'chip') throw new Error('no wide gate')
const t = truthTable(lookup(p), target.chip)
if ('error' in t) throw new Error(t.error)
expect(t.inputs).toHaveLength(n)
for (const r of t.rows) expect(r.outs[0], `${base} ×${n} ${r.ins.join('')}`).toBe(fn(r.ins))
}
})
}
it('counts honestly and reuses what it built', () => {
const p = createProject({ examples: true })
const counts = () => nandCounts(p.components)
const and4 = wideGate(p, 'ex-and', 4)!
expect(wideGate(p, 'ex-and', 4)).toEqual(and4)
if (and4.kind !== 'chip') throw new Error()
expect(counts().get(and4.chip)).toBe(3 * counts().get('ex-and')!)
// NAND with 3 inputs: an AND of two (NAND + NAND as NOT), then a NAND.
const nand3 = wideGate(p, NAND_BASE, 3)!
if (nand3.kind !== 'chip') throw new Error()
expect(counts().get(nand3.chip)).toBe(3)
expect(wideGate(p, 'ex-and', 2)).toEqual({ kind: 'chip', chip: 'ex-and' })
expect(wideGate(p, NAND_BASE, 2)).toEqual({ kind: 'nand' })
expect(wideGate(p, 'ex-and', 17)).toBeNull()
expect(wideGate(p, 'ex-xnor', 3)).toBeNull()
})
it('draws a wide AND as an AND symbol with all its pins', () => {
const p = createProject({ examples: true })
const t = wideGate(p, 'ex-and', 6)!
if (t.kind !== 'chip') throw new Error()
const s = shapeOf({ id: 'g', kind: 'chip', chip: t.chip, x: 0, y: 0 }, lookup(p))
expect(s.gate).toBe('and')
expect(s.inputs).toHaveLength(6)
})
})
describe('pass-through lamps and outputs', () => {
it('a lamp passes its signal on', () => {
const p = createProject({ examples: false })
const def: ComponentDef = {
id: 'r',
name: 'R',
symbol: 'box',
nodes: [
{ id: 's', kind: 'input', x: 0, y: 0 },
{ id: 'l1', kind: 'lamp', x: 5, y: 0 },
{ id: 'l2', kind: 'lamp', x: 10, y: 0 },
],
wires: [
{ id: 'w1', from: { node: 's', pin: 'q' }, to: { node: 'l1', pin: 'a' } },
{ id: 'w2', from: { node: 'l1', pin: 'q' }, to: { node: 'l2', pin: 'a' } },
],
}
p.components.push(def)
const sim = new Simulator(compile(lookup(p), 'r'))
sim.setSource('s', true)
sim.run()
expect([sim.pin('l1', 'a'), sim.pin('l1', 'q'), sim.pin('l2', 'a')]).toEqual([1, 1, 1])
})
it('an output pin inside a component also feeds parts after it', () => {
const p = createProject({ examples: true })
const inner: ComponentDef = {
id: 'in',
name: 'In',
symbol: 'box',
nodes: [
{ id: 'a', kind: 'input', x: 0, y: 0, label: 'A' },
{ id: 'q', kind: 'output', x: 6, y: 0, label: 'Q' },
{ id: 'not', kind: 'chip', chip: 'ex-not', x: 12, y: 0 },
{ id: 'nq', kind: 'output', x: 20, y: 0, label: 'NQ' },
],
wires: [
{ id: 'w1', from: { node: 'a', pin: 'q' }, to: { node: 'q', pin: 'a' } },
{ id: 'w2', from: { node: 'q', pin: 'q' }, to: { node: 'not', pin: p.components.find(d => d.id === 'ex-not')!.nodes.find(n => n.kind === 'input')!.id } },
{ id: 'w3', from: { node: 'not', pin: p.components.find(d => d.id === 'ex-not')!.nodes.find(n => n.kind === 'output')!.id }, to: { node: 'nq', pin: 'a' } },
],
}
p.components.push(inner)
const t = truthTable(lookup(p), 'in')
if ('error' in t) throw new Error(t.error)
expect(t.rows.map(r => r.outs.join(''))).toEqual(['01', '10'])
})
})