//! The wasm-bindgen surface: a cartridge's bytes in, frames of pixels and sound out, the //! player's buttons in, battery RAM and save states out and back. Numbers, strings and typed //! arrays only, so the page needs no glue beyond wasm-bindgen's. //! //! The board is gameboy-rust-fast, unchanged. It starts from the state the boot ROM leaves //! (Nintendo's boot ROMs are not shipped). The page's shape, rewind and run-ahead are //! play-nes's. use std::collections::VecDeque; use std::io::{Cursor, Read}; use wasm_bindgen::prelude::*; use gameboy_rust::{load_cartridge, machine, Clock, GameBoy}; /// T-cycles in a frame (154 lines of 456 dots). const FRAME_T: u64 = 70224; const CLOCK_HZ: f64 = 4_194_304.0; // The page's button bits. pub const UP: u32 = 1 << 0; pub const DOWN: u32 = 1 << 1; pub const LEFT: u32 = 1 << 2; pub const RIGHT: u32 = 1 << 3; pub const B: u32 = 1 << 4; pub const A: u32 = 1 << 5; pub const SELECT: u32 = 1 << 7; pub const START: u32 = 1 << 8; const BUTTONS: [(u32, &str); 8] = [ (UP, "up"), (DOWN, "down"), (LEFT, "left"), (RIGHT, "right"), (B, "b"), (A, "a"), (SELECT, "select"), (START, "start"), ]; /// A DMG's four shades, lightest first, by the page's palette name. fn shades(name: &str) -> [[u8; 3]; 4] { match name { // the grey of a Game Boy Pocket's screen "grey" => [ [0xE8, 0xE8, 0xE8], [0xA0, 0xA0, 0xA0], [0x58, 0x58, 0x58], [0x10, 0x10, 0x10], ], // a crisp black and white "bw" => [ [0xFF, 0xFF, 0xFF], [0xAA, 0xAA, 0xAA], [0x55, 0x55, 0x55], [0x00, 0x00, 0x00], ], // the green of the original's screen _ => [ [0xC4, 0xCF, 0xA1], [0x8B, 0x95, 0x6D], [0x4D, 0x53, 0x3C], [0x1F, 0x1F, 0x1F], ], } } /// A Game Boy Color's screen, as SameBoy models it ("modern balanced", its default): each /// channel through the LCD's brightness curve, then green mixed with a quarter of blue at gamma /// 1.6. Transcribed from SameBoy's Core/display.c `GB_convert_rgb15` (scale_channel_with_curve /// and the MODERN_BALANCED branch). SameBoy: Copyright (c) 2015-2026 Lior Halphon, Expat /// licence: "Permission is hereby granted, free of charge, to any person obtaining a copy of /// this software and associated documentation files (the "Software"), to deal in the Software /// without restriction, including without limitation the rights to use, copy, modify, merge, /// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to /// whom the Software is furnished to do so, subject to the following conditions: The above /// copyright notice and this permission notice shall be included in all copies or substantial /// portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND." const CGB_CURVE: [u8; 32] = [ 0, 6, 12, 20, 28, 36, 45, 56, 66, 76, 88, 100, 113, 125, 137, 149, 161, 172, 182, 192, 202, 210, 218, 225, 232, 238, 243, 247, 250, 252, 254, 255, ]; fn cgb_screen(word: u16) -> [u8; 3] { let r = CGB_CURVE[(word & 31) as usize]; let g = CGB_CURVE[((word >> 5) & 31) as usize]; let b = CGB_CURVE[((word >> 10) & 31) as usize]; let g = if g == b { g } else { let gamma = 1.6f64; let mixed = ((g as f64 / 255.0).powf(gamma) * 3.0 + (b as f64 / 255.0).powf(gamma)) / 4.0; (mixed.powf(1.0 / gamma) * 255.0).round() as u8 }; [r, g, b] } /// Four RGB shades as SNES colour words (`0bbbbbgggggrrrrr`), for the SGB's starting palettes. fn snes_words(shades: &[[u8; 3]; 4]) -> [u16; 4] { shades.map(|[r, g, b]| (r as u16 >> 3) | ((g as u16 >> 3) << 5) | ((b as u16 >> 3) << 10)) } /// RGB555 widened, with no screen modelled. fn cgb_raw(word: u16) -> [u8; 3] { let five = |c: u16| { let c = (c & 31) as u8; (c << 3) | (c >> 2) }; [five(word), five(word >> 5), five(word >> 10)] } const ROM_SUFFIXES: [&str; 3] = [".gb", ".gbc", ".sgb"]; fn is_rom(name: &str) -> bool { let lower = name.to_lowercase(); ROM_SUFFIXES.iter().any(|s| lower.ends_with(s)) } fn stem(name: &str) -> String { let last = name.rsplit(['/', '\\']).next().unwrap_or(name); match last.rfind('.') { Some(dot) if dot > 0 => last[..dot].to_string(), _ => last.to_string(), } } /// The ROM bytes and a name: the file itself, or the one ROM inside a .zip or .7z. pub fn unpack(bytes: Vec, name: &str) -> Result<(Vec, String), String> { if bytes.starts_with(b"PK\x03\x04") { let mut archive = zip::ZipArchive::new(Cursor::new(&bytes)).map_err(|e| format!("{name}: {e}"))?; let members: Vec = archive .file_names() .filter(|n| is_rom(n)) .map(str::to_owned) .collect(); if members.len() != 1 { return Err(format!("{name}: expected one ROM, found {members:?}")); } let mut entry = archive.by_name(&members[0]).map_err(|e| e.to_string())?; let mut data = Vec::new(); entry.read_to_end(&mut data).map_err(|e| e.to_string())?; return Ok((data, stem(&members[0]))); } if bytes.starts_with(&[b'7', b'z', 0xBC, 0xAF, 0x27, 0x1C]) { use sevenz_rust2::{ArchiveReader, Password}; let mut reader = ArchiveReader::new(Cursor::new(&bytes), Password::empty()) .map_err(|e| format!("{name}: could not read the 7z archive: {e}"))?; let members: Vec = reader .archive() .files .iter() .filter(|f| f.has_stream() && !f.is_directory() && is_rom(f.name())) .map(|f| f.name().to_string()) .collect(); if members.len() != 1 { return Err(format!("{name}: expected one ROM, found {members:?}")); } let data = reader .read_file(&members[0]) .map_err(|e| format!("{name}: could not unpack {}: {e}", members[0]))?; return Ok((data, stem(&members[0]))); } Ok((bytes, stem(name))) } /// One console with one cartridge. #[wasm_bindgen] pub struct Console { gb: GameBoy, /// the page's output rate: a save state carries the APU's own, so it is set again after a load sample_rate: u32, title: String, machine: String, shades: [[u8; 3]; 4], /// a CGB's RGB555 words as RGB, by the colour setting colours: Vec<[u8; 3]>, /// the buttons held, per player (players 2-4 exist on a Super Game Boy only) held: [u32; 4], rgba: Vec, sound: Vec, messages: Vec, /// Rewind: a compressed 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 numbers). 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 too). const REWIND_BUDGET: usize = 48 << 20; #[wasm_bindgen] impl Console { /// Power on with a cartridge: `bytes` as the file holds them (a .zip or .7z is fine), /// `name` the file's name, `machine` "dmg", "cgb" or "" (a Game Boy Color for a game that /// knows it, else the original), `palette` a DMG palette name ("green", "grey", "bw"), /// `wall_seconds` the time now (Unix seconds, the page's `Date.now() / 1000`): a /// cartridge clock starts there and runs with the game, and the time between visits /// passes as the cartridge's battery would have it. #[wasm_bindgen(constructor)] pub fn new( bytes: Vec, name: &str, sample_rate: u32, machine_key: &str, palette: &str, wall_seconds: f64, ) -> Result { let (data, rom_name) = unpack(bytes, name).map_err(|e| JsError::new(&e))?; // a browser's wasm has no wall clock to read: the page's time at power-on, then the board's let cart = load_cartridge(&data, Clock::BoardFrom(wall_seconds)) .map_err(|e| JsError::new(&e.to_string()))?; let key = if machine_key.is_empty() { if cart.header.cgb_flag & 0x80 != 0 { "cgb" } else if cart.header.sgb_flag == 0x03 { // a Super Game Boy for a game that has one (its border and colours) "sgb" } else { "dmg" } } else { machine_key }; let row = machine(key).ok_or_else(|| JsError::new(&format!("unknown console {key}")))?; let title = rom_name; let mut gb = GameBoy::new(cart, row, None).map_err(|e| JsError::new(&e.to_string()))?; let sgb = row.model == "sgb" || row.model == "sgb2"; if sgb { // the SGB's palettes start as the page's Game Boy screen colours (the real BIOS's // built-in palettes are Nintendo's data): a game that sends none keeps them gb.attach_sgb(snes_words(&shades(palette))) .map_err(|e| JsError::new(&e))?; } gb.hw.apu.set_sample_rate(sample_rate); gb.hw.apu.capture = true; Ok(Console { gb, sample_rate, title, machine: key.to_string(), shades: shades(palette), colours: (0..0x8000).map(cgb_screen).collect(), held: [0; 4], rgba: if sgb { vec![255; 256 * 224 * 4] } else { vec![255; 160 * 144 * 4] }, sound: Vec::new(), messages: Vec::new(), rewind: VecDeque::new(), rewind_bytes: 0, frames_since_snapshot: 0, }) } pub fn title(&self) -> String { self.title.clone() } /// "dmg" or "cgb". pub fn machine(&self) -> String { self.machine.clone() } /// The machine's display name. pub fn machine_name(&self) -> String { match self.machine.as_str() { "cgb" => "Game Boy Color".to_string(), "sgb" | "sgb2" => "Super Game Boy".to_string(), _ => "Game Boy".to_string(), } } /// The cartridge: its header title, mapper and sizes. pub fn cartridge(&self) -> String { let h = &self.gb.hw.cartridge.header; let mut text = format!("{:?}, ROM {} KiB", h.board, h.rom_banks as usize * 16); if h.ram_bytes != 0 { text += &format!(", RAM {} KiB", h.ram_bytes / 1024); } if h.has_battery { text += ", battery"; } if h.has_timer { text += ", clock"; } if h.cgb_only() { text += ", Color only"; } else if h.cgb_flag & 0x80 != 0 { text += ", Color enhanced"; } text } /// Frames a second (59.73). pub fn rate(&self) -> f64 { CLOCK_HZ / FRAME_T as f64 } /// The DMG palette, changed while playing. /// The picture's size: 160 x 144, or 256 x 224 on a Super Game Boy (its border). pub fn width(&self) -> u32 { if self.gb.hw.sgb.is_some() { 256 } else { 160 } } pub fn height(&self) -> u32 { if self.gb.hw.sgb.is_some() { 224 } else { 144 } } pub fn set_palette(&mut self, palette: &str) { self.shades = shades(palette); self.paint(); } /// A Game Boy Color's colours: true as its screen shows them (SameBoy's model), false the /// raw RGB555 words. pub fn set_screen_colours(&mut self, as_the_screen: bool) { let convert = if as_the_screen { cgb_screen } else { cgb_raw }; self.colours = (0..0x8000).map(convert).collect(); self.paint(); } // -- input ------------------------------------------------------------------------- /// The buttons held (the bits above) by player 1. The console sees each change as the /// pad's lines (on a Super Game Boy, the SGB's first SNES pad). pub fn set_buttons(&mut self, mask: u32) { self.set_player_buttons(0, mask); } /// The buttons held by player `player` (0-3). Players 2-4 are a Super Game Boy's other SNES /// pads (a game that asks for them with MLT_REQ: Bomberman, for one); elsewhere only /// player 1 exists and the others are ignored. pub fn set_player_buttons(&mut self, player: usize, mask: u32) { let sgb = self.gb.hw.sgb.is_some(); if player >= 4 || (player > 0 && !sgb) { return; } let changed = mask ^ self.held[player]; for (bit, name) in BUTTONS { if changed & bit != 0 { if sgb { // on an SGB the buttons are the SNES pads'; the ICD2 drives the lines self.gb.sgb_set_pressed(name, mask & bit != 0, player); } else { self.gb.set_pressed(name, mask & bit != 0); } } } self.held[player] = mask; } /// Whether the console takes more than one player's pad (a Super Game Boy). pub fn multiplayer(&self) -> bool { self.gb.hw.sgb.is_some() } // -- running ----------------------------------------------------------------------- /// Run one frame; `draw` false skips the picture (catching up). pub fn run_frame(&mut self, draw: bool) { self.real_frame(); if draw { self.paint(); } } /// Run one frame and show the picture of `ahead` frames later (play-nes's run-ahead): /// the console's own frame runs and gives the sound; then it is saved, run `ahead` /// frames further with the same buttons, painted, and loaded back. False if the state /// could not be loaded back (the caller should stop asking). pub fn run_frame_ahead(&mut self, ahead: u32) -> bool { self.real_frame(); if ahead == 0 { self.paint(); return true; } let snapshot = self.gb.save_state(); self.run_t(ahead as u64 * FRAME_T); self.paint(); self.gb.hw.apu.take_samples(); match self.load(&snapshot) { Ok(()) => true, Err(error) => { self.messages.push(format!("Run-ahead off: {error}")); false } } } /// Load a save state and give the APU back this page's output rate and capture (the state /// holds the rate it was saved at, perhaps another device's). fn load(&mut self, data: &[u8]) -> Result<(), String> { self.gb.load_state(data)?; self.gb.hw.apu.set_sample_rate(self.sample_rate); self.gb.hw.apu.capture = true; Ok(()) } fn run_t(&mut self, t: u64) { let end = self.gb.hw.t + t; while self.gb.hw.t < end { self.gb.step(); } } /// The console's own next frame: the frame, a rewind snapshot now and then, the sound. fn real_frame(&mut self) { // frames by the clock, from where the last one ended (a STOP or LCD-off frame is as // long as any) let end = (self.gb.hw.t / FRAME_T + 1) * FRAME_T; let t = end - self.gb.hw.t; self.run_t(t); self.frames_since_snapshot += 1; if self.frames_since_snapshot >= REWIND_EVERY { self.frames_since_snapshot = 0; self.keep_snapshot(); } self.sound.clear(); for s in self.gb.hw.apu.take_samples() { self.sound.push(s as f32 / 32768.0); } } /// One snapshot onto the rewind window, the oldest dropped past its limits. fn keep_snapshot(&mut self) { use std::io::Write; let raw = self.gb.save_state(); 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(); } } } /// The picture into the RGBA buffer: a CGB's RGB555 words, or a DMG's shades. fn paint(&mut self) { if self.gb.hw.sgb.is_some() { // the SNES picture: the border and the colourised Game Boy picture, BGR555 (sgb_render // first takes the border-fade steps due at the board's time) let words = self.gb.sgb_render(); for (pixel, &word) in self.rgba.chunks_exact_mut(4).zip(words.iter()) { let widen = |c: u16| { let c = (c & 31) as u8; (c << 3) | (c >> 2) }; pixel[0] = widen(word); pixel[1] = widen(word >> 5); pixel[2] = widen(word >> 10); } return; } let frame = &self.gb.hw.ppu.frame; if self.gb.hw.cgb { for (pixel, &word) in self.rgba.chunks_exact_mut(4).zip(frame.iter()) { let [r, g, b] = self.colours[(word & 0x7FFF) as usize]; pixel[0] = r; pixel[1] = g; pixel[2] = b; } } else { for (pixel, &shade) in self.rgba.chunks_exact_mut(4).zip(frame.iter()) { let [r, g, b] = self.shades[(shade & 3) as usize]; pixel[0] = r; pixel[1] = g; pixel[2] = b; } } } /// The last frame's RGBA bytes, 160 × 144 × 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 at the page's rate. pub fn sound(&self) -> Vec { self.sound.clone() } /// The next message to show, or "". pub fn take_message(&mut self) -> String { if self.messages.is_empty() { String::new() } else { self.messages.remove(0) } } // -- rewind ------------------------------------------------------------------------ /// One step back in place of a frame, while rewind is held (play-nes's): the newest /// snapshot kept is loaded, painted and forgotten; the oldest stays. 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 let Err(error) = self.load(&raw) { self.messages.push(format!("Rewind: {error}")); self.rewind.clear(); self.rewind_bytes = 0; return false; } self.gb.hw.apu.take_samples(); self.frames_since_snapshot = 0; self.sound.clear(); self.paint(); true } /// Seconds of the past the rewind window holds. pub fn rewind_seconds(&self) -> f64 { self.rewind.len() as f64 * REWIND_EVERY as f64 / self.rate() } /// The rewind window's memory, in bytes. pub fn rewind_memory(&self) -> usize { self.rewind_bytes } // -- battery RAM and save states --------------------------------------------------- pub fn has_battery(&mut self) -> bool { let t = self.gb.hw.t; self.gb.hw.cartridge.save_ram(t).is_some() } /// The battery-backed RAM (with an MBC3's clock, the 48-byte trailer BGB, SameBoy and /// mGBA share), to keep between visits; empty if none. pub fn battery(&mut self) -> Vec { let t = self.gb.hw.t; self.gb.hw.cartridge.save_ram(t).unwrap_or_default() } /// Battery RAM kept from an earlier visit (or from another emulator's .sav). pub fn load_battery(&mut self, data: &[u8]) { let t = self.gb.hw.t; if self.gb.hw.cartridge.save_ram(t).is_some() { self.gb.hw.cartridge.load_ram(data, t); } } /// The whole machine, as gameboy-rust's save state. pub fn save_state(&self) -> Vec { self.gb.save_state() } pub fn load_state(&mut self, data: &[u8]) -> Result<(), JsError> { self.load(data).map_err(|e| JsError::new(&e))?; self.gb.hw.apu.take_samples(); self.paint(); Ok(()) } }