diff options
| author | gbc dev <gbc@localhost> | 2026-09-22 15:57:06 +0200 |
|---|---|---|
| committer | gbc dev <gbc@localhost> | 2026-09-22 15:57:06 +0200 |
| commit | 6fb4fbbce99c08bd535d1b7e0f356864fb0c38a0 (patch) | |
| tree | 7f0b249f4cfe640d80a7848d9012dc695d42d5c3 | |
| parent | core: make the machine loadable without a filesystem (diff) | |
| download | sl0pboy-6fb4fbbce99c08bd535d1b7e0f356864fb0c38a0.tar.gz sl0pboy-6fb4fbbce99c08bd535d1b7e0f356864fb0c38a0.tar.xz sl0pboy-6fb4fbbce99c08bd535d1b7e0f356864fb0c38a0.zip | |
wasm: run the emulator in a browser
`make wasm` builds the core to WebAssembly (~44KB stripped) and web/ is a
front-end for it: drag-drop a ROM, pixelated canvas at any zoom, keyboard
mapped like the native build, battery saves in localStorage.
Built with zig cc, which carries its own wasm backend, linker and
wasi-libc - so no emscripten dependency, just zig on PATH. Only the
portable core goes in; render/kitty/control/main are terminal- and
POSIX-bound and stay out. src/wasm.c is the browser's whole host layer:
no terminal, no sockets, no files, and no frame pacing (the page's
requestAnimationFrame owns that). The machine is static, the RGB888 ->
RGBA conversion for putImageData happens in wasm, and nothing allocates
per frame.
The entire host interface is four WASI fd_* imports, pulled in by the
cart info banner's fprintf; the page shims them to console.log in ~20
lines. Cartridge RAM *is* the save file here, so it's exported for the
page to persist per cart title (every 5s and on unload).
Because both builds now advance on the same frame boundary, the port is
checked byte-for-byte against the native binary rather than by eyeballing
a canvas - tools/wasm_check.mjs runs N frames in node and diffs the
framebuffer against a --shot PPM:
cgb-acid2 @60, dmg-acid2 @60, cpu_instrs @600, mem_timing-2 @700,
pky.gbc @400 with an imported .sav, cgb-acid2 @120 through the full
CGB BIOS boot animation -> all pixel-identical
Also smoke-tested in headless chromium over CDP: core instantiates, ROM
loads through the file input, canvas animates (7 distinct frames over
5.6s), keyboard reaches the joypad, 60fps, and a 32KB save lands in
localStorage.
No audio: the APU is still stubbed.
| -rw-r--r-- | .gitignore | 3 | ||||
| -rw-r--r-- | Makefile | 26 | ||||
| -rw-r--r-- | README.md | 61 | ||||
| -rw-r--r-- | src/wasm.c | 126 | ||||
| -rwxr-xr-x | tools/wasm_check.mjs | 137 | ||||
| -rw-r--r-- | web/index.html | 231 |
6 files changed, 581 insertions, 3 deletions
@@ -1,5 +1,8 @@ /build/ *.o + +# built by `make wasm` +/web/*.wasm *.gb *.gbc *.sav @@ -3,14 +3,34 @@ CFLAGS := -std=c11 -O2 -Wall -Wextra -Wno-unused-parameter -g -D_POSIX_C_SOURCE LDFLAGS := SRCDIR := src BUILD := build -SRCS := $(wildcard $(SRCDIR)/*.c) +# The native binary is every .c except the wasm host layer. +SRCS := $(filter-out $(SRCDIR)/wasm.c,$(wildcard $(SRCDIR)/*.c)) OBJS := $(patsubst $(SRCDIR)/%.c,$(BUILD)/%.o,$(SRCS)) BIN := $(BUILD)/sl0pboy -.PHONY: all clean run +# ---- wasm ---- +# Only the portable core plus the wasm host layer: render/kitty/control/main +# are terminal-and-POSIX bound and have no meaning in a browser. +# zig cc carries its own wasm backend, linker and wasi-libc, so there is no +# emscripten dependency. Reactor model = no main(), exports stay callable. +WASM_SRCS := $(addprefix $(SRCDIR)/,cpu.c ppu.c timer.c gb.c cart.c wasm.c) +WASM_OUT := web/sl0pboy.wasm +WASM_CC := zig cc +WASM_FLAGS := -target wasm32-wasi -mexec-model=reactor -O2 -std=c11 \ + -Wall -Wextra -Wno-unused-parameter \ + -Wl,--no-entry -Wl,--export-dynamic -Wl,--strip-all + +.PHONY: all clean run wasm all: $(BIN) +wasm: $(WASM_OUT) + +$(WASM_OUT): $(WASM_SRCS) $(wildcard $(SRCDIR)/*.h) + @mkdir -p $(dir $@) + $(WASM_CC) $(WASM_FLAGS) $(WASM_SRCS) -o $@ + @echo "built $@ ($$(du -h $@ | cut -f1))" + $(BIN): $(OBJS) $(CC) $(CFLAGS) $(OBJS) -o $@ $(LDFLAGS) @@ -21,7 +41,7 @@ $(BUILD): mkdir -p $(BUILD) clean: - rm -rf $(BUILD) + rm -rf $(BUILD) $(WASM_OUT) run: $(BIN) $(BIN) $(ROM) @@ -413,6 +413,65 @@ Socket auto-resolves to the single live instance. Run `./gbctl` bare for the full command list. Driven end-to-end by the `gbc-driver` skill. +## In the browser (`make wasm`) + +The same core, compiled to WebAssembly, so anyone can try a ROM without +building anything: + +```sh +make wasm # -> web/sl0pboy.wasm (~44KB) +cd web && python3 -m http.server 8000 +# open http://localhost:8000 and drop in a .gb/.gbc +``` + +Built with `zig cc` (no emscripten): it carries its own wasm backend, linker +and wasi-libc, so `make wasm` needs nothing but zig on PATH. Only the portable +core compiles in — `render.c`, `kitty.c`, `control.c` and `main.c` are terminal- +and POSIX-bound and are left out; `src/wasm.c` is the browser's host layer +instead. It's a *reactor* module, so the page calls `_initialize()` and then +drives the exports directly: + +| export | does what | +| --- | --- | +| `gbw_alloc` / `gbw_free` | staging buffer for handing a ROM to wasm | +| `gbw_load(ptr,len)` | parse cart + reset (0 = ok) | +| `gbw_load_bootrom(ptr,len)` | boot through a real BIOS, logo and all | +| `gbw_run_frame()` | advance exactly one frame | +| `gbw_set_buttons(mask)` | `BTN_*` bits; browsers report key-release, so this is the true live state | +| `gbw_framebuffer_rgba()` | 160×144×4, straight into `putImageData` | +| `gbw_framebuffer_rgb()` | the raw PPU buffer, same bytes `--shot` writes | +| `gbw_sram_ptr/_size/_load` | cartridge RAM — *is* the save file here | + +The whole host interface is **four WASI `fd_*` imports** (stdio, from the cart +info banner), shimmed in ~20 lines of JS; the page routes them to the devtools +console. No filesystem, no sockets, no WASI runtime needed. + +`web/index.html` is the front-end: drag-drop a ROM, pixelated canvas at any +zoom, keyboard mapped like the native build, and battery saves persisted to +`localStorage` per cart title (autosaved every 5s and on unload). Frame pacing +is an accumulator against 59.7275Hz with capped catch-up, so a backgrounded tab +skips ahead instead of running hundreds of frames in one burst. + +No audio — the APU is still stubbed (see below). + +### Proving it's the same emulator + +Both builds advance on the identical frame boundary (`gb_run_frame` in `gb.c`), +so the wasm core can be checked against the native one **byte for byte** rather +than by eyeballing a canvas: + +```sh +./build/sl0pboy --shot 60 /tmp/ref.ppm roms/cgb-acid2.gbc +node tools/wasm_check.mjs roms/cgb-acid2.gbc 60 --check /tmp/ref.ppm +# OK: wasm frame 60 matches /tmp/ref.ppm exactly (160x144) +``` + +Any mismatch is a real portability bug (struct layout, endianness, UB the two +backends resolved differently), not a rendering difference. Currently exact on +cgb-acid2, dmg-acid2, 600 frames of `cpu_instrs`, MBC5 + battery with an +imported `.sav`, and a full CGB BIOS boot animation. `--sram` / `--bios` / +`-o out.ppm` are supported too. + ## Architecture | File | Does what | @@ -427,6 +486,8 @@ Run `./gbctl` bare for the full command list. Driven end-to-end by the | `src/kitty.c` | kitty graphics protocol: shm/base64 transfer, tmux wrap | | `src/control.c` | socket control/debug: memory, CPU, step, breakpoints | | `src/main.c` | arg parsing, frame loop, timing, screenshot/test modes | +| `src/wasm.c` | browser host layer: exports the core to JS (wasm build) | +| `web/index.html`| the browser front-end (canvas, input, localStorage saves) | ## Emulation status diff --git a/src/wasm.c b/src/wasm.c new file mode 100644 index 0000000..e1051a1 --- /dev/null +++ b/src/wasm.c @@ -0,0 +1,126 @@ +// ---- wasm entry point: the browser's "main" ------------------------------- +// +// The native build has render.c / kitty.c / control.c / main.c wrapped around +// the core; a browser has none of that. This file is the whole host layer for +// the wasm target: no terminal, no sockets, no files, no frame pacing (the +// page's requestAnimationFrame owns that). It just exposes the core as a +// handful of C functions the page can call, plus two buffers it can read. +// +// The contract, in the order a page uses it: +// _initialize() once, libc + ctors (wasi reactor model) +// p = gbw_alloc(len) get a staging buffer for the ROM bytes +// gbw_load(p, len) parse cart + reset (0 = ok) +// gbw_free(p) staging buffer is no longer needed +// gbw_set_buttons(mask) BTN_* bits, 1 = pressed +// gbw_run_frame() advance exactly one frame +// gbw_framebuffer_rgba() 160*144*4 bytes, ready for putImageData +// +// Everything hands back a pointer into the wasm linear memory; the page reads +// it through a typed array view. Nothing here allocates per frame. + +#include "gb.h" +#include "cart.h" +#include <stdlib.h> +#include <string.h> + +#define EXPORT(name) __attribute__((export_name(#name))) name + +// One machine, statically allocated: a GB is ~120KB of arrays, and keeping it +// out of the heap means the ROM upload is the only thing that ever mallocs. +static GB gb; +static bool loaded = false; + +// The PPU draws RGB888, but canvas ImageData wants RGBA8888. Converting here +// costs one pass over 23k pixels in wasm instead of a per-pixel loop in JS. +static u8 fb_rgba[SCREEN_H * SCREEN_W * 4]; + +// ---- memory handoff ------------------------------------------------------- +// The page can't write into wasm memory without somewhere to put things. +void *EXPORT(gbw_alloc)(int n) { return malloc((size_t)n); } +void EXPORT(gbw_free)(void *p) { free(p); } + +// ---- lifecycle ------------------------------------------------------------ + +// Parse a ROM image and reset the machine. Returns 0 on success. +// Safe to call again to swap games; the old cart is released first. +int EXPORT(gbw_load)(const u8 *rom, int len) { + if (loaded) { + cart_free(&gb.cart); // no-op battery save in this build + loaded = false; + } + Cart c; + if (cart_load_mem(&c, rom, (size_t)len) != 0) return -1; + gb_init(&gb); // zeroes the machine, keeps any boot ROM + gb.cart = c; // install the cart, then boot into it + gb_reset(&gb); + loaded = true; + return 0; +} + +// Install a boot ROM (256B DMG / 2304B CGB) so the next load boots through the +// power-on animation. Must be called before gbw_load. Returns 0 on success. +int EXPORT(gbw_load_bootrom)(const u8 *data, int len) { + return gb_load_bootrom_mem(&gb, data, len); +} + +void EXPORT(gbw_reset)(void) { + if (loaded) gb_reset(&gb); +} + +int EXPORT(gbw_is_loaded)(void) { return loaded ? 1 : 0; } + +// ---- running -------------------------------------------------------------- + +// Advance exactly one frame (to the next VBlank). The page calls this from +// requestAnimationFrame; the emulator itself does no timing. +void EXPORT(gbw_run_frame)(void) { + if (loaded) gb_run_frame(&gb); +} + +// Pressed-button bitmask (BTN_A | BTN_LEFT | ...), 1 = pressed. Unlike the +// terminal, a browser reports key-release, so this is just the live state. +void EXPORT(gbw_set_buttons)(int mask) { gb.buttons = (u8)mask; } + +// ---- reading the screen --------------------------------------------------- + +// Convert the PPU framebuffer to RGBA and return it. 160*144*4 bytes. +const u8 *EXPORT(gbw_framebuffer_rgba)(void) { + const u8 *src = &gb.ppu.fb[0][0][0]; + u8 *dst = fb_rgba; + for (int i = 0; i < SCREEN_W * SCREEN_H; i++) { + *dst++ = *src++; + *dst++ = *src++; + *dst++ = *src++; + *dst++ = 0xFF; + } + return fb_rgba; +} + +// Raw RGB888 straight out of the PPU (160*144*3) - what --shot writes, so the +// golden-frame test can compare it byte for byte against a native PPM. +const u8 *EXPORT(gbw_framebuffer_rgb)(void) { return &gb.ppu.fb[0][0][0]; } + +int EXPORT(gbw_screen_w)(void) { return SCREEN_W; } +int EXPORT(gbw_screen_h)(void) { return SCREEN_H; } + +// ---- cart info & battery saves -------------------------------------------- + +const char *EXPORT(gbw_title)(void) { return gb.cart.title; } +int EXPORT(gbw_is_cgb)(void) { return gb.cart.cgb ? 1 : 0; } +int EXPORT(gbw_has_battery)(void) { return gb.cart.has_battery ? 1 : 0; } + +// Cartridge RAM, for the page to persist (IndexedDB/localStorage) and restore. +// There is no .sav file in a browser, so this *is* the save. +u8 *EXPORT(gbw_sram_ptr)(void) { return gb.cart.ram; } +int EXPORT(gbw_sram_size)(void) { return (int)gb.cart.ram_size; } + +// Overwrite cartridge RAM from a previously saved blob. Returns bytes copied; +// a size mismatch copies nothing (wrong game, or a different MBC layout). +int EXPORT(gbw_sram_load)(const u8 *data, int len) { + if (!gb.cart.ram || (size_t)len != gb.cart.ram_size) return 0; + memcpy(gb.cart.ram, data, (size_t)len); + return len; +} + +// Total T-cycles since power-on; handy for pacing checks and debugging. +double EXPORT(gbw_cycles)(void) { return (double)gb.cycles; } diff --git a/tools/wasm_check.mjs b/tools/wasm_check.mjs new file mode 100755 index 0000000..a9260fb --- /dev/null +++ b/tools/wasm_check.mjs @@ -0,0 +1,137 @@ +#!/usr/bin/env node +// Golden-frame test for the wasm build. +// +// The point: prove the browser core is the *same emulator* as the native one, +// not "looks about right". It runs a ROM for N frames in wasm and compares the +// framebuffer byte-for-byte against a PPM written by the native binary: +// +// ./build/sl0pboy --shot 60 /tmp/n.ppm roms/cgb-acid2.gbc +// node tools/wasm_check.mjs roms/cgb-acid2.gbc 60 --check /tmp/n.ppm +// +// Both sides run the identical loop (gb_run_frame in gb.c), so any mismatch is +// a real portability bug - endianness, struct layout, UB the two backends +// resolved differently - and not a rendering difference. +// +// Also doubles as a PPM dumper: ... 60 -o /tmp/w.ppm +import { readFileSync, writeFileSync } from "node:fs"; + +const argv = process.argv.slice(2); +if (argv.length < 1) { + console.error("usage: wasm_check.mjs <rom> [frames] [--check ref.ppm] [-o out.ppm]"); + console.error(" [--wasm path] [--sram file] [--bios file]"); + process.exit(2); +} +const romPath = argv[0]; +const frames = argv[1] && !argv[1].startsWith("-") ? parseInt(argv[1], 10) : 60; +const flag = (n) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : null; }; +const checkPath = flag("--check"); +const outPath = flag("-o"); +const wasmPath = flag("--wasm") || new URL("../web/sl0pboy.wasm", import.meta.url).pathname; +const sramPath = flag("--sram"); +const biosPath = flag("--bios"); + +// ---- the entire WASI surface this module uses ---------------------------- +// Four fd_* imports, pulled in by the diagnostic fprintf(stderr) in cart.c. +// stdout/stderr go to the console; everything else is a closed file. +const WASI_EBADF = 8; +let memory; +const text = new TextDecoder(); +const wasi = { + fd_write(fd, iovs, iovsLen, nwritten) { + const view = new DataView(memory.buffer); + let written = 0, out = []; + for (let i = 0; i < iovsLen; i++) { + const ptr = view.getUint32(iovs + i * 8, true); + const len = view.getUint32(iovs + i * 8 + 4, true); + out.push(new Uint8Array(memory.buffer, ptr, len)); + written += len; + } + const blob = Buffer.concat(out.map(Buffer.from)); + if (fd === 1 || fd === 2) process.stderr.write(text.decode(blob)); + view.setUint32(nwritten, written, true); + return 0; + }, + fd_read: () => WASI_EBADF, + fd_seek: () => WASI_EBADF, + fd_close: () => WASI_EBADF, +}; + +const bytes = readFileSync(wasmPath); +const { instance } = await WebAssembly.instantiate(bytes, { + wasi_snapshot_preview1: wasi, +}); +const ex = instance.exports; +memory = ex.memory; +ex._initialize(); // reactor model: libc + ctors before anything else + +// Copy a Buffer into wasm linear memory, returning [ptr, len] to free later. +const intoWasm = (buf) => { + const ptr = ex.gbw_alloc(buf.length); + if (!ptr) throw new Error("gbw_alloc failed"); + new Uint8Array(memory.buffer, ptr, buf.length).set(buf); + return ptr; +}; + +if (biosPath) { + const b = readFileSync(biosPath); + const p = intoWasm(b); + if (ex.gbw_load_bootrom(p, b.length) !== 0) throw new Error("bootrom rejected"); + ex.gbw_free(p); +} + +const rom = readFileSync(romPath); +const romPtr = intoWasm(rom); +if (ex.gbw_load(romPtr, rom.length) !== 0) throw new Error("gbw_load failed"); +ex.gbw_free(romPtr); + +if (sramPath) { + const s = readFileSync(sramPath); + const p = intoWasm(s); + const n = ex.gbw_sram_load(p, s.length); + ex.gbw_free(p); + if (n !== s.length) + throw new Error(`sram rejected: ${s.length}B given, cart wants ${ex.gbw_sram_size()}B`); +} + +const cstr = (ptr) => { + const m = new Uint8Array(memory.buffer); + let e = ptr; while (m[e]) e++; + return text.decode(m.subarray(ptr, e)); +}; +console.error(`wasm: '${cstr(ex.gbw_title())}' cgb=${ex.gbw_is_cgb()} ` + + `battery=${ex.gbw_has_battery()} sram=${ex.gbw_sram_size()}B`); + +for (let f = 0; f < frames; f++) ex.gbw_run_frame(); + +const w = ex.gbw_screen_w(), h = ex.gbw_screen_h(); +// Copy out: any later wasm call could grow (and thus detach) the buffer. +const fb = Buffer.from(new Uint8Array(memory.buffer, ex.gbw_framebuffer_rgb(), w * h * 3)); +console.error(`ran ${frames} frames, ${ex.gbw_cycles()} cycles, fb ${w}x${h}`); + +if (outPath) { + writeFileSync(outPath, Buffer.concat([Buffer.from(`P6\n${w} ${h}\n255\n`), fb])); + console.error(`wrote ${outPath}`); +} + +if (checkPath) { + const ref = readFileSync(checkPath); + // P6 header: magic, width, height, maxval - then binary RGB. + const m = /^P6\s+(\d+)\s+(\d+)\s+(\d+)\s/.exec(ref.subarray(0, 64).toString("latin1")); + if (!m) { console.error(`FAIL: ${checkPath} is not a P6 PPM`); process.exit(1); } + const [rw, rh] = [parseInt(m[1]), parseInt(m[2])]; + const pix = ref.subarray(m[0].length); + if (rw !== w || rh !== h) { + console.error(`FAIL: size ${rw}x${rh} (ref) vs ${w}x${h} (wasm)`); + process.exit(1); + } + if (!pix.subarray(0, fb.length).equals(fb)) { + let diff = 0, first = -1; + for (let i = 0; i < fb.length; i++) + if (pix[i] !== fb[i]) { diff++; if (first < 0) first = i; } + const px = Math.floor(first / 3); + console.error(`FAIL: ${diff}/${fb.length} bytes differ; first at byte ${first} ` + + `(pixel ${px % w},${Math.floor(px / w)}) ref=${pix[first]} wasm=${fb[first]}`); + process.exit(1); + } + console.error(`OK: wasm frame ${frames} matches ${checkPath} exactly (${w}x${h})`); +} diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..5503048 --- /dev/null +++ b/web/index.html @@ -0,0 +1,231 @@ +<!DOCTYPE html> +<html lang="en"> +<head> +<meta charset="utf-8"> +<meta name="viewport" content="width=device-width,initial-scale=1"> +<title>sl0pboy — a Game Boy Color emulator in your browser</title> +<style> + :root { --bg:#12121a; --fg:#d7d7e0; --dim:#6f6f85; --accent:#9bbc0f; } + * { box-sizing: border-box; } + body { + margin:0; min-height:100vh; background:var(--bg); color:var(--fg); + font:14px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; + display:flex; flex-direction:column; align-items:center; justify-content:center; + gap:14px; padding:20px; + } + h1 { font-size:15px; font-weight:600; margin:0; letter-spacing:.14em; text-transform:uppercase; } + h1 span { color:var(--accent); } + #screen { + /* the PPU's 160x144 must stay crisp at any zoom, never smoothed */ + image-rendering: pixelated; image-rendering: crisp-edges; + /* Height-aware: 160/144 means width = height * 1.111, so capping width at + 71vh keeps the whole LCD on screen in a short/landscape window. */ + background:#000; border-radius:6px; width:min(640px,92vw,71vh); aspect-ratio:160/144; + box-shadow:0 0 0 10px #22222e, 0 0 0 11px #2e2e3d, 0 18px 50px #0008; + touch-action:none; + } + #drop { + border:1px dashed #3a3a4d; border-radius:8px; padding:16px 22px; text-align:center; + color:var(--dim); cursor:pointer; transition:border-color .15s, color .15s; + } + #drop.over, #drop:hover { border-color:var(--accent); color:var(--fg); } + #drop input { display:none; } + #status { color:var(--dim); min-height:1.5em; text-align:center; font-size:12.5px; } + #status b { color:var(--fg); font-weight:600; } + kbd { + background:#22222e; border:1px solid #33334a; border-bottom-width:2px; + border-radius:4px; padding:1px 5px; font-size:11px; color:var(--fg); + } + .keys { color:var(--dim); font-size:12px; text-align:center; max-width:640px; } + .hide { display:none; } +</style> +</head> +<body> + <h1>sl0p<span>boy</span></h1> + <canvas id="screen" width="160" height="144"></canvas> + <label id="drop"> + <input type="file" id="file" accept=".gb,.gbc,.bin"> + <b>drop a ROM here</b> or click to pick one — <code>.gb</code> / <code>.gbc</code> + </label> + <div id="status">loading core…</div> + <div class="keys"> + <kbd>←↑↓→</kbd>/<kbd>WASD</kbd> d-pad · <kbd>Z</kbd> A · <kbd>X</kbd> B · + <kbd>Enter</kbd> start · <kbd>Space</kbd> select · <kbd>R</kbd> reset + </div> + +<script type="module"> +const $ = (id) => document.getElementById(id); +const statusEl = $("status"), canvas = $("screen"); +const ctx = canvas.getContext("2d", { alpha: false }); +const say = (html) => { statusEl.innerHTML = html; }; + +// ---- WASI shim ------------------------------------------------------------ +// The core is built against wasi-libc but only ever touches stdio, so these +// four fd_* calls are the entire host interface. stdout/stderr (the cart info +// banner) go to the devtools console; there are no real files to open. +const EBADF = 8; +let memory; +const dec = new TextDecoder(); +const wasi = { + fd_write(fd, iovs, iovsLen, nwritten) { + const dv = new DataView(memory.buffer); + let total = 0, parts = []; + for (let i = 0; i < iovsLen; i++) { + const p = dv.getUint32(iovs + i * 8, true), l = dv.getUint32(iovs + i * 8 + 4, true); + parts.push(new Uint8Array(memory.buffer, p, l).slice()); + total += l; + } + const s = dec.decode(new Uint8Array(parts.flatMap((a) => [...a]))); + if (s.trim()) console.log("[sl0pboy]", s.trimEnd()); + dv.setUint32(nwritten, total, true); + return 0; + }, + fd_read: () => EBADF, fd_seek: () => EBADF, fd_close: () => EBADF, +}; + +// instantiateStreaming needs the server to send application/wasm; fall back to +// the buffer path so a lazily-configured static host still works. +const imports = { wasi_snapshot_preview1: wasi }; +const res = await fetch("sl0pboy.wasm"); +if (!res.ok) { say(`<b>couldn't fetch sl0pboy.wasm</b> (${res.status})`); throw new Error("wasm fetch"); } +let instance; +try { + ({ instance } = await WebAssembly.instantiateStreaming(res.clone(), imports)); +} catch { + ({ instance } = await WebAssembly.instantiate(await res.arrayBuffer(), imports)); +} +const gb = instance.exports; +memory = gb.memory; +gb._initialize(); // reactor model: libc init first + +const intoWasm = (bytes) => { + const ptr = gb.gbw_alloc(bytes.length); + new Uint8Array(memory.buffer, ptr, bytes.length).set(bytes); + return ptr; +}; +const cstr = (ptr) => { + const m = new Uint8Array(memory.buffer); + let e = ptr; while (m[e]) e++; + return dec.decode(m.subarray(ptr, e)); +}; + +// ---- input ---------------------------------------------------------------- +// Same bits as gb.h. A browser reports key *release*, so unlike the terminal +// build there's no hold-for-N-frames guesswork: this is the true live state. +const BTN = { A:0x01, B:0x02, SELECT:0x04, START:0x08, RIGHT:0x10, LEFT:0x20, UP:0x40, DOWN:0x80 }; +const KEYMAP = { + ArrowUp:BTN.UP, ArrowDown:BTN.DOWN, ArrowLeft:BTN.LEFT, ArrowRight:BTN.RIGHT, + KeyW:BTN.UP, KeyS:BTN.DOWN, KeyA:BTN.LEFT, KeyD:BTN.RIGHT, + KeyZ:BTN.A, KeyJ:BTN.A, KeyX:BTN.B, KeyK:BTN.B, + Enter:BTN.START, Space:BTN.SELECT, +}; +let buttons = 0; +addEventListener("keydown", (e) => { + if (e.code === "KeyR" && running) { gb.gbw_reset(); return; } + const b = KEYMAP[e.code]; + if (b === undefined) return; + e.preventDefault(); + buttons |= b; gb.gbw_set_buttons(buttons); +}); +addEventListener("keyup", (e) => { + const b = KEYMAP[e.code]; + if (b === undefined) return; + e.preventDefault(); + buttons &= ~b; gb.gbw_set_buttons(buttons); +}); +// Dropping focus mid-press would otherwise latch a button down forever. +addEventListener("blur", () => { buttons = 0; gb.gbw_set_buttons(0); }); + +// ---- battery saves -------------------------------------------------------- +// No filesystem, so cartridge RAM lives in localStorage keyed by game title. +let saveKey = null, saveTimer = 0; +const readSram = () => + new Uint8Array(memory.buffer, gb.gbw_sram_ptr(), gb.gbw_sram_size()).slice(); +const persist = () => { + if (!saveKey || !gb.gbw_has_battery() || !gb.gbw_sram_size()) return; + localStorage.setItem(saveKey, btoa(String.fromCharCode(...readSram()))); +}; +const restore = () => { + if (!saveKey || !gb.gbw_has_battery()) return false; + const b64 = localStorage.getItem(saveKey); + if (!b64) return false; + const raw = atob(b64), buf = new Uint8Array(raw.length); + for (let i = 0; i < raw.length; i++) buf[i] = raw.charCodeAt(i); + const p = intoWasm(buf), n = gb.gbw_sram_load(p, buf.length); + gb.gbw_free(p); + return n === buf.length; +}; +addEventListener("beforeunload", persist); + +// ---- the frame loop ------------------------------------------------------- +// The GB runs at 59.7275Hz and the display is whatever it is, so an +// accumulator decides how many frames to emulate per repaint. Catch-up is +// capped: after a background tab or a long stall, skip ahead rather than +// running hundreds of frames in one blocking burst. +const FRAME_MS = 1000 / 59.7275, MAX_CATCHUP = 4; +const img = ctx.createImageData(160, 144); +let running = false, acc = 0, last = 0, fps = 0, fpsT = 0, fpsN = 0; + +function draw() { + // The view must be rebuilt each frame: any wasm allocation can grow the + // memory and detach every existing ArrayBuffer view. + img.data.set(new Uint8Array(memory.buffer, gb.gbw_framebuffer_rgba(), 160 * 144 * 4)); + ctx.putImageData(img, 0, 0); +} + +function loop(t) { + requestAnimationFrame(loop); + if (!running) return; + if (!last) last = t; + acc += t - last; last = t; + let n = Math.floor(acc / FRAME_MS); + if (n <= 0) return; + acc -= n * FRAME_MS; + if (n > MAX_CATCHUP) n = MAX_CATCHUP; + for (let i = 0; i < n; i++) gb.gbw_run_frame(); + draw(); + + fpsN += n; + if (t - fpsT > 500) { + fps = Math.round((fpsN * 1000) / (t - fpsT)); fpsT = t; fpsN = 0; + say(`<b>${cstr(gb.gbw_title()) || "(untitled)"}</b> · ${gb.gbw_is_cgb() ? "CGB" : "DMG"} · ${fps} fps` + + (gb.gbw_has_battery() ? " · battery save on" : "")); + } + if (gb.gbw_has_battery() && t - saveTimer > 5000) { saveTimer = t; persist(); } +} +requestAnimationFrame(loop); +document.addEventListener("visibilitychange", () => { if (!document.hidden) last = 0; }); + +// ---- loading a ROM -------------------------------------------------------- +async function loadROM(file) { + const bytes = new Uint8Array(await file.arrayBuffer()); + if (running) persist(); // flush the outgoing game + running = false; + const ptr = intoWasm(bytes); + const rc = gb.gbw_load(ptr, bytes.length); + gb.gbw_free(ptr); + if (rc !== 0) { say(`<b>failed to load ${file.name}</b> — not a Game Boy ROM?`); return; } + saveKey = "sl0pboy.sav." + (cstr(gb.gbw_title()) || file.name); + const had = restore(); + buttons = 0; gb.gbw_set_buttons(0); + acc = 0; last = 0; fpsT = 0; fpsN = 0; + running = true; + say(`<b>${cstr(gb.gbw_title()) || file.name}</b> — running${had ? " (save restored)" : ""}`); + canvas.focus(); +} + +$("file").addEventListener("change", (e) => e.target.files[0] && loadROM(e.target.files[0])); +const drop = $("drop"); +addEventListener("dragover", (e) => { e.preventDefault(); drop.classList.add("over"); }); +addEventListener("dragleave", () => drop.classList.remove("over")); +addEventListener("drop", (e) => { + e.preventDefault(); drop.classList.remove("over"); + const f = e.dataTransfer.files[0]; + if (f) loadROM(f); +}); + +say("core ready — drop in a ROM to start"); +draw(); +</script> +</body> +</html> |
