//! The wasm-bindgen surface: a cartridge's bytes in, frames of pixels and sound out, //! the pads' buttons in, battery RAM out and back. Numbers, strings and typed arrays //! only, so the page needs no glue beyond wasm-bindgen's own. //! //! The board is megadrive-rust-fast, unchanged: what `md-play` runs in a window //! (`src/play.rs` there), run here a frame at a time by the page. Save states, rewind //! and run-ahead are the board's (`megadrive_rust::state`), as play-nes's are //! famicom-rust's. use std::collections::VecDeque; use std::io::Read; use wasm_bindgen::prelude::*; use megadrive_rust::cartridge::{ image_from_bytes, install_software_list, Cartridge, Listed, IMAGE_SUFFIXES, }; use megadrive_rust::frontend::{machine_for, pad_for}; use megadrive_rust::io::Device; use megadrive_rust::machine::machine; use megadrive_rust::system::System; /// MAME's software list without the plain ROMs (scripts/make-boards.py): what tells the /// board a cartridge's mapper, EEPROM or battery, as it reads megadriv.xml on a desktop. fn install_boards() { let table = include_str!("boards.tsv") .lines() .filter_map(|line| { let mut fields = line.split('\t'); let sha1 = fields.next()?.to_string(); let slot = fields.next()?.to_string(); let sram = fields.next()?.parse().ok()?; let name = fields.next()?.to_string(); Some((sha1, Listed { name, slot, sram })) }) .collect(); install_software_list(table); } /// One console with one cartridge. #[wasm_bindgen] pub struct Console { system: System, machine: String, pad: String, title: String, /// The last frame, 0xRRGGBB words from the renderer, and the same as RGBA bytes /// for an ImageData. rgb: Vec, rgba: Vec, width: u32, height: u32, /// The last frame's sound, interleaved stereo floats in [-1, 1]. sound: Vec, locked_up: Option, /// Rewind: a deflated snapshot every [`REWIND_EVERY`] frames, newest last. rewind: VecDeque>, rewind_bytes: usize, frames_since_snapshot: u32, } /// Rewind keeps a snapshot every this many frames, so holding it goes back this many /// times faster than the game runs (play-nes's figure). const REWIND_EVERY: u32 = 4; /// About a minute of snapshots at 60 frames a second... const REWIND_KEEP: usize = 900; /// ...unless they take more memory than this (a snapshot holds the picture being drawn, /// both frames' line buffers, as the board's state does). const REWIND_BUDGET: usize = 64 << 20; /// The game's name from its header: the overseas name at $150, else the domestic one /// at $120, spaces run together. fn header_title(image: &[u8]) -> String { let name = |at: usize| -> String { let field = image.get(at..(at + 48).min(image.len())).unwrap_or(&[]); let text: String = field .iter() .map(|&b| if (0x20..0x7F).contains(&b) { b as char } else { ' ' }) .collect(); text.split_whitespace().collect::>().join(" ") }; let overseas = name(0x150); if overseas.is_empty() { name(0x120) } else { overseas } } /// A 7z archive's cartridge file and its name, or `None` if `bytes` are not a 7z. /// The board reads zips itself; this picks a 7z's file the way it picks a zip's /// (`pick_image` there): the only image, else the one named as the archive, else /// the largest. The file then goes to the board as if chosen on its own, so an /// SMD dump inside is still deinterleaved. fn unpack_7z(bytes: &[u8], name: &str) -> Result, String)>, String> { use sevenz_rust2::{ArchiveReader, Password}; if !bytes.starts_with(&[b'7', b'z', 0xBC, 0xAF, 0x27, 0x1C]) { return Ok(None); } let mut reader = ArchiveReader::new(std::io::Cursor::new(bytes), Password::empty()) .map_err(|e| format!("could not read the 7z archive: {e}"))?; let files: Vec<(String, u64)> = reader .archive() .files .iter() .filter(|f| f.has_stream() && !f.is_directory()) .map(|f| (f.name().to_string(), f.size())) .collect(); let is_image = |n: &str| IMAGE_SUFFIXES.iter().any(|s| n.to_lowercase().ends_with(s)); let images: Vec<&(String, u64)> = files.iter().filter(|(n, _)| is_image(n)).collect(); let candidates = if images.is_empty() { files.iter().collect() } else { images }; let stem = |n: &str| { let last = n.rsplit(['/', '\\']).next().unwrap_or(n); match last.rfind('.') { Some(dot) if dot > 0 => last[..dot].to_string(), _ => last.to_string(), } }; let archive_stem = stem(name); let chosen = match candidates.as_slice() { [] => return Err("no cartridge image inside the 7z archive".into()), [only] => only, _ => candidates .iter() .find(|(n, _)| stem(n) == archive_stem) // The first of the largest, as the board's zip pick. .or_else(|| candidates.iter().reduce(|best, f| if f.1 > best.1 { f } else { best })) .unwrap(), }; let member_name = chosen.0.clone(); let data = reader .read_file(&member_name) .map_err(|e| format!("could not unpack {member_name} from the 7z archive: {e}"))?; Ok(Some((data, member_name))) } #[wasm_bindgen] impl Console { /// Power on with a cartridge: `bytes` as a file holds them (a ZIP, 7z or SMD dump /// is fine), `name` the file's name. `machine` and `pad` empty choose from the header. #[wasm_bindgen(constructor)] pub fn new( bytes: Vec, name: &str, sample_rate: u32, machine_name: &str, pad: &str, ) -> Result { let (bytes, name) = match unpack_7z(&bytes, name).map_err(|e| JsError::new(&e))? { Some((member, member_name)) => (member, member_name), None => (bytes, name.to_string()), }; let image = image_from_bytes(bytes, &name).map_err(|e| JsError::new(&e))?; if image.len() < 0x200 { return Err(JsError::new("too small to be a Mega Drive cartridge")); } let machine_name = if machine_name.is_empty() { machine_for(&image).to_string() } else { machine_name.to_string() }; let pad = if pad.is_empty() { pad_for(&image).to_string() } else { pad.to_string() }; let title = header_title(&image); let board_machine = machine(&machine_name) .ok_or_else(|| JsError::new(&format!("unknown machine {machine_name}")))?; let pads = [ Device::by_name(&pad).map_err(|e| JsError::new(&e))?, Device::by_name("3button").map_err(|e| JsError::new(&e))?, ]; install_boards(); let cartridge = Cartridge::from_image(image); let mut system = System::new(board_machine, Some(cartridge), Some(pads), None); system.audio.sample_rate = sample_rate; Ok(Console { system, machine: machine_name, pad, title, rgb: Vec::new(), rgba: Vec::new(), width: 0, height: 0, sound: Vec::new(), locked_up: None, rewind: VecDeque::new(), rewind_bytes: 0, frames_since_snapshot: 0, }) } pub fn machine(&self) -> String { self.machine.clone() } pub fn pad(&self) -> String { self.pad.clone() } pub fn title(&self) -> String { self.title.clone() } /// The console's own frame rate. pub fn rate(&self) -> f64 { if self.system.machine.pal { 49.70 } else { 59.92 } } /// The buttons held on a port (0 or 1), as the board's pad bits. pub fn set_buttons(&mut self, port: usize, mask: u16) { if let Some(Some(device)) = self .system .board() .dev .io .ports .get_mut(port) .map(|p| p.device.as_mut()) { device.set_pressed(mask); } } /// Run one frame; `draw` false runs it undrawn and leaves the page's picture as it was /// (catching up; see `real_frame`). False once the console has locked up; /// `locked_up` then says how. pub fn run_frame(&mut self, draw: bool) -> bool { if !self.real_frame(draw) { return false; } if draw { self.paint(); } true } /// Run one frame, and show the picture of `ahead` frames later: the console's own /// frame runs as in [`Console::run_frame`] and gives the sound; then it is /// snapshotted, run `ahead` frames further with the same buttons held, painted, and /// put back. A game that answers a button two frames later shows /// the answer in the frame the button went down, for `ahead` = 2. Costs `ahead` /// frames of emulation and a snapshot each way per frame. False if the console locked /// up in its own frame; a lock-up in a frame ahead is only looked at, not kept. pub fn run_frame_ahead(&mut self, ahead: u32) -> bool { if !self.real_frame(ahead == 0) { return false; } if ahead == 0 { self.paint(); return true; } let snapshot = megadrive_rust::state::save_snapshot(&self.system); let mut ran = true; for k in 0..ahead { // Only the frame shown is drawn (`real_frame` says why that is safe). if self.console_frame(k == ahead - 1).is_err() { ran = false; break; } let _ = self.system.take_audio(); } if ran { self.paint(); } if let Err(error) = megadrive_rust::state::load_snapshot(&mut self.system, &snapshot) { self.locked_up = Some(format!("run-ahead could not go back: {error}")); return false; } true } /// The console's own next frame: the frame, the rewind window, its sound. Drawn when /// `draw` says or when its snapshot goes into the rewind window (a rewind step shows /// the picture a snapshot holds); undrawn otherwise. The drawing switches gate only /// the pixels since megadrive-python 5351daf: an undrawn frame is the same frame, so /// the game, the sound and every later picture are what they would be /// (`scripts/check-run-ahead.mjs` checks it). fn real_frame(&mut self, draw: bool) -> bool { if self.locked_up.is_some() { return false; } let kept = self.frames_since_snapshot + 1 >= REWIND_EVERY; if let Err(lockup) = self.console_frame(draw || kept) { self.locked_up = Some(lockup.to_string()); return false; } self.frames_since_snapshot += 1; if self.frames_since_snapshot >= REWIND_EVERY { self.frames_since_snapshot = 0; self.keep_snapshot(); } let samples = self.system.take_audio(); self.sound.clear(); self.sound.extend( samples .iter() .flat_map(|&(l, r)| [l as f32 / 32768.0, r as f32 / 32768.0]) .map(|v| v.clamp(-1.0, 1.0)), ); true } /// The board's `run_frame`, drawn or not. An undrawn frame is asked for with /// `VdpState::undrawn_frame`, which the VDP clears itself as the next frame begins: /// `run_frame` stops inside the step that starts the next frame, and that step can run /// some of its lines (Overdrive 2's frame 217 begins 13 lines in, after a DMA; Virtua /// Racing's framebuffer DMA runs through the whole blank), which must be drawn if that /// frame is to be shown whole. fn console_frame(&mut self, draw: bool) -> Result<(), megadrive_rust::Lockup> { let vdp = &mut self.system.board().vdp.s; vdp.rendering = true; vdp.undrawn_frame = !draw; self.system.run_frame() } /// The finished picture into the RGBA buffer. fn paint(&mut self) { let vdp = &self.system.board().vdp; let (width, height) = vdp.renderer.frame_rgb_into(&vdp.s, &mut self.rgb); if width != 0 && height != 0 { self.width = width as u32; self.height = height as u32; self.rgba.clear(); self.rgba.reserve(self.rgb.len() * 4); for &p in &self.rgb { self.rgba .extend_from_slice(&[(p >> 16) as u8, (p >> 8) as u8, p as u8, 255]); } } } /// One snapshot onto the rewind window, the oldest dropped past its limits. fn keep_snapshot(&mut self) { use std::io::Write; let raw = megadrive_rust::state::save_snapshot(&self.system); let mut encoder = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::fast()); encoder.write_all(&raw).expect("compressing to memory"); let packed = encoder.finish().expect("compressing to memory"); self.rewind_bytes += packed.len(); self.rewind.push_back(packed); while self.rewind.len() > REWIND_KEEP || (self.rewind_bytes > REWIND_BUDGET && self.rewind.len() > 1) { if let Some(old) = self.rewind.pop_front() { self.rewind_bytes -= old.len(); } } } /// One step back in place of a frame, while rewind is held: the newest snapshot /// kept is loaded, painted and forgotten, so each call goes [`REWIND_EVERY`] frames /// further back; the oldest one stays, and the game runs on from wherever it stops. /// No sound. False when nothing is kept (or a snapshot would not load). pub fn rewind_step(&mut self) -> bool { let packed = if self.rewind.len() > 1 { let packed = self.rewind.pop_back().expect("not empty"); self.rewind_bytes -= packed.len(); packed } else if let Some(only) = self.rewind.back() { only.clone() } else { return false; }; let mut raw = Vec::new(); if flate2::read::DeflateDecoder::new(packed.as_slice()) .read_to_end(&mut raw) .is_err() { return false; } if megadrive_rust::state::load_snapshot(&mut self.system, &raw).is_err() { self.rewind.clear(); self.rewind_bytes = 0; return false; } self.locked_up = None; self.frames_since_snapshot = 0; self.sound.clear(); // The snapshot is taken at a frame's end: the picture it holds is that frame's. self.paint(); true } /// Seconds of the past the rewind window holds. pub fn rewind_seconds(&self) -> f64 { self.rewind.len() as f64 * f64::from(REWIND_EVERY) / self.rate() } /// The rewind window's memory, in bytes. pub fn rewind_memory(&self) -> usize { self.rewind_bytes } /// A snapshot's size in bytes, raw (what run-ahead copies each way per frame). pub fn snapshot_size(&self) -> usize { megadrive_rust::state::save_snapshot(&self.system).len() } /// Everything of the machine but its picture (the board's `machine_snapshot`): what a /// drawn and an undrawn run must agree on. For the checks; not a state to load. pub fn machine_state(&mut self) -> Vec { megadrive_rust::state::machine_snapshot(&mut self.system) } /// The whole machine, as megadrive-rust-fast's save state (refused on loading into /// another cartridge, machine or pad). pub fn save_state(&self) -> Vec { megadrive_rust::state::save_state(&self.system) } pub fn load_state(&mut self, data: &[u8]) -> Result<(), JsError> { megadrive_rust::state::load_state(&mut self.system, data).map_err(|e| JsError::new(&e))?; self.locked_up = None; self.paint(); Ok(()) } pub fn locked_up(&self) -> Option { self.locked_up.clone() } pub fn width(&self) -> u32 { self.width } pub fn height(&self) -> u32 { self.height } /// The last frame's RGBA bytes, width × height × 4, in the module's memory: a view /// that a later call may move, so copy it before calling again. pub fn frame_ptr(&self) -> *const u8 { self.rgba.as_ptr() } pub fn frame_len(&self) -> usize { self.rgba.len() } /// The last frame's sound, interleaved stereo floats. pub fn sound(&self) -> Vec { self.sound.clone() } /// The reset button. pub fn reset(&mut self) { self.system.press_reset(None); } /// Whether the cartridge keeps a battery-backed save. pub fn has_battery(&mut self) -> bool { !self.system.board().dev.cartridge.battery().is_empty() } /// The battery RAM, to keep between visits. pub fn save_bytes(&mut self) -> Vec { self.system.board().dev.cartridge.save_bytes() } /// Battery RAM kept from an earlier visit. pub fn load_bytes(&mut self, data: &[u8]) { self.system.board().dev.cartridge.load_bytes(data); } }