A GameCube/Wii emulator and debugger written in Rust.
screenshotter and cpu handlers
Layle041144434d00
diff --git a/Cargo.lock b/Cargo.lockindex 90df824..38b4114 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3022,6 +3022,18 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"+[[package]]+name = "screenshotter"+version = "0.1.0"+dependencies = [+ "backend-wgpu",+ "gecko",+ "image 0.1.0",+ "png",+ "pollster",+ "wgpu",+]+[[package]]name = "scripting"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 29f663a..5e6548c 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -16,6 +16,7 @@ members = [# Stuff we rarely use"crates/dsptestrunner",+ "crates/screenshotter",]default-members = ["crates/gctool",diff --git a/README.md b/README.mdindex 68336aa..2fb5be7 100644--- a/README.md+++ b/README.md@@ -51,7 +51,7 @@ For more information refer to the GitHub CI actions file. PGO optimized compilat```shgctool ipl --action decode ipl.encoded.bin ipl.decoded.bintinyapp --dol homebrew.dol # may also require a DSP depending on the DOL-tinyapp --iso game.iso --ipl ipl.decoded.bin --dsp dsp_rom.bin+tinyapp --dvd game.iso --ipl ipl.decoded.bin --dsp dsp_rom.bin```The CLI options are largely the same across the sub projects (such as the debugger). For more options, see `--help`.diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rsindex bd5b9f8..a8f9ae5 100644--- a/crates/backend-wgpu/src/lib.rs+++ b/crates/backend-wgpu/src/lib.rs@@ -159,7 +159,7 @@ pub struct GxRenderer {pub(crate) current_texture_ids: [Option<Address>; 8],pub(crate) current_sampler_keys: [Option<SamplerKey>; 8],// XFB output texture: composited from per-copy snapshots by PresentXfb.- pub(crate) xfb_texture: wgpu::Texture,+ pub xfb_texture: wgpu::Texture,pub xfb_view: wgpu::TextureView,pub(crate) xfb_has_content: bool,// Per-copy temporary textures stored by CopyXfb, composited by PresentXfb.@@ -386,6 +386,7 @@ impl GxRenderer {dimension: wgpu::TextureDimension::D2,format: surface_format,usage: wgpu::TextureUsages::COPY_DST+ | wgpu::TextureUsages::COPY_SRC| wgpu::TextureUsages::TEXTURE_BINDING| wgpu::TextureUsages::RENDER_ATTACHMENT,view_formats: &[],diff --git a/crates/backend-wgpu/src/render.rs b/crates/backend-wgpu/src/render.rsindex b5d1718..991a883 100644--- a/crates/backend-wgpu/src/render.rs+++ b/crates/backend-wgpu/src/render.rs@@ -526,6 +526,7 @@ impl GxRenderer {dimension: wgpu::TextureDimension::D2,format: self.surface_format,usage: wgpu::TextureUsages::COPY_DST+ | wgpu::TextureUsages::COPY_SRC| wgpu::TextureUsages::TEXTURE_BINDING| wgpu::TextureUsages::RENDER_ATTACHMENT,view_formats: &[],diff --git a/crates/gecko/src/cpu/interpreter.rs b/crates/gecko/src/cpu/interpreter.rsindex f9815e8..30da9a2 100644--- a/crates/gecko/src/cpu/interpreter.rs+++ b/crates/gecko/src/cpu/interpreter.rs@@ -7,17 +7,15 @@ mod ps_ops;mod psq;mod rotate;mod store_load;-mod stubs;mod system;pub use alu::{alu, logical};pub use branch::branch;pub use compare::compare;-pub use cr_ops::cr_ops;+pub use cr_ops::{cr_ops, mcrxr};pub use fp_ops::fp_ops;pub use ps_ops::ps_ops;pub use psq::store_load_psq;pub use rotate::rotate;-pub use store_load::{lwarx, store_load, store_load_fp, stwcx_dot};-pub use stubs::*;-pub use system::{mftb, msr, nop, sc, segment, spr, twi};+pub use store_load::{eciwx, ecowx, lswi, lswx, lwarx, store_load, store_load_fp, stswi, stswx, stwcx_dot};+pub use system::{mfsrin, mftb, msr, mtsrin, nop, sc, segment, spr, tw, twi};diff --git a/crates/gecko/src/cpu/interpreter/cr_ops.rs b/crates/gecko/src/cpu/interpreter/cr_ops.rsindex c18dc77..ee421da 100644--- a/crates/gecko/src/cpu/interpreter/cr_ops.rs+++ b/crates/gecko/src/cpu/interpreter/cr_ops.rs@@ -1,3 +1,17 @@+use crate::cpu::condition::ConditionField;++#[inline(always)]+pub fn mcrxr(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::Instruction) {+ let xer = ctx.cpu.spr.xer;+ let field = ConditionField::new()+ .with_lt(xer.summary_overflow())+ .with_gt(xer.overflow())+ .with_eq(xer.carry())+ .with_so(false);+ ctx.cpu.cr.set_field(instr.crfd(), field);+ ctx.cpu.spr.xer = xer.with_summary_overflow(false).with_overflow(false).with_carry(false);+}+#[inline(always)]pub fn cr_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::Instruction) {match OP {diff --git a/crates/gecko/src/cpu/interpreter/store_load.rs b/crates/gecko/src/cpu/interpreter/store_load.rsindex e7b3e8c..a9efcd1 100644--- a/crates/gecko/src/cpu/interpreter/store_load.rs+++ b/crates/gecko/src/cpu/interpreter/store_load.rs@@ -299,3 +299,128 @@ pub fn store_load_fp<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr:_ => todo!("FP Store/Load instruction with OP = {OP:#x}"),}}++#[inline(always)]+pub fn lswx(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::Instruction) {+ let ea = ctx+ .cpu+ .read_gpr_or_zero(instr.ra())+ .wrapping_add(ctx.cpu.read_gpr(instr.rb()));+ let mut n = ctx.cpu.spr.xer.byte_count() as u32;+ if n == 0 {+ return;+ }+ let mut r = (instr.rd() as u32).wrapping_sub(1) & 31;+ let mut i = 0u32;+ let mut addr = ea;+ while n > 0 {+ if i == 0 {+ r = (r + 1) & 31;+ ctx.cpu.write_gpr(r as u8, 0);+ }+ let byte = ctx.read_u8(addr) as u32;+ let shift = 24 - i;+ let val = ctx.cpu.read_gpr(r as u8) | (byte << shift);+ ctx.cpu.write_gpr(r as u8, val);+ i += 8;+ if i == 32 {+ i = 0;+ }+ addr = addr.wrapping_add(1);+ n -= 1;+ }+}++#[inline(always)]+pub fn stswx(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::Instruction) {+ let ea = ctx+ .cpu+ .read_gpr_or_zero(instr.ra())+ .wrapping_add(ctx.cpu.read_gpr(instr.rb()));+ let mut n = ctx.cpu.spr.xer.byte_count() as u32;+ let mut r = (instr.rs() as u32).wrapping_sub(1) & 31;+ let mut i = 0u32;+ let mut addr = ea;+ while n > 0 {+ if i == 0 {+ r = (r + 1) & 31;+ }+ let byte = (ctx.cpu.read_gpr(r as u8) >> (24 - i)) as u8;+ ctx.write_u8(addr, byte);+ i += 8;+ if i == 32 {+ i = 0;+ }+ addr = addr.wrapping_add(1);+ n -= 1;+ }+}++#[inline(always)]+pub fn lswi(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::Instruction) {+ let ea = ctx.cpu.read_gpr_or_zero(instr.ra());+ let nb = instr.nb();+ let mut n = if nb == 0 { 32u32 } else { nb as u32 };+ let mut r = (instr.rd() as u32).wrapping_sub(1) & 31;+ let mut i = 0u32;+ let mut addr = ea;+ while n > 0 {+ if i == 0 {+ r = (r + 1) & 31;+ ctx.cpu.write_gpr(r as u8, 0);+ }+ let byte = ctx.read_u8(addr) as u32;+ let shift = 24 - i;+ let val = ctx.cpu.read_gpr(r as u8) | (byte << shift);+ ctx.cpu.write_gpr(r as u8, val);+ i += 8;+ if i == 32 {+ i = 0;+ }+ addr = addr.wrapping_add(1);+ n -= 1;+ }+}++#[inline(always)]+pub fn stswi(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::Instruction) {+ let ea = ctx.cpu.read_gpr_or_zero(instr.ra());+ let nb = instr.nb();+ let mut n = if nb == 0 { 32u32 } else { nb as u32 };+ let mut r = (instr.rs() as u32).wrapping_sub(1) & 31;+ let mut i = 0u32;+ let mut addr = ea;+ while n > 0 {+ if i == 0 {+ r = (r + 1) & 31;+ }+ let byte = (ctx.cpu.read_gpr(r as u8) >> (24 - i)) as u8;+ ctx.write_u8(addr, byte);+ i += 8;+ if i == 32 {+ i = 0;+ }+ addr = addr.wrapping_add(1);+ n -= 1;+ }+}++#[inline(always)]+pub fn eciwx(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::Instruction) {+ let ea = ctx+ .cpu+ .read_gpr_or_zero(instr.ra())+ .wrapping_add(ctx.cpu.read_gpr(instr.rb()));+ let val = ctx.read_u32(ea);+ ctx.cpu.write_gpr(instr.rd(), val);+}++#[inline(always)]+pub fn ecowx(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::Instruction) {+ let ea = ctx+ .cpu+ .read_gpr_or_zero(instr.ra())+ .wrapping_add(ctx.cpu.read_gpr(instr.rb()));+ let val = ctx.cpu.read_gpr(instr.rs());+ ctx.write_u32(ea, val);+}diff --git a/crates/gecko/src/cpu/interpreter/stubs.rs b/crates/gecko/src/cpu/interpreter/stubs.rsdeleted file mode 100644index d0278ed..0000000--- a/crates/gecko/src/cpu/interpreter/stubs.rs+++ /dev/null@@ -1,78 +0,0 @@-macro_rules! stub {- ($($name:ident),* $(,)?) => {- $(- #[rustfmt::skip]- #[inline(always)]- pub fn $name(- _ctx: &mut crate::gamecube::GameCube,- _instr: crate::cpu::instruction::Instruction,- ) {- todo!(stringify!($name))- }- )*- };-}--stub! {- tw,- mtsrin, mcrxr,- lswi, mfsrin,- stswi,- eciwx, ecowx,-}--#[inline(always)]-pub fn lswx(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::Instruction) {- let ea = ctx- .cpu- .read_gpr_or_zero(instr.ra())- .wrapping_add(ctx.cpu.read_gpr(instr.rb()));- let mut n = ctx.cpu.spr.xer.byte_count() as u32;- if n == 0 {- return;- }- let mut r = (instr.rd() as u32).wrapping_sub(1) & 31;- let mut i = 0u32;- let mut addr = ea;- while n > 0 {- if i == 0 {- r = (r + 1) & 31;- ctx.cpu.write_gpr(r as u8, 0);- }- let byte = ctx.read_u8(addr) as u32;- let shift = 24 - i;- let val = ctx.cpu.read_gpr(r as u8) | (byte << shift);- ctx.cpu.write_gpr(r as u8, val);- i += 8;- if i == 32 {- i = 0;- }- addr = addr.wrapping_add(1);- n -= 1;- }-}--#[inline(always)]-pub fn stswx(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::Instruction) {- let ea = ctx- .cpu- .read_gpr_or_zero(instr.ra())- .wrapping_add(ctx.cpu.read_gpr(instr.rb()));- let mut n = ctx.cpu.spr.xer.byte_count() as u32;- let mut r = (instr.rs() as u32).wrapping_sub(1) & 31;- let mut i = 0u32;- let mut addr = ea;- while n > 0 {- if i == 0 {- r = (r + 1) & 31;- }- let byte = (ctx.cpu.read_gpr(r as u8) >> (24 - i)) as u8;- ctx.write_u8(addr, byte);- i += 8;- if i == 32 {- i = 0;- }- addr = addr.wrapping_add(1);- n -= 1;- }-}diff --git a/crates/gecko/src/cpu/interpreter/system.rs b/crates/gecko/src/cpu/interpreter/system.rsindex e111442..b1962e0 100644--- a/crates/gecko/src/cpu/interpreter/system.rs+++ b/crates/gecko/src/cpu/interpreter/system.rs@@ -77,6 +77,18 @@ pub fn segment<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate:}}+#[inline(always)]+pub fn mtsrin(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::Instruction) {+ let sr_idx = (ctx.cpu.read_gpr(instr.rb()) >> 28) as usize;+ ctx.cpu.sr[sr_idx] = Sr::from_raw(ctx.cpu.read_gpr(instr.rs()));+}++#[inline(always)]+pub fn mfsrin(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::Instruction) {+ let sr_idx = (ctx.cpu.read_gpr(instr.rb()) >> 28) as usize;+ ctx.cpu.write_gpr(instr.rd(), ctx.cpu.sr[sr_idx].raw());+}+#[inline(always)]pub fn mftb(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::Instruction) {let tbr = instr.spr_swapped();@@ -105,6 +117,23 @@ pub fn twi(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::}}+#[inline(always)]+pub fn tw(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::Instruction) {+ let a = ctx.cpu.read_gpr(instr.ra()) as i32;+ let b = ctx.cpu.read_gpr(instr.rb()) as i32;+ let to = instr.to();++ let trap = (to & 0x10 != 0 && a < b)+ || (to & 0x08 != 0 && a > b)+ || (to & 0x04 != 0 && a == b)+ || (to & 0x02 != 0 && (a as u32) < (b as u32))+ || (to & 0x01 != 0 && (a as u32) > (b as u32));++ if trap {+ ctx.cause_trap_exception();+ }+}+#[inline(always)]pub fn nop<const OP: u32>(_ctx: &mut crate::gamecube::GameCube, _instr: crate::cpu::instruction::Instruction) {}diff --git a/crates/screenshotter/Cargo.toml b/crates/screenshotter/Cargo.tomlnew file mode 100644index 0000000..f0b1a53--- /dev/null+++ b/crates/screenshotter/Cargo.toml@@ -0,0 +1,12 @@+[package]+name = "screenshotter"+version = "0.1.0"+edition = "2024"++[dependencies]+gecko = { path = "../gecko" }+image = { path = "../image" }+backend-wgpu = { path = "../backend-wgpu" }+wgpu = "28.0.0"+pollster = "0.4.0"+png = "0.18.1"diff --git a/crates/screenshotter/src/main.rs b/crates/screenshotter/src/main.rsnew file mode 100644index 0000000..aab5bc6--- /dev/null+++ b/crates/screenshotter/src/main.rs@@ -0,0 +1,249 @@+use backend_wgpu::GxRenderer;+use backend_wgpu::capture;+use gecko::flipper::si::pad;+use gecko::flipper::si::pad::PadStatus;+use gecko::flipper::vi::regs::RefreshRate;+use gecko::gamecube::GameCube;+use gecko::host::{GxAction, RenderSink};+use std::collections::HashMap;+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::{Arc, Mutex};++const WORKER_COUNT: usize = 5;++const IPL: &[u8] = include_bytes!("../../../private/IPL.decoded.bin");+const DSP: &[u8] = include_bytes!("../../../private/dsp_rom.bin");++struct SyncSink {+ gx: Arc<Mutex<GxRenderer>>,+ device: wgpu::Device,+ queue: wgpu::Queue,+}++impl RenderSink for SyncSink {+ fn exec(&mut self, action: GxAction) {+ self.gx+ .lock()+ .unwrap()+ .process_action(&self.device, &self.queue, &action);+ }+}++fn take_screenshot(device: &wgpu::Device, queue: &wgpu::Queue, gx: &GxRenderer, code: &str, frame: u32) {+ let _ = device.poll(wgpu::PollType::Wait {+ submission_index: None,+ timeout: None,+ });++ let mut captured = capture::capture_texture(device, queue, &gx.xfb_texture).expect("capture_texture returned None");++ for px in captured.rgba.chunks_exact_mut(4) {+ px[3] = 255;+ }++ let path = format!("screenshotdb/{}/{}.png", code, frame);+ let file = std::fs::File::create(&path).expect("Failed to create PNG file");++ let mut encoder = png::Encoder::new(std::io::BufWriter::new(file), captured.width, captured.height);+ encoder.set_color(png::ColorType::Rgba);+ encoder.set_depth(png::BitDepth::Eight);++ let mut writer = encoder.write_header().expect("Failed to write PNG header");+ writer+ .write_image_data(&captured.rgba)+ .expect("Failed to write PNG data");+}++fn main() {+ let path = std::env::args()+ .nth(1)+ .expect("Please provide a path to a folder of GameCube ISOs/RVZs");+ let files = std::fs::read_dir(path)+ .expect("Failed to read the provided path")+ .filter(|entry| {+ let path = entry.as_ref().unwrap().path();+ matches!(path.extension().and_then(|e| e.to_str()), Some("iso" | "rvz" | "zip"))+ })+ .map(|entry| entry.unwrap().path())+ .collect::<Vec<_>>();+ println!("Found {} files to process", files.len());++ let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {+ backends: wgpu::Backends::all(),+ ..Default::default()+ });+ let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {+ power_preference: wgpu::PowerPreference::default(),+ compatible_surface: None,+ force_fallback_adapter: false,+ }))+ .expect("no compatible wgpu adapter");+ let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default()))+ .expect("failed to acquire wgpu device");++ let surface_format = wgpu::TextureFormat::Rgba8Unorm;++ let files = Arc::new(files);+ let next = Arc::new(AtomicUsize::new(0));++ let mut handles = Vec::with_capacity(WORKER_COUNT);+ for worker_id in 0..WORKER_COUNT {+ let files = files.clone();+ let next = next.clone();+ let device = device.clone();+ let queue = queue.clone();++ handles.push(+ std::thread::Builder::new()+ .name(format!("screenshotter-{worker_id}"))+ .spawn(move || {+ loop {+ let idx = next.fetch_add(1, Ordering::Relaxed);+ if idx >= files.len() {+ break;+ }++ let file = &files[idx];+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ run_one(&device, &queue, surface_format, file);+ }));++ if let Err(payload) = result {+ let msg = payload+ .downcast_ref::<String>()+ .cloned()+ .or_else(|| payload.downcast_ref::<&'static str>().map(|s| s.to_string()))+ .unwrap_or_else(|| "<non-string panic>".to_string());+ eprintln!("Skipping {}: emulator crashed: {}", file.display(), msg);+ }+ }+ })+ .expect("failed to spawn worker"),+ );+ }++ for h in handles {+ let _ = h.join();+ }++ cleanup("screenshotdb");+}++fn hash_or_delete_unicolor(path: &std::path::Path) -> Option<u64> {+ let file = std::fs::File::open(path).ok()?;+ let decoder = png::Decoder::new(std::io::BufReader::new(file));+ let mut reader = decoder.read_info().ok()?;+ let mut buf = vec![0u8; reader.output_buffer_size()?];+ reader.next_frame(&mut buf).ok()?;++ let samples = reader.info().color_type.samples();+ let bit_depth = reader.info().bit_depth as usize;+ let bytes_per_pixel = samples * bit_depth / 8;+ if bytes_per_pixel == 0 {+ return None;+ }++ let first = &buf[..bytes_per_pixel];+ if buf.chunks_exact(bytes_per_pixel).all(|px| px == first) {+ let _ = std::fs::remove_file(path);+ return None;+ }++ use std::hash::{Hash, Hasher};+ let mut hasher = std::collections::hash_map::DefaultHasher::new();+ buf.hash(&mut hasher);+ Some(hasher.finish())+}++fn cleanup(root: &str) {+ let Ok(entries) = std::fs::read_dir(root) else {+ return;+ };++ let pngs = entries+ .flatten()+ .flat_map(|game_dir| std::fs::read_dir(game_dir.path()).ok())+ .flat_map(|dir| dir.flatten())+ .map(|e| e.path())+ .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("png"));++ let mut by_hash: HashMap<u64, Vec<std::path::PathBuf>> = HashMap::new();+ for path in pngs {+ if let Some(h) = hash_or_delete_unicolor(&path) {+ by_hash.entry(h).or_default().push(path);+ }+ }++ for paths in by_hash.into_values().filter(|v| v.len() > 1) {+ for p in paths.into_iter().skip(1) {+ let _ = std::fs::remove_file(&p);+ }+ }+}++fn run_one(device: &wgpu::Device, queue: &wgpu::Queue, surface_format: wgpu::TextureFormat, file: &std::path::Path) {+ let buffer = std::fs::read(file).expect("Failed to read the file");+ let image = image::load_dvd(buffer);++ let name = String::from_utf8_lossy(&image.header().game_name);+ let name = name.trim_end_matches('\0').to_owned();+ let code = String::from_utf8_lossy(&image.header().game_code);+ let code = code.trim_end_matches('\0').to_owned();+ println!("Running: {} ({})", name, code);++ let out_dir = format!("screenshotdb/{}", code);+ std::fs::create_dir_all(&out_dir).expect("Failed to create screenshotdb directory");++ let gx = Arc::new(Mutex::new(GxRenderer::new(device, queue, surface_format)));++ let mut gamecube = GameCube::with_ipl(IPL, true);+ gamecube.dsp.load_irom(DSP);+ gamecube.add_primary_controller(PadStatus {+ connected: true,+ ..Default::default()+ });+ gamecube.render_sink = Box::new(SyncSink {+ gx: gx.clone(),+ device: device.clone(),+ queue: queue.clone(),+ });+ gamecube.insert_dvd(image);++ let framerate = match gamecube.vi.dcr.video_format().refresh_rate() {+ RefreshRate::Hz50 => 50,+ RefreshRate::Hz60 => 60,+ };++ // Preliminary for IPL skip+ for _ in 0..(framerate * 1) {+ gamecube.run_until_vsync();+ }++ let mut frame: u32 = framerate * 2;+ {+ let g = gx.lock().unwrap();+ take_screenshot(device, queue, &g, &code, frame);+ }++ for idx in 0..20 {+ {+ let pad = gamecube.primary_controller_mut();+ pad.stick_y = pad::STICK_CENTER;+ pad.buttons = 0;++ if idx == 3 {+ pad.stick_y = 255;+ } else if idx > 3 && idx % 5 == 0 {+ pad.buttons = pad::A | pad::START;+ }+ }++ for _ in 0..(framerate * 2) {+ gamecube.run_until_vsync();+ frame += 1;+ }++ let g = gx.lock().unwrap();+ take_screenshot(device, queue, &g, &code, frame);+ }+}