# z80-wasm The [z80-rust-fast](https://github.com/alewman/z80-rust-fast) Z80 core compiled to WebAssembly, certified in the browser against the committed conformance traces before it plays anything, then Galaxian on a board transcribed from [galemu](https://github.com/alewman/galemu) and proven against it. Live at **https://galaxian.supertux.com**. The brief is `docs/handoff-brief.md`; what happened when it ran is `docs/build-record.md`. Where it stands (2026-09-08): all seven milestones done. On load the page runs thirteen conformance manifests through the wasm core and shows every one identical to the reference; ZEXALL completes there with the exact native totals in 33.6 s (native 16.8 s); the Galaxian board reproduces galemu's canonical trace byte for byte over six runs and its sound sample for sample over two, natively and through the wasm; a visitor's own verified ROM set plays with keyboard, gamepad or touch, with sound. This crate is a *host* of z80-rust-fast: it depends on the core by git tag and compiles against it unchanged (`use z80_rust::...`). Nothing in the core is modified here. ## Pins | What | Value | | --- | --- | | z80-rust-fast | tag `v0.1.0` = `85fb856` (`Cargo.toml`) | | z80-python, whose certification the core's rests on | `cab1598` | | Trace schema | version 1 | | galemu, the board's oracle | `fa5f935` (its venv runs the local z80-python `d1ec9c7`, core = `cab1598`) | | rustc | 1.93.1 (`rust-toolchain.toml`), the compiler the core's i9 numbers used | | wasm-bindgen | 0.2.128, crate and CLI | | wasm-opt | binaryen version_132 | ## Where it stands **Milestone 1 (done).** The core builds for `wasm32-unknown-unknown`; one export, `check_manifest(manifest_json, reference_jsonl)`, runs a conformance manifest through the crate's own conformance host and compares every record with the reference trace, ignoring only the `mnemonic` and `operands` text an external producer omits, exactly as z80-rust-fast's `tests/rung1.rs` does. The thirteen manifests under `conformance/` (rung 1: three example manifests; rung 5: ten interrupt scenarios; copied byte for byte from z80-python `cab1598`, see `conformance/README.md`) are identical to their references: - natively, `cargo test --release` (`tests/rungs.rs`), through the same function the export calls; - under Node 22, `node web/check.mjs`, through the wasm export itself. CI runs both on every push. `.wasm` size at this commit: 237,916 bytes as built (`opt-level = 3`, fat LTO, one codegen unit, `panic = "abort"`), 194,403 bytes after `wasm-opt -Oz`. **Milestone 2 (done).** The page, `web/index.html` + `app.js`, runs the thirteen on load and renders the table (rung, manifest, records produced / expected, stop reason, result); the sections below it stay hidden until every row is identical. `scripts/build-dist.sh` assembles a self-contained `dist/` (page, wasm, the manifests and traces, `conformance/index.json`, `version.json` with the commit). `scripts/check-page.sh` serves `dist/` and renders it in headless Chromium, requiring 13 identical rows and the page's own "13 of 13" summary; CI runs it in the runner's Chrome and uploads `dist/` as an artifact. Live at **https://galaxian.supertux.com** (`scripts/deploy.sh`, see "Deploying"); the live page renders the same 13 rows. **Milestone 3 (done).** "Run ZEXALL" on the page runs Frank Cringle's exerciser to completion in a Web Worker on the same core, streaming its console output and reporting the five numbers `z80-bench` prints. The worker calls `Runner` (`src/runner.rs`), `z80-bench`'s loop made resumable in slices of 25 M instructions; the manifest is z80-rust-fast's `conformance/zex/zexall.json` with its `file` segment inlined (`inline_files`). `zexall.com` (GPL-2.0) is not committed (it was until 2026-11-26 and is still in history; see `docs/provenance.md`): `scripts/fetch_zexall.sh` takes it from a fixed commit of [agn453/ZEXALL](https://github.com/agn453/ZEXALL) into the git-ignored `external/` and verifies the SHA-256 z80-python and z80-rust-fast pin; `tests/runner.rs` skips without it; `build-dist.sh` fetches it and puts it under `dist/zex/`. Timing covers the run calls only, one core, nothing else running: | Where | Time | Instructions/s | Equivalent Z80 | | --- | --- | --- | --- | | native, `z80-bench`, i9-13900K (z80-rust-fast v0.1.0, rustc 1.93.1) | 16.8 s | 343.8 M | 2.78 GHz | | wasm under Node 22.19 (V8 12.4), `node web/zex.mjs`, pinned to CPU 4 | 32.08 s | 179.7 M | 1.46 GHz | | wasm in headless Chromium 141 through the page, `node web/zex-browser.mjs` | 33.63 s | 171.4 M | 1.39 GHz | | Firefox | not measured: no Firefox on the build machine | | | Every run stopped on `cpm_exit` with exactly 5,764,169,474 instructions and 46,734,975,782 T-states, all 67 tests OK, "Tests complete". That is the consistency check the core's second-machine record describes, not a rung. So the wasm build runs at about half native speed: a 1.4 GHz Z80. `.wasm` size at this commit: 246,246 bytes built, 198,974 after `wasm-opt -Oz`. CI runs the first 200 M instructions through the Runner under Node as a smoke test; the full run is a local measurement. **Milestone 4 (done).** Galaxian runs on the page, on a board transcribed from [galemu](https://github.com/alewman/galemu) (`fa5f935`) and proven against it. galemu is the oracle for the board as z80-python is for the CPU: it is deterministic and serializes a run as canonical JSON (typed events plus a snapshot with the CPU registers and all three RAMs). The Rust board produces the same JSON, byte for byte, for six recorded runs (`oracle/runs.json`, references under `oracle/reference/` generated by `oracle/make_references.sh` from galemu's own `GalaxianBoard` through `oracle/galemu_run.py`): | Run | What | Reference | | --- | --- | --- | | `headless-5000` | galemu's default headless run, every RAM write recorded | 163 KB | | `vblank-20000-writes` | boot with the vblank NMI, every RAM write recorded | 345 KB | | `attract-1s` | 600,000 boundaries, device writes and NMI boundaries only | 7 KB | | `attract-5s` | 303 frames of attract mode | 168 KB | | `attract-30s` | 1,818 frames of attract mode | 1.6 MB | | `game-20s` | coin at frame 120, start at 200, moves and shots at stated frames | 1.1 MB | All six are identical natively (`tests/galaxian.rs`) and through the wasm board under Node (`web/board-check.mjs`, 30 s of game in 114 ms). Both need the extracted set at `rom/galaxian/` and skip without it, so CI does not run them: the ROMs never leave this machine. The reference runs contain no ROM bytes (events and RAM contents only) and are committed. The transcription: `src/galaxian/board.rs` (memory map with its mirrors, inputs, latches, the 50,688-T-state frame with vblank at 43,008, the event and snapshot records), `roms.rs` (the manifest: size, CRC32, SHA-1 of all eight files, checked before a byte reaches the bus), `video.rs` (palette and star-palette decode, tiles, sprites, the 17-bit LFSR starfield, and composition in galemu's layer order with the sprite edge clip and the one-shell-per-scanline arbitration), `trace.rs` (galemu's canonical JSON). One thing galemu gets for free that this board cannot: galemu's board *is* its CPU, so an event carries the PC at the moment of the write, while here the CPU owns the bus. `Machine::step` stamps each step's events afterwards with the pre-step PC plus the bytes the instruction fetched (a Z80 writes only after its last fetch), or the pre-step PC for an NMI acceptance, which pushes before it jumps. The six runs, 1.1 million events with PCs, agree. The set can also be fetched by the visitor's browser from a URL they give (a field next to the file picker, or `?rom=` in the page's address, which fetches on load and is the easy way onto a phone). The fetch is cross-origin, so the host must send CORS headers; archive.org does on its `/cors/` path and not on `/download/`, and the page rewrites the latter to the former. This site never sees or serves the file either way; the verification is the same as for a picked file. On the page: the visitor's `galaxian.zip` is unzipped in the browser (`web/unzip.js`, `DecompressionStream`), each file verified in Rust, the board runs one frame per display frame with galemu's catch-up rule (at most four frames per tick), and the frame is composed in Rust and rotated for the portrait monitor. Keyboard: 5 coin, 1 start, arrows, space. The game runs on the main thread, not in the worker the brief expected: a frame is about 10,000 instructions, under 0.1 ms here, so a worker would add input latency and frame copies for no responsiveness gain. Headless Chromium reports 60.0 frames/s emulated against the board's 60.61 (the display is 60 Hz; the catch-up rule makes up the difference) and keeping up; `web/game-browser.mjs` drives the whole thing over the DevTools protocol, feeds the zip to the file input, inserts a coin, starts a game, plays with key events, and screenshots. The NMI path the board uses is the one rung 5 certifies: `nmi-accept-while-running` and `nmi-accept-from-halt`. `.wasm` size at this commit: 413,550 bytes built, 342,509 after `wasm-opt -Oz` (the board and the compositor add 144 KB). **Milestone 5 (done).** The demo: any standard-mapping gamepad works without setup (polled each tick; Select inserts a coin, Start starts, held a second it starts two players, D-pad or stick moves, A fires, R1 pauses), keyboard as before plus P to pause, on-screen touch buttons on coarse pointers, a Pause and a Mute button, a controls table, and a "What this page is" panel: how to obtain the ROM set and what is checked, what the certification table means and the four repositories it rests on, what ZEXALL is. The canvas keeps its 224:256 aspect and fits phone widths. `web/demo-browser.mjs` checks it in headless Chromium: the ROM loads, a simulated standard gamepad's coin and start begin a game (screenshot), P pauses and resumes, and at 390 px with touch emulation the touch controls are shown and the page does not overflow. **Phones, rewind, unmapped pads (2026-11-13).** On a coarse pointer the running game takes the screen (a play view; its cross docks it back into the page): a stick on the left (left and right only; a thumb that lands on it steers wherever it slides until lifted), FIRE on the right, Start and Coin between. On its side the picture takes the full height with the controls beside it. Rewind: hold Backspace, a controller's left trigger, or the bar's button; `Machine::capture`/`restore` (the core's `capture_state`/`restore_state`, the three RAMs, latches, counters and the vblank scheduler, with the sound state) are kept every 4 frames, about a minute at ~2.5 KB each, and each held frame restores the newest. `tests/rewind.rs` proves a restore continues as the uninterrupted run, 600 frames of play identical in picture, sound, RAM and counters. A pad without the standard mapping (Firefox on Windows with a Switch Pro) has its d-pad read from its hat-switch axis. `web/check-touch.mjs` checks the stick and buttons in portrait and on its side and rewinds by touch; `web/game-browser.mjs` rewinds with Backspace. **The family's controls (2026-11-23).** The scheme of emulator-lineage `docs/proposals/2026-11-play-controls.md`, through `web/controls.js` (a copy of play-nes's, its second line naming the play-nes commit; play-nes's `scripts/controls-drift.sh` checks it). The play view's bar has a pause button (the page's Pause is outside it); Start and Coin sit top-left on a phone on its side. Keyboard: ← → or A D move, Space, Z or X fire, Enter or 1 start (2 for two players), Shift, 5 or C coin, P or Pause pause, R or Backspace (held) rewind, F9 sound. A controller: any face button fires, the right shoulder or the right stick pressed (R3) pauses. Volume, mute and haptics (a buzz on each touch press, Android only, off at first) are kept on the device as `z80-wasm-settings`. `web/game-browser.mjs` checks the keys, the play view's pause, the remembered settings and a faked controller; `web/check-touch.mjs` the pause under a finger, haptics and the corner the pills sit in. **Save states (2026-11-23).** F5 saves the game, F7 loads it (keys only, as emu-galaga), kept on the device in IndexedDB (database `z80-wasm`, store `files`, key `saved`; one state). The state is rewind's snapshot in bytes: `Snapshot::to_bytes` / `from_bytes` (`src/galaxian/mod.rs`) write every field of `MachineState` (`board.rs`: the CPU's `CpuState` fields in their order, the three RAMs, latches, counters, the vblank scheduler) and `SoundState` (`sound.rs`, its `f64`s by their bits) in declaration order through `src/galaxian/bytes.rs`; the board's behaviour is not touched (the change only adds code). `Galaxian::save_state` in `src/bindings.rs` puts `GALAXIAN` and the format's version (1, u32) in front, 2,546 bytes in all; `load_state` refuses, with the game untouched, bytes that are not a Galaxian state, a state of another version ("a save state of version 2, not 1"), one cut short or with bytes left over, or a yes-or-no byte that is neither. A change to what a snapshot holds must raise the version. Proved by `tests/save_state.rs` (natively) and `web/state-check.mjs` (through the wasm): a state saved at frame 600 in attract mode and at frame 1000 in play, loaded into a fresh board, saves the same bytes back and runs 3,000 frames identical to the uninterrupted run (picture, sound, the three RAMs, counters); seeded faults (two sound fields swapped in the reader; the vblank scheduler left out of both writer and reader) were each caught. `web/game-browser.mjs` checks F5 and F7 in the page and a state of another version refused while the game runs on. **Milestone 6 (done).** Sound. galemu's `synth.py` is a deterministic signal-level model of the discrete board (the resistor-DAC-driven 555 drone with its three tone generators, the pitch divider, the 17-bit noise LFSR, the FIRE and HIT stages), 792 samples per frame at 48 kHz. `src/galaxian/sound.rs` transcribes it in the same arithmetic order. `oracle/galemu_sound.py` runs galemu's board and synthesizer for the frame-driven runs and writes the PCM; the Rust board's PCM for the same runs is compared sample for sample: | Run | Samples | Differing, native (`tests/sound.rs`) | Differing, wasm under Node (`web/sound-check.mjs`) | | --- | --- | --- | --- | | `attract-5s` | 239,976 | 0 | 0 | | `game-20s` | 959,904 | 0 | 0 | Identical even through wasm's own `ln`/`exp`, which was not guaranteed (the check allows 2 LSB and reports the largest difference). On the page an `AudioWorklet` (`web/audio-worklet.js`) plays a bounded FIFO of frames with galemu's rules: start with two chunks of margin, drop stale frames, never steer game time; contexts not at 48 kHz are resampled linearly. The context is created on the ROM file selection, a user gesture, so autoplay policy allows it. Rungs that do not run in the browser, and why: 2 is 1,604,000 vectors of data; 3 is nine hours per exerciser against PyPy; 4 and 6 need their suites fetched. They are the core's rungs and pass in z80-rust-fast at the pinned tag. ## Building ``` scripts/build-wasm.sh # -> web/pkg/z80_wasm.js, z80_wasm_bg.wasm (wasm-opt'd), sizes node web/check.mjs # the thirteen manifests through the wasm cargo test --release # the same thirteen natively, plus the Runner tests scripts/fetch_zexall.sh # zexall.com into external/, SHA-256 verified node web/zex.mjs # all of ZEXALL under Node: z80-bench's line scripts/build-dist.sh # -> dist/ scripts/check-page.sh # dist/ in headless Chromium: 13 green rows node web/zex-browser.mjs # ZEXALL through the page in headless Chromium, timed unzip rom/galaxian.zip -d rom/galaxian # the ROM set, never committed oracle/make_references.sh # galemu's reference runs (needs galemu's venv) node web/board-check.mjs # the six runs through the wasm board node web/game-browser.mjs # the game in headless Chromium, with screenshots node web/demo-browser.mjs # gamepad, pause, phone layout in headless Chromium ROMS=rom/galaxian.zip node web/check-touch.mjs # the stick, FIRE, landscape, rewind by touch node web/sound-check.mjs # the PCM of the frame runs against galemu's node web/state-check.mjs # save states through the wasm: round trips, refusals ``` `scripts/build-wasm.sh` needs `wasm-bindgen` 0.2.128 (`cargo install wasm-bindgen-cli --version 0.2.128 --locked`) and `wasm-opt` (a binaryen release under `~/.local/binaryen`, or on `PATH`). On this machine rustup is a snap and `rustup run` leaves the system rustc first on `PATH`, so the script calls the `rust-toolchain.toml` toolchain's own `cargo` and `rustc` directly; `CARGO=cargo scripts/build-wasm.sh` uses whatever is on `PATH`. ## Deploying `galaxian.supertux.com` is served by this machine's docker stack: an `nginx:alpine` container (`deploy/galaxian.yml`, a copy of the stack's `galaga.yml` with the name changed) serving `/docker/appdata/galaxian` read-only behind Traefik with the public `chain-no-auth` middleware. `scripts/deploy.sh` builds `dist/`, rsyncs it there, installs the compose file into `/docker/compose/apps/` if it changed, brings the container up if it is not running, and curls the page, the wasm (must be `application/wasm`; nginx's default types include it) and `version.json`. nginx serves new files without a restart. No cross-origin isolation headers are set: nothing uses `SharedArrayBuffer` yet. ## Layout - `src/check.rs`: the comparison. `src/bindings.rs`: the wasm-bindgen surface (`check_manifest`, `build_info`). `tests/rungs.rs`: rungs 1 and 5 natively, plus a test that a corrupted reference is reported at its index. - `conformance/rung1`, `conformance/rung5`: manifests and reference traces. - `src/runner.rs`: the resumable `z80-bench` loop; `tests/runner.rs`. - `src/galaxian/`: the board (`board.rs`, `roms.rs`, `video.rs`, `trace.rs`, `sound.rs`); `tests/galaxian.rs`, `tests/sound.rs`. `oracle/`: the galemu drivers, the run list, the reference runs and PCM. - `web/index.html`, `style.css`, `app.js`, `zex-worker.js`, `unzip.js`, `audio-worklet.js`: the page. `web/check.mjs`, `zex.mjs`, `zex-browser.mjs`, `board-check.mjs`, `game-browser.mjs`, `demo-browser.mjs`, `sound-check.mjs`: the Node checks. `web/pkg/`, `dist/`, `external/`: build output and fetched inputs, not committed. - `deploy/galaxian.yml`: the compose service. `scripts/`: `build-wasm.sh`, `build-dist.sh`, `check-page.sh`, `deploy.sh`.