A GameCube/Wii emulator and debugger written in Rust.
dsp shit idk its broken now
Layle9ce96953b5b5
diff --git a/Cargo.toml b/Cargo.tomlindex 8d23b58..e14facf 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -15,6 +15,20 @@ members = ["crates/dspemu","crates/web",]+default-members = [+ "crates/gctool",+ "crates/disasm",+ "crates/gecko",+ "crates/tinyemu",+ "crates/tinybench",+ "crates/image",+ "crates/tinyapp",+ "crates/backend-wgpu",+ "crates/dbglib",+ "crates/debugger",+ "crates/scripting",+ "crates/dspemu",+][patch.crates-io]egui = { git = "https://github.com/ioncodes/egui.git" }diff --git a/crates/dbglib/src/lib.rs b/crates/dbglib/src/lib.rsindex 470b215..0b57ef5 100644--- a/crates/dbglib/src/lib.rs+++ b/crates/dbglib/src/lib.rs@@ -5,6 +5,7 @@ pub mod windows;use std::io::Write;use gecko::gamecube::GameCube;+use gecko::scheduler::EventKind;#[derive(Debug, PartialEq, Eq, Clone, Copy)]pub enum EmulatorState {@@ -14,12 +15,15 @@ pub enum EmulatorState {StepDsp,RunUntilVsync,RunUntilAddress(u32),+ RunUntilDsp,}pub struct Debugger {state: EmulatorState,#[cfg(not(target_arch = "wasm32"))]trace_writer: Option<Box<dyn Write>>,+ #[cfg(not(target_arch = "wasm32"))]+ dsp_trace_writer: Option<Box<dyn Write>>,}impl Debugger {@@ -28,6 +32,8 @@ impl Debugger {state: EmulatorState::Paused,#[cfg(not(target_arch = "wasm32"))]trace_writer: None,+ #[cfg(not(target_arch = "wasm32"))]+ dsp_trace_writer: None,}}@@ -72,6 +78,66 @@ impl Debugger {#[cfg(target_arch = "wasm32")]pub fn trace_step(&mut self, _emulator: &GameCube) {}+ #[cfg(not(target_arch = "wasm32"))]+ pub fn is_dsp_tracing(&self) -> bool {+ self.dsp_trace_writer.is_some()+ }++ #[cfg(target_arch = "wasm32")]+ pub fn is_dsp_tracing(&self) -> bool {+ false+ }++ #[cfg(not(target_arch = "wasm32"))]+ pub fn start_dsp_trace(&mut self, writer: Box<dyn Write>) {+ self.dsp_trace_writer = Some(writer);+ }++ #[cfg(not(target_arch = "wasm32"))]+ pub fn stop_dsp_trace(&mut self) {+ if let Some(mut w) = self.dsp_trace_writer.take() {+ let _ = w.flush();+ }+ }++ #[cfg(not(target_arch = "wasm32"))]+ fn dsp_trace_step(&mut self, emulator: &GameCube) {+ if let Some(ref mut writer) = self.dsp_trace_writer {+ let line = trace::format_dsp_trace_line(&emulator.dsp);+ let _ = writeln!(writer, "{}", line);+ }+ }++ #[cfg(target_arch = "wasm32")]+ fn dsp_trace_step(&mut self, _emulator: &GameCube) {}++ /// Drain and process scheduler events, tracing DSP ticks when active.+ #[inline(always)]+ fn drain_events(&mut self, emulator: &mut GameCube) {+ while let Some(event) = emulator.scheduler.poll() {+ if event == EventKind::DspTick {+ self.dsp_trace_step(emulator);+ }+ emulator.process_event(event);+ }+ }++ /// Drain and process scheduler events, returning `true` if a DSP tick was+ /// processed. Used by `RunUntilDsp` to detect when the DSP is about to+ /// execute.+ #[inline(always)]+ fn drain_events_until_dsp(&mut self, emulator: &mut GameCube) -> bool {+ let mut dsp_hit = false;+ while let Some(event) = emulator.scheduler.poll() {+ if event == EventKind::DspTick {+ self.dsp_trace_step(emulator);+ dsp_hit = true;+ }+ emulator.process_event(event);+ }+ dsp_hit+ }+/// Execute one frame's worth of emulation based on the current state.////// After execution, transient states (`Step`, `RunUntilVsync`, `RunUntilAddress`)@@ -79,11 +145,12 @@ impl Debugger {pub fn tick(&mut self, emulator: &mut GameCube) {match self.state {EmulatorState::Running => {- if self.is_tracing() {+ if self.is_tracing() || self.is_dsp_tracing() {emulator.prepare_frame();while !emulator.vsync_pending {+ self.drain_events(emulator);self.trace_step(emulator);- emulator.step();+ emulator.step_cpu();}} else {emulator.run_until_vsync();@@ -95,15 +162,17 @@ impl Debugger {self.state = EmulatorState::Paused;}EmulatorState::StepDsp => {+ self.dsp_trace_step(emulator);emulator.tick_dsp();self.state = EmulatorState::Paused;}EmulatorState::RunUntilVsync => {- if self.is_tracing() {+ if self.is_tracing() || self.is_dsp_tracing() {emulator.prepare_frame();while !emulator.vsync_pending {+ self.drain_events(emulator);self.trace_step(emulator);- emulator.step();+ emulator.step_cpu();}} else {emulator.run_until_vsync();@@ -112,8 +181,20 @@ impl Debugger {}EmulatorState::RunUntilAddress(addr) => {while emulator.cpu.pc != addr {+ self.drain_events(emulator);+ self.trace_step(emulator);+ emulator.step_cpu();+ }+ self.state = EmulatorState::Paused;+ }+ EmulatorState::RunUntilDsp => {+ loop {+ let hit = self.drain_events_until_dsp(emulator);+ if hit {+ break;+ }self.trace_step(emulator);- emulator.step();+ emulator.step_cpu();}self.state = EmulatorState::Paused;}diff --git a/crates/dbglib/src/trace.rs b/crates/dbglib/src/trace.rsindex e7155f0..1b7c4f0 100644--- a/crates/dbglib/src/trace.rs+++ b/crates/dbglib/src/trace.rs@@ -1,5 +1,7 @@use disasm::gekko::GekkoInstruction;use disasm::tokenizer::{self, AsmToken};+use gecko::flipper::dsp::Dsp;+use gecko::flipper::dsp::core::Registers as DspRegisters;use gecko::gamecube::GameCube;const DISASM_COL: usize = 22;@@ -56,3 +58,89 @@ pub fn reg_comment(disasm_text: &str, gprs: &[u32; 32], fprs: &[f64; 32]) -> Str}parts.join(", ")}++/// Format a single DSP trace line for the current PC.+pub fn format_dsp_trace_line(dsp: &Dsp) -> String {+ let pc = dsp.registers.pc;+ let w0 = dsp.read_imem(pc);+ let w1 = dsp.read_imem(pc.wrapping_add(1));+ let buf = [(w0 >> 8) as u8, w0 as u8, (w1 >> 8) as u8, w1 as u8];++ match disasm::dsp::GcDspInstruction::decode(&buf) {+ Some((instr, byte_len)) => {+ let text = instr.to_string();+ let comment = dsp_reg_comment(&text, &dsp.registers);+ let raw = if byte_len == 2 {+ format!("{:04X} ", w0)+ } else {+ format!("{:04X} {:04X}", w0, w1)+ };+ if comment.is_empty() {+ format!("{:04X} {} {}", pc, raw, text)+ } else {+ format!("{:04X} {} {:<30}; {}", pc, raw, text, comment)+ }+ }+ None => format!("{:04X} {:04X} <unknown>", pc, w0),+ }+}++fn dsp_reg_comment(disasm_text: &str, regs: &DspRegisters) -> String {+ let tokens = tokenizer::tokenize(disasm_text);+ let mut parts = Vec::new();+ let mut seen = Vec::new();+ for tok in &tokens {+ if let AsmToken::Spr(name) = tok {+ if seen.contains(name) {+ continue;+ }+ seen.push(name);+ if let Some(val) = dsp_reg_value(name, regs) {+ parts.push(val);+ }+ }+ }+ parts.join(", ")+}++fn dsp_reg_value(name: &str, regs: &DspRegisters) -> Option<String> {+ Some(match name {+ "$ar0" => format!("ar0={:04X}", regs.ar[0]),+ "$ar1" => format!("ar1={:04X}", regs.ar[1]),+ "$ar2" => format!("ar2={:04X}", regs.ar[2]),+ "$ar3" => format!("ar3={:04X}", regs.ar[3]),+ "$ix0" => format!("ix0={:04X}", regs.ix[0]),+ "$ix1" => format!("ix1={:04X}", regs.ix[1]),+ "$ix2" => format!("ix2={:04X}", regs.ix[2]),+ "$ix3" => format!("ix3={:04X}", regs.ix[3]),+ "$wr0" => format!("wr0={:04X}", regs.wr[0]),+ "$wr1" => format!("wr1={:04X}", regs.wr[1]),+ "$wr2" => format!("wr2={:04X}", regs.wr[2]),+ "$wr3" => format!("wr3={:04X}", regs.wr[3]),+ "$st0" => format!("st0={:04X}", regs.call_stack.top()),+ "$st1" => format!("st1={:04X}", regs.data_stack.top()),+ "$st2" => format!("st2={:04X}", regs.loop_addr.top()),+ "$st3" => format!("st3={:04X}", regs.loop_counter.top()),+ "$ac0.h" => format!("ac0.h={:04X}", regs.ac0_high),+ "$ac1.h" => format!("ac1.h={:04X}", regs.ac1_high),+ "$ac0.m" => format!("ac0.m={:04X}", regs.ac0_mid),+ "$ac1.m" => format!("ac1.m={:04X}", regs.ac1_mid),+ "$ac0.l" => format!("ac0.l={:04X}", regs.ac0_low),+ "$ac1.l" => format!("ac1.l={:04X}", regs.ac1_low),+ "$ac0" => format!("ac0={:010X}", regs.ac(0) as u64 & 0xFF_FFFF_FFFF),+ "$ac1" => format!("ac1={:010X}", regs.ac(1) as u64 & 0xFF_FFFF_FFFF),+ "$ax0.l" => format!("ax0.l={:04X}", regs.ax[0]),+ "$ax1.l" => format!("ax1.l={:04X}", regs.ax[1]),+ "$ax0.h" => format!("ax0.h={:04X}", regs.axh[0]),+ "$ax1.h" => format!("ax1.h={:04X}", regs.axh[1]),+ "$ax0" => format!("ax0={:08X}", (regs.axh[0] as u32) << 16 | regs.ax[0] as u32),+ "$ax1" => format!("ax1={:08X}", (regs.axh[1] as u32) << 16 | regs.ax[1] as u32),+ "$cr" => format!("cr={:04X}", regs.config),+ "$sr" => format!("sr={:04X}", u16::from(regs.status)),+ "$prod.l" => format!("prod.l={:04X}", regs.product_low),+ "$prod.m1" => format!("prod.m1={:04X}", regs.product_mid1),+ "$prod.h" => format!("prod.h={:04X}", regs.product_high),+ "$prod.m2" => format!("prod.m2={:04X}", regs.product_mid2),+ _ => return None,+ })+}diff --git a/crates/dbglib/src/windows.rs b/crates/dbglib/src/windows.rsindex ebba8df..9a3d9c4 100644--- a/crates/dbglib/src/windows.rs+++ b/crates/dbglib/src/windows.rs@@ -27,9 +27,12 @@ pub(crate) fn token_color(token: &AsmToken<'_>) -> Option<Color32> {AsmToken::Gpr(_) | AsmToken::Fpr(_) | AsmToken::CrField(_) | AsmToken::Spr(_) => {Some(Color32::from_rgb(255, 200, 100))}- AsmToken::ImmSigned(_) | AsmToken::ImmUnsigned(_) | AsmToken::ImmHex(_) | AsmToken::Displacement(_) => {- Some(Color32::from_rgb(150, 220, 150))- }+ AsmToken::ImmSigned(_)+ | AsmToken::ImmUnsigned(_)+ | AsmToken::ImmHex(_)+ | AsmToken::Displacement(_)+ | AsmToken::AddrPrefix+ | AsmToken::ImmPrefix => Some(Color32::from_rgb(150, 220, 150)),AsmToken::BranchTarget(_) => Some(Color32::from_rgb(255, 150, 150)),AsmToken::Punct(_) | AsmToken::Text(_) => None,}diff --git a/crates/dbglib/src/windows/controls.rs b/crates/dbglib/src/windows/controls.rsindex b1a93c1..ec3010b 100644--- a/crates/dbglib/src/windows/controls.rs+++ b/crates/dbglib/src/windows/controls.rs@@ -12,6 +12,9 @@ pub fn show_controls(tracing: bool,start_trace: &mut bool,stop_trace: &mut bool,+ dsp_tracing: bool,+ start_dsp_trace: &mut bool,+ stop_dsp_trace: &mut bool,) {egui::Window::new("Controls").open(open)@@ -72,6 +75,16 @@ pub fn show_controls(*state = EmulatorState::RunUntilVsync;}+ if ui+ .add_enabled(+ is_paused,+ egui::Button::new(format!("{} Run Until DSP", icons::FAST_FORWARD)).min_size(btn_size),+ )+ .clicked()+ {+ *state = EmulatorState::RunUntilDsp;+ }+ui.separator();ui.horizontal(|ui| {@@ -109,18 +122,34 @@ pub fn show_controls(if !tracing {if ui- .add(egui::Button::new(format!("{} Start Trace", icons::RECORD)).min_size(btn_size))+ .add(egui::Button::new(format!("{} Start CPU Trace", icons::RECORD)).min_size(btn_size)).clicked(){*start_trace = true;}} else {if ui- .add(egui::Button::new(format!("{} Stop Trace", icons::STOP)).min_size(btn_size))+ .add(egui::Button::new(format!("{} Stop CPU Trace", icons::STOP)).min_size(btn_size)).clicked(){*stop_trace = true;}}++ if !dsp_tracing {+ if ui+ .add(egui::Button::new(format!("{} Start DSP Trace", icons::RECORD)).min_size(btn_size))+ .clicked()+ {+ *start_dsp_trace = true;+ }+ } else {+ if ui+ .add(egui::Button::new(format!("{} Stop DSP Trace", icons::STOP)).min_size(btn_size))+ .clicked()+ {+ *stop_dsp_trace = true;+ }+ }});}diff --git a/crates/dbglib/src/windows/dsp.rs b/crates/dbglib/src/windows/dsp.rsindex 6402ec5..90fabfb 100644--- a/crates/dbglib/src/windows/dsp.rs+++ b/crates/dbglib/src/windows/dsp.rs@@ -21,40 +21,110 @@ fn imem_slice(dsp: &Dsp, word_addr: u16) -> Option<&[u8]> {pub fn show_dsp(ctx: &Context, open: &mut bool, dsp: &Dsp) {egui::Window::new("DSP").open(open).show(ctx, |ui| {- Grid::new("dsp_special_regs")- .num_columns(4)- .striped(true)- .show(ui, |ui| {- ui.label("PC");- ui.monospace(format!("{:#06X}", dsp.registers.pc));- ui.label("Halt");- ui.label(if dsp.csr.halt() { "yes" } else { "no" });- ui.end_row();-- ui.label("Reset");- ui.label(if dsp.csr.reset() { "yes" } else { "no" });- ui.label("CSR");- ui.monospace(format!("{:#06X}", dsp.csr.raw()));- ui.end_row();+ Grid::new("dsp_control").num_columns(4).striped(true).show(ui, |ui| {+ ui.label("PC");+ ui.monospace(format!("{:#06X}", dsp.registers.pc));+ ui.label("Halt");+ ui.label(if dsp.csr.halt() { "yes" } else { "no" });+ ui.end_row();++ ui.label("Reset");+ ui.label(if dsp.csr.reset() { "yes" } else { "no" });+ ui.label("CSR");+ ui.monospace(format!("{:#06X}", dsp.csr.raw()));+ ui.end_row();++ let mbox_to_dsp = ((dsp.mailbox_to_dsp_hi.raw() as u32) << 16) | dsp.mailbox_to_dsp_lo.raw() as u32;+ let mbox_to_cpu = ((dsp.mailbox_to_cpu_hi.raw() as u32) << 16) | dsp.mailbox_to_cpu_lo.raw() as u32;++ ui.label("CPU->DSP");+ ui.monospace(format!("{:#010X}", mbox_to_dsp));+ ui.label("DSP->CPU");+ ui.monospace(format!("{:#010X}", mbox_to_cpu));+ ui.end_row();++ let to_dsp_busy = dsp.mailbox_to_dsp_hi.busy();+ let to_cpu_busy = dsp.mailbox_to_cpu_hi.busy();++ ui.label("CPU->DSP");+ ui.label(if to_dsp_busy { "busy" } else { "ready" });+ ui.label("DSP->CPU");+ ui.label(if to_cpu_busy { "busy" } else { "ready" });+ ui.end_row();++ #[cfg(not(target_arch = "wasm32"))]+ if ui.button("Dump DSP").clicked() {+ let mut dump = Vec::new();+ dump.extend_from_slice(&dsp.iram[..]);+ dump.extend_from_slice(&dsp.irom[..]);+ dump.extend_from_slice(&dsp.dram[..]);+ dump.extend_from_slice(&dsp.coef[..]);+ dump.extend_from_slice(&dsp.ifx[..]);+ std::fs::write("dsp_dump.bin", dump).expect("Failed to write DSP dump");+ }+ ui.end_row();+ });- let mbox_to_dsp = ((dsp.mailbox_to_dsp_hi.raw() as u32) << 16) | dsp.mailbox_to_dsp_lo.raw() as u32;- let mbox_to_cpu = ((dsp.mailbox_to_cpu_hi.raw() as u32) << 16) | dsp.mailbox_to_cpu_lo.raw() as u32;-- ui.label("CPU->DSP");- ui.monospace(format!("{:#010X}", mbox_to_dsp));- ui.label("DSP->CPU");- ui.monospace(format!("{:#010X}", mbox_to_cpu));- ui.end_row();+ ui.separator();- #[cfg(not(target_arch = "wasm32"))]- if ui.button("Dump DSP").clicked() {- let mut dump = Vec::new();- dump.extend_from_slice(&dsp.iram[..]);- dump.extend_from_slice(&dsp.dram[..]);- std::fs::write("dsp_dump.bin", dump).expect("Failed to write DSP dump");+ let r = &dsp.registers;++ Grid::new("dsp_regs").num_columns(8).striped(true).show(ui, |ui| {+ // AR0-AR3 / IX0-IX3+ for i in 0..4 {+ ui.label(format!("AR{i}"));+ ui.monospace(format!("{:04X}", r.ar[i]));+ ui.label(format!("IX{i}"));+ ui.monospace(format!("{:04X}", r.ix[i]));+ ui.label(format!("WR{i}"));+ ui.monospace(format!("{:04X}", r.wr[i]));+ match i {+ 0 => {+ ui.label("ST0");+ ui.monospace(format!("{:04X}", r.call_stack.top()));+ }+ 1 => {+ ui.label("ST1");+ ui.monospace(format!("{:04X}", r.data_stack.top()));+ }+ 2 => {+ ui.label("ST2");+ ui.monospace(format!("{:04X}", r.loop_addr.top()));+ }+ 3 => {+ ui.label("ST3");+ ui.monospace(format!("{:04X}", r.loop_counter.top()));+ }+ _ => unreachable!(),}ui.end_row();- });+ }++ // Accumulators (40-bit)+ ui.label("AC0");+ ui.monospace(format!("{:02X}_{:04X}_{:04X}", r.ac0_high & 0xFF, r.ac0_mid, r.ac0_low));+ ui.label("AC1");+ ui.monospace(format!("{:02X}_{:04X}_{:04X}", r.ac1_high & 0xFF, r.ac1_mid, r.ac1_low));+ ui.label("AX0");+ ui.monospace(format!("{:04X}_{:04X}", r.axh[0], r.ax[0]));+ ui.label("AX1");+ ui.monospace(format!("{:04X}_{:04X}", r.axh[1], r.ax[1]));+ ui.end_row();++ // Product, Config, SR+ ui.label("PROD");+ ui.monospace(format!(+ "{:04X}_{:04X}_{:04X}_{:04X}",+ r.product_mid2, r.product_high, r.product_mid1, r.product_low+ ));+ ui.label("SR");+ ui.monospace(format!("{:04X}", u16::from(r.status)));+ ui.label("CR");+ ui.monospace(format!("{:04X}", r.config));+ ui.label("");+ ui.label("");+ ui.end_row();+ });ui.separator();@@ -67,8 +137,8 @@ pub fn show_dsp(ctx: &Context, open: &mut bool, dsp: &Dsp) {.min_col_width(0.0).striped(true).show(ui, |ui| {- let mut addr = dsp.registers.pc;- for _ in 0..20 {+ let mut addr = dsp.registers.pc.saturating_sub(20);+ for _ in 0..40 {let mem = imem_slice(dsp, addr);let Some(mem) = mem else { break };diff --git a/crates/debugger/src/debugger.rs b/crates/debugger/src/debugger.rsindex 1a1800d..1feb7dc 100644--- a/crates/debugger/src/debugger.rs+++ b/crates/debugger/src/debugger.rs@@ -4,7 +4,8 @@ use std::io::BufWriter;use dbglib::Debugger;use image::symbols::SymbolTable;-const TRACE_FILENAME: &str = "trace.log";+const CPU_TRACE_FILENAME: &str = "cpu_trace.log";+const DSP_TRACE_FILENAME: &str = "dsp_trace.log";const DEFAULT_LUA_SCRIPT: &str = include_str!("../../../scripts/bs2_dvd_state_logger.lua");pub struct DebuggerUi {@@ -57,11 +58,20 @@ impl Default for DebuggerUi {impl DebuggerUi {pub fn start_trace(&mut self) {- let file = File::create(TRACE_FILENAME).expect("failed to create trace file");+ let file = File::create(CPU_TRACE_FILENAME).expect("failed to create CPU trace file");self.debugger.start_trace(Box::new(BufWriter::new(file)));}pub fn stop_trace(&mut self) {self.debugger.stop_trace();}++ pub fn start_dsp_trace(&mut self) {+ let file = File::create(DSP_TRACE_FILENAME).expect("failed to create DSP trace file");+ self.debugger.start_dsp_trace(Box::new(BufWriter::new(file)));+ }++ pub fn stop_dsp_trace(&mut self) {+ self.debugger.stop_dsp_trace();+ }}diff --git a/crates/debugger/src/render.rs b/crates/debugger/src/render.rsindex 47d1e5d..6a78aab 100644--- a/crates/debugger/src/render.rs+++ b/crates/debugger/src/render.rs@@ -276,6 +276,16 @@ impl RenderState {debugger_ui.debugger.set_state(EmulatorState::RunUntilVsync);ui.close();}+ if ui+ .add_enabled(+ is_paused,+ egui::Button::new(format!("{} Run Until DSP", icons::FAST_FORWARD)),+ )+ .clicked()+ {+ debugger_ui.debugger.set_state(EmulatorState::RunUntilDsp);+ ui.close();+ }});ui.menu_button("Windows", |ui| {@@ -317,7 +327,10 @@ impl RenderState {if debugger_ui.show_controls {let mut start_trace = false;let mut stop_trace = false;+ let mut start_dsp_trace = false;+ let mut stop_dsp_trace = false;let tracing = debugger_ui.debugger.is_tracing();+ let dsp_tracing = debugger_ui.debugger.is_dsp_tracing();let mut state = debugger_ui.debugger.state();dbglib::windows::controls::show_controls(&ctx,@@ -328,6 +341,9 @@ impl RenderState {tracing,&mut start_trace,&mut stop_trace,+ dsp_tracing,+ &mut start_dsp_trace,+ &mut stop_dsp_trace,);debugger_ui.debugger.set_state(state);if start_trace {@@ -336,6 +352,12 @@ impl RenderState {if stop_trace {debugger_ui.stop_trace();}+ if start_dsp_trace {+ debugger_ui.start_dsp_trace();+ }+ if stop_dsp_trace {+ debugger_ui.stop_dsp_trace();+ }}if debugger_ui.show_gx_state {dbglib::windows::gx::show_gx(&ctx, &mut debugger_ui.show_gx_state, gx, mmio);diff --git a/crates/disasm/src/tokenizer.rs b/crates/disasm/src/tokenizer.rsindex 3576503..63f1837 100644--- a/crates/disasm/src/tokenizer.rs+++ b/crates/disasm/src/tokenizer.rs@@ -12,6 +12,8 @@ pub enum AsmToken<'a> {ImmHex(i64),Displacement(i32),BranchTarget(&'a str),+ AddrPrefix,+ ImmPrefix,Punct(char),Text(&'a str),}@@ -28,6 +30,8 @@ impl fmt::Display for AsmToken<'_> {AsmToken::ImmUnsigned(v) => write!(f, "{v}"),AsmToken::ImmHex(v) if *v < 0 => write!(f, "-0x{:X}", -v),AsmToken::ImmHex(v) => write!(f, "0x{v:X}"),+ AsmToken::AddrPrefix => f.write_str("@"),+ AsmToken::ImmPrefix => f.write_str("#"),AsmToken::Displacement(v) => write!(f, "{v}"),AsmToken::BranchTarget(s) => f.write_str(s),AsmToken::Punct(c) => write!(f, "{c}"),@@ -123,12 +127,24 @@ fn tokenize_operands<'a>(sc: &mut Scanner<'a>, tokens: &mut Vec<AsmToken<'a>>, mlet ch = b as char;// ── Whitespace / punctuation ─────────────────────────────────- if ch.is_ascii_whitespace() || matches!(ch, ',' | '(' | ')' | '@' | '#' | '.') {+ if ch.is_ascii_whitespace() || matches!(ch, ',' | '(' | ')' | '.') {tokens.push(AsmToken::Punct(ch));sc.skip(1);continue;}+ if ch == '@' {+ tokens.push(AsmToken::AddrPrefix);+ sc.skip(1);+ continue;+ }++ if ch == '#' {+ tokens.push(AsmToken::ImmPrefix);+ sc.skip(1);+ continue;+ }+// ── Hex immediate: 0x... ─────────────────────────────────────if sc.starts_with(b"0x") {let slice = sc.span(|s| {diff --git a/crates/gecko/src/flipper/dsp.rs b/crates/gecko/src/flipper/dsp.rsindex bdc50dd..e801a65 100644--- a/crates/gecko/src/flipper/dsp.rs+++ b/crates/gecko/src/flipper/dsp.rs@@ -184,6 +184,7 @@ impl GameCube {}self.dsp.registers.pc = self.dsp.registers.nia;+ self.check_dsp_interrupts();}}@@ -229,8 +230,13 @@ impl Dsp {/// Read a 16-bit word from IFX register space, with mailbox side-effects.pub fn read_ifx(&mut self, addr: u16) -> u16 {match addr {- // CMBH (CPU Mailbox High): reading returns data + M bit- 0xFFFE => self.mailbox_to_dsp_hi.raw(),+ // CMBH (CPU Mailbox High): reading returns data + M bit;+ // clears M (busy) so the CPU sees the mailbox as free.+ 0xFFFE => {+ let val = self.mailbox_to_dsp_hi.raw();+ self.mailbox_to_dsp_hi.set_busy(false);+ val+ }// CMBL (CPU Mailbox Low): reading clears CMBH.M (busy)0xFFFF => {self.mailbox_to_dsp_hi.set_busy(false);@@ -238,12 +244,8 @@ impl Dsp {}// DMBH (DSP Mailbox High): DSP reads back what it wrote0xFFFC => self.mailbox_to_cpu_hi.raw(),- // DMBL (DSP Mailbox Low): reading clears DMBH.M (CPU consumed the mail)- 0xFFFD => {- let val = self.mailbox_to_cpu_lo.raw();- self.mailbox_to_cpu_hi.set_busy(false);- val- }+ // DMBL (DSP Mailbox Low): DSP reads back what it wrote (no side effects)+ 0xFFFD => self.mailbox_to_cpu_lo.raw(),_ => read_word(&*self.ifx, addr - 0xFF00),}}@@ -251,19 +253,22 @@ impl Dsp {/// Write a 16-bit word to IFX register space, with mailbox side-effects.pub fn write_ifx(&mut self, addr: u16, value: u16) {match addr {- // DMBH (DSP Mailbox High): store data bits, M will be set when DMBL is written+ // DMBH (DSP Mailbox High): store data bits (14:0), clear M bit+ // M will be set when DMBL is written (matching Dolphin behavior)0xFFFC => {self.mailbox_to_cpu_hi = regs::MailboxToCpuHi::from_raw(value & 0x7FFF);}- // DMBL (DSP Mailbox Low): writing sets DMBH.M, signaling mail ready to CPU+ // DMBL (DSP Mailbox Low): writing sets DMBH.M+ // Interrupt is NOT raised here; the ucode must explicitly write DIRQ (0xFFFB)0xFFFD => {self.mailbox_to_cpu_lo = regs::MailboxToCpuLo::from_raw(value);self.mailbox_to_cpu_hi.set_busy(true);- tracing::debug!(- hi = format!("{:04X}", self.mailbox_to_cpu_hi.raw()),- lo = format!("{:04X}", value),- "DSP->CPU mailbox"- );+ }+ // DIRQ: DSP explicitly raises interrupt to CPU+ 0xFFFB => {+ if value & 1 != 0 {+ self.csr.set_dsp_interrupt(true);+ }}// CMBH/CMBL are read-only from DSP side0xFFFE | 0xFFFF => {}diff --git a/crates/gecko/src/flipper/dsp/interpreter.rs b/crates/gecko/src/flipper/dsp/interpreter.rsindex 313f43e..9420d1d 100644--- a/crates/gecko/src/flipper/dsp/interpreter.rs+++ b/crates/gecko/src/flipper/dsp/interpreter.rs@@ -56,11 +56,33 @@ pub fn cmp_test<const OP: u32>(let result = a.wrapping_sub(b);ctx.dsp.registers.update_flags_sub(a, b, result);}- OP_TST => todo!("tst"),- OP_TSTPROD => todo!("tstprod"),- OP_TSTAXH => todo!("tstaxh"),- OP_NX_0 => todo!("nx_0"),- OP_NX_1 => todo!("nx_1"),+ OP_TST => {+ let r = instr.r_4_4();+ let ac = ctx.dsp.registers.ac(r);+ ctx.dsp.registers.update_flags_ac(ac);+ ctx.dsp.registers.status.set_o(false);+ ctx.dsp.registers.status.set_c(false);+ }+ OP_TSTPROD => {+ let regs = &mut ctx.dsp.registers;+ let ph = (regs.product_high as u8) as i8 as i64;+ let pm1 = regs.product_mid1 as i64;+ let pm2 = regs.product_mid2 as i64;+ let pl = regs.product_low as i64;+ let prod = (ph << 32) + ((pm1 + pm2) << 16) + pl;+ regs.update_flags_ac(prod);+ regs.status.set_o(false);+ regs.status.set_c(false);+ }+ OP_TSTAXH => {+ let r = instr.r_7_7() as usize;+ let val = (ctx.dsp.registers.axh[r] as i16 as i64) << 16;+ ctx.dsp.registers.update_flags_ac(val);+ ctx.dsp.registers.status.set_as32(false);+ ctx.dsp.registers.status.set_o(false);+ ctx.dsp.registers.status.set_c(false);+ }+ OP_NX_0 | OP_NX_1 => {}OP_CLR => {let r = instr.r_4_4();// Clear all three parts of the accumulator@@ -165,9 +187,47 @@ pub fn imm_alu<const OP: u32>() {match OP {OP_ADDI => todo!("addi"),- OP_XORI => todo!("xori"),- OP_ANDI => todo!("andi"),- OP_ORI => todo!("ori"),+ OP_XORI => {+ let d = instr.d_7_7();+ let ac_mid = if d != 0 {+ ctx.dsp.registers.ac1_mid+ } else {+ ctx.dsp.registers.ac0_mid+ };+ let result = ac_mid ^ instr.imm_16_31();+ ctx.dsp.registers.write::<false>(reg::AC0M + d, result);+ let ac = ctx.dsp.registers.ac(d);+ ctx.dsp.registers.update_flags_ac(ac);+ ctx.dsp.registers.status.set_o(false);+ ctx.dsp.registers.status.set_c(false);+ }+ OP_ANDI => {+ let d = instr.d_7_7();+ let ac_mid = if d != 0 {+ ctx.dsp.registers.ac1_mid+ } else {+ ctx.dsp.registers.ac0_mid+ };+ let result = ac_mid & instr.imm_16_31();+ ctx.dsp.registers.write::<false>(reg::AC0M + d, result);+ let ac = ctx.dsp.registers.ac(d);+ ctx.dsp.registers.update_flags_ac(ac);+ ctx.dsp.registers.status.set_o(false);+ ctx.dsp.registers.status.set_c(false);+ }+ OP_ORI => {+ let d = instr.d_7_7();+ let ac_mid = if d != 0 {+ ctx.dsp.registers.ac1_mid+ } else {+ ctx.dsp.registers.ac0_mid+ };+ let result = ac_mid | instr.imm_16_31();+ ctx.dsp.registers.write::<false>(reg::AC0M + d, result);+ let ac = ctx.dsp.registers.ac(d);+ ctx.dsp.registers.update_flags_ac(ac);+ ctx.dsp.registers.status.set_o(false);+ }OP_CMPI => {let d = instr.d_7_7();let a = ctx.dsp.registers.ac(d);@@ -308,17 +368,105 @@ pub fn load_store<const OP: u32>(}#[inline(always)]-pub fn logic<const OP: u32>(- _ctx: &mut crate::gamecube::GameCube,- _instr: crate::flipper::dsp::instruction::Instruction,-) {+pub fn logic<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::flipper::dsp::instruction::Instruction) {match OP {- OP_XORR => todo!("xorr"),- OP_ANDR => todo!("andr"),- OP_ORR => todo!("orr"),- OP_ANDC => todo!("andc"),- OP_ORC => todo!("orc"),- OP_XORC => todo!("xorc"),+ OP_XORR => {+ let s = instr.s_6_6() as usize;+ let d = instr.d_7_7();+ let ac_mid = if d != 0 {+ ctx.dsp.registers.ac1_mid+ } else {+ ctx.dsp.registers.ac0_mid+ };+ let result = ac_mid ^ ctx.dsp.registers.axh[s];+ ctx.dsp.registers.write::<false>(reg::AC0M + d, result);+ let ac = ctx.dsp.registers.ac(d);+ ctx.dsp.registers.update_flags_ac(ac);+ ctx.dsp.registers.status.set_o(false);+ ctx.dsp.registers.status.set_c(false);+ }+ OP_ANDR => {+ let s = instr.s_6_6() as usize;+ let d = instr.d_7_7();+ let ac_mid = if d != 0 {+ ctx.dsp.registers.ac1_mid+ } else {+ ctx.dsp.registers.ac0_mid+ };+ let result = ac_mid & ctx.dsp.registers.axh[s];+ ctx.dsp.registers.write::<false>(reg::AC0M + d, result);+ let ac = ctx.dsp.registers.ac(d);+ ctx.dsp.registers.update_flags_ac(ac);+ ctx.dsp.registers.status.set_o(false);+ ctx.dsp.registers.status.set_c(false);+ }+ OP_ORR => {+ let s = instr.s_6_6() as usize;+ let d = instr.d_7_7();+ let ac_mid = if d != 0 {+ ctx.dsp.registers.ac1_mid+ } else {+ ctx.dsp.registers.ac0_mid+ };+ let result = ac_mid | ctx.dsp.registers.axh[s];+ ctx.dsp.registers.write::<false>(reg::AC0M + d, result);+ let ac = ctx.dsp.registers.ac(d);+ ctx.dsp.registers.update_flags_ac(ac);+ ctx.dsp.registers.status.set_o(false);+ }+ OP_ANDC => {+ let d = instr.d_7_7();+ let ac_mid = if d != 0 {+ ctx.dsp.registers.ac1_mid+ } else {+ ctx.dsp.registers.ac0_mid+ };+ let other_mid = if d != 0 {+ ctx.dsp.registers.ac0_mid+ } else {+ ctx.dsp.registers.ac1_mid+ };+ let result = ac_mid & other_mid;+ ctx.dsp.registers.write::<false>(reg::AC0M + d, result);+ let ac = ctx.dsp.registers.ac(d);+ ctx.dsp.registers.update_flags_ac(ac);+ ctx.dsp.registers.status.set_o(false);+ ctx.dsp.registers.status.set_c(false);+ }+ OP_ORC => {+ let d = instr.d_7_7();+ let ac_mid = if d != 0 {+ ctx.dsp.registers.ac1_mid+ } else {+ ctx.dsp.registers.ac0_mid+ };+ let other_mid = if d != 0 {+ ctx.dsp.registers.ac0_mid+ } else {+ ctx.dsp.registers.ac1_mid+ };+ let result = ac_mid | other_mid;+ ctx.dsp.registers.write::<false>(reg::AC0M + d, result);+ }+ OP_XORC => {+ let d = instr.d_7_7();+ let ac_mid = if d != 0 {+ ctx.dsp.registers.ac1_mid+ } else {+ ctx.dsp.registers.ac0_mid+ };+ let other_mid = if d != 0 {+ ctx.dsp.registers.ac0_mid+ } else {+ ctx.dsp.registers.ac1_mid+ };+ let result = ac_mid ^ other_mid;+ ctx.dsp.registers.write::<false>(reg::AC0M + d, result);+ let ac = ctx.dsp.registers.ac(d);+ ctx.dsp.registers.update_flags_ac(ac);+ ctx.dsp.registers.status.set_o(false);+ ctx.dsp.registers.status.set_c(false);+ }OP_NOT_AC => todo!("not_ac"),_ => unreachable!(),}diff --git a/crates/gecko/src/flipper/dsp/regs.rs b/crates/gecko/src/flipper/dsp/regs.rsindex d1a75d4..09b35b6 100644--- a/crates/gecko/src/flipper/dsp/regs.rs+++ b/crates/gecko/src/flipper/dsp/regs.rs@@ -113,7 +113,6 @@ impl Default for ControlStatus {}// 0xCC005000 2 [W] CPU-to-DSP Mailbox High-// TODO: Since we don't emulate the DSP processor, always read busy as 0crate::mmio_register! {MailboxToDspHi: u16 @ 0xCC005000 {@@ -131,7 +130,9 @@ impl MmioAccess<Dsp> for MailboxToDspHi {}fn write(self, dsp: &mut Dsp) {- dsp.mailbox_to_dsp_hi = self;+ // CPU writing CMBH sets data bits (14:0) and clears M bit+ // M will be set when CMBL is written+ dsp.mailbox_to_dsp_hi = self.with_busy(false);}}@@ -161,7 +162,7 @@ impl MmioAccess<Dsp> for MailboxToDspLo {// 0xCC005004 2 [R] DSP-to-CPU Mailbox High (DMBH)crate::mmio_register! {- MailboxToCpuHi: u16 @ 0xCC005004 => Dsp.mailbox_to_cpu_hi {+ MailboxToCpuHi: u16 @ 0xCC005004 {#[bits(0..=14)]pub data: u16,@@ -170,6 +171,20 @@ crate::mmio_register! {}}+impl MmioAccess<Dsp> for MailboxToCpuHi {+ fn read(dsp: &Dsp) -> Self {+ dsp.mailbox_to_cpu_hi+ }++ fn read_at(dsp: &mut Dsp, addr: u32, access_size: u32) -> u32 {+ Self::read_sub(Self::read(dsp).raw() as u32, addr, access_size)+ }++ fn write(self, _dsp: &mut Dsp) {+ // Read-only from CPU side+ }+}+// 0xCC005006 2 [R] DSP-to-CPU Mailbox Low (DMBL)// Reading clears DMBH.M (bit 15), indicating the CPU has consumed the mail.diff --git a/crates/gecko/src/gamecube.rs b/crates/gecko/src/gamecube.rsindex a777eab..f49191a 100644--- a/crates/gecko/src/gamecube.rs+++ b/crates/gecko/src/gamecube.rs@@ -156,31 +156,32 @@ impl GameCube {emulator}+ /// Handle a single scheduler event.#[inline(always)]- pub fn step(&mut self) {- // Fire any events that are due- while let Some(event) = self.scheduler.poll() {- match event {- EventKind::VSync => {- self.vsync_pending = true;- self.scheduler.schedule_in(CYCLES_PER_VSYNC, EventKind::VSync);- }- EventKind::ViHalfLine => {- self.vi.on_half_line(self.scheduler.cycles);- self.vi.half_line_scheduled = false;- self.maybe_schedule_vi_half_line();- self.check_vi_interrupts();- }- EventKind::DiTransferComplete => {- self.complete_dvd_transfer();- }- EventKind::DspTick => {- self.tick_dsp();- self.scheduler.schedule_in(DSP_TICKS_PER_CPU_CYCLE, EventKind::DspTick);- }+ pub fn process_event(&mut self, event: EventKind) {+ match event {+ EventKind::VSync => {+ self.vsync_pending = true;+ self.scheduler.schedule_in(CYCLES_PER_VSYNC, EventKind::VSync);+ }+ EventKind::ViHalfLine => {+ self.vi.on_half_line(self.scheduler.cycles);+ self.vi.half_line_scheduled = false;+ self.maybe_schedule_vi_half_line();+ self.check_vi_interrupts();+ }+ EventKind::DiTransferComplete => {+ self.complete_dvd_transfer();+ }+ EventKind::DspTick => {+ self.tick_dsp();+ self.scheduler.schedule_in(DSP_TICKS_PER_CPU_CYCLE, EventKind::DspTick);}}+ }+ #[inline(always)]+ pub fn step_cpu(&mut self) {// Deliver external interrupt when EE=1 and any enabled PI interrupt is pendingif self.cpu.msr.external_interrupt_enable() && self.pi.interrupt_pending() {self.cause_external_interrupt();@@ -243,6 +244,15 @@ impl GameCube {self.cpu.pc = self.cpu.nia;}+ /// Drain pending scheduler events, then execute one CPU instruction.+ #[inline(always)]+ pub fn step(&mut self) {+ while let Some(event) = self.scheduler.poll() {+ self.process_event(event);+ }+ self.step_cpu();+ }+#[inline(always)]pub fn prepare_frame(&mut self) {self.vsync_pending = false;diff --git a/crates/gecko/src/scheduler.rs b/crates/gecko/src/scheduler.rsindex 8400d12..8ed1a09 100644--- a/crates/gecko/src/scheduler.rs+++ b/crates/gecko/src/scheduler.rs@@ -3,7 +3,7 @@ use std::collections::BinaryHeap;pub const CYCLES_PER_VSYNC: u64 = 486_000_000 / 60; // TODO: fixpub const TIMEBASE_DIVISOR: u64 = 12;-pub const DSP_TICKS_PER_CPU_CYCLE: u64 = 1024; // TODO: should probably be much less, batch it on vsync? need this for debugging atm+pub const DSP_TICKS_PER_CPU_CYCLE: u64 = 6; // ~486MHz CPU / ~81MHz DSP#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]pub enum EventKind {diff --git a/crates/tinyemu/src/fmt.rs b/crates/tinyemu/src/fmt.rsindex dc04b4a..723cf29 100644--- a/crates/tinyemu/src/fmt.rs+++ b/crates/tinyemu/src/fmt.rs@@ -14,6 +14,7 @@ pub fn colorize(tok: &AsmToken<'_>) -> String {AsmToken::ImmHex(v) => format!("0x{v:X}").blue().to_string(),AsmToken::Displacement(v) => format!("{v}").blue().to_string(),AsmToken::BranchTarget(s) => s.bright_red().to_string(),+ AsmToken::AddrPrefix | AsmToken::ImmPrefix => tok.to_string().blue().to_string(),AsmToken::Punct(_) | AsmToken::Text(_) => tok.to_string(),}}diff --git a/crates/web/src/debug_ui.rs b/crates/web/src/debug_ui.rsindex ca71a20..3d8ac05 100644--- a/crates/web/src/debug_ui.rs+++ b/crates/web/src/debug_ui.rs@@ -99,7 +99,10 @@ impl DebugState {if self.show_controls {let mut start_trace = false;let mut stop_trace = false;+ let mut start_dsp_trace = false;+ let mut stop_dsp_trace = false;let tracing = self.debugger.is_tracing();+ let dsp_tracing = self.debugger.is_dsp_tracing();let mut state = self.debugger.state();dbglib::windows::controls::show_controls(ctx,@@ -110,6 +113,9 @@ impl DebugState {tracing,&mut start_trace,&mut stop_trace,+ dsp_tracing,+ &mut start_dsp_trace,+ &mut stop_dsp_trace,);self.debugger.set_state(state);}