// SPDX-License-Identifier: MIT //! The WebAssembly check: the board built for `wasm32-unknown-unknown` (no //! window, no file system), with raw exports for a JavaScript host to load a //! ROM image and time frames (`scripts/wasm-bench.mjs`). The checksum is //! a2600-bench's (every finished line, every audio sample), so the wasm build //! can be compared with the native one. //! //! cargo build --release --target wasm32-unknown-unknown --example wasm_bench //! node scripts/wasm-bench.mjs target/wasm32-unknown-unknown/release/examples/wasm_bench.wasm ROM.a26 [FRAMES] use std::cell::RefCell; use std::rc::Rc; use a2600::cartridge::{Options, Rom}; use a2600::{System, VCS_NTSC}; struct Run { system: System, crc: Rc>, } thread_local! { static IMAGE: RefCell> = const { RefCell::new(Vec::new()) }; static RUN: RefCell> = const { RefCell::new(None) }; } /// A buffer of `len` bytes for the host to copy the ROM image into. #[no_mangle] pub extern "C" fn rom_buffer(len: usize) -> *mut u8 { IMAGE.with(|image| { let mut image = image.borrow_mut(); image.clear(); image.resize(len, 0); image.as_mut_ptr() }) } /// Power on an NTSC console with the image in the buffer; 1 on success. #[no_mangle] pub extern "C" fn load() -> u32 { let image = IMAGE.with(|image| image.borrow().clone()); let Ok(mut system) = System::from_rom(Rom::Bytes(&image), VCS_NTSC, None, Options::default()) else { return 0; }; let crc = Rc::new(RefCell::new(crc32fast::Hasher::new())); let shared = crc.clone(); system.board_mut().tia.on_line = Some(Box::new(move |tia| shared.borrow_mut().update(&tia.pixels))); RUN.with(|run| *run.borrow_mut() = Some(Run { system, crc })); 1 } /// Run `frames` frames (audio taken each frame, as a2600-bench does); returns /// the CPU cycles run since power-on. #[no_mangle] pub extern "C" fn run_frames(frames: u32) -> f64 { RUN.with(|run| { let mut run = run.borrow_mut(); let run = run.as_mut().expect("load first"); for _ in 0..frames { run.system.run_frames(1); let samples = run.system.board_mut().tia.audio.take_samples(); let mut crc = run.crc.borrow_mut(); for sample in samples { crc.update(&sample.to_le_bytes()); } } run.system.cycles() as f64 }) } /// The checksum so far (a2600-bench's `check`). #[no_mangle] pub extern "C" fn checksum() -> u32 { RUN.with(|run| { run.borrow() .as_ref() .expect("load first") .crc .borrow() .clone() .finalize() }) } /// The CPU clock of the loaded machine, Hz. #[no_mangle] pub extern "C" fn cpu_hz() -> f64 { RUN.with(|run| { run.borrow() .as_ref() .expect("load first") .system .machine .timing .cpu_hz() }) }