Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

MEMORY CARDS!!!

Laylebc3f6a511574
diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs
index 90dca26..125907e 100644
--- a/crates/app/src/app.rs
+++ b/crates/app/src/app.rs
@@ -44,6 +44,8 @@ pub enum Message {
MenuQuit,
MenuToggleCpu(CpuMode),
MenuToggleSkipIpl,
+ MenuToggleMemoryCard,
+ MenuToggleSram,
MenuSetTheme(ThemePreference),
MenuSetUpscale(u32),
MenuAbout,
@@ -394,6 +396,16 @@ impl App {
self.persist_config();
Task::none()
}
+ Message::MenuToggleMemoryCard => {
+ self.config.memcard_enabled = !self.config.memcard_enabled;
+ self.persist_config();
+ Task::none()
+ }
+ Message::MenuToggleSram => {
+ self.config.sram_enabled = !self.config.sram_enabled;
+ self.persist_config();
+ Task::none()
+ }
Message::MenuSetTheme(pref) => {
self.config.theme = pref;
self.persist_config();
@@ -656,6 +668,8 @@ impl App {
self.config.theme,
self.config.skip_ipl,
self.config.upscale,
+ self.config.memcard_enabled,
+ self.config.sram_enabled,
),
search_bar::search_bar(palette, &self.search),
body,
diff --git a/crates/app/src/config.rs b/crates/app/src/config.rs
index 272e7d1..7661a04 100644
--- a/crates/app/src/config.rs
+++ b/crates/app/src/config.rs
@@ -19,6 +19,10 @@ pub struct Config {
pub skip_ipl: bool,
#[serde(default = "self::default_upscale")]
pub upscale: u32,
+ #[serde(default = "self::default_memcard_enabled")]
+ pub memcard_enabled: bool,
+ #[serde(default = "self::default_sram_enabled")]
+ pub sram_enabled: bool,
pub input: hostinput::InputConfig,
}
@@ -30,6 +34,14 @@ fn default_upscale() -> u32 {
1
}
+fn default_memcard_enabled() -> bool {
+ true
+}
+
+fn default_sram_enabled() -> bool {
+ true
+}
+
impl Default for Config {
fn default() -> Self {
Self {
@@ -43,11 +55,17 @@ impl Default for Config {
ipl: None,
skip_ipl: self::default_skip_ipl(),
upscale: self::default_upscale(),
+ memcard_enabled: self::default_memcard_enabled(),
+ sram_enabled: self::default_sram_enabled(),
input: hostinput::InputConfig::default(),
}
}
}
+/// Console-internal storage (SRAM, memory cards) lives next to the binary.
+pub const SRAM_FILE: &str = "internal/sram.bin";
+pub const MEMCARD_A_FILE: &str = "internal/memcard_a.raw";
+
pub const DSP_ROM_FILE: &str = "dsp_rom.bin";
pub const DSP_COEF_FILE: &str = "dsp_coef.bin";
pub const IPL_FILE: &str = "IPL.bin";
diff --git a/crates/app/src/player/state.rs b/crates/app/src/player/state.rs
index 0863e11..fb5d15c 100644
--- a/crates/app/src/player/state.rs
+++ b/crates/app/src/player/state.rs
@@ -13,7 +13,7 @@ use gecko::{HostInput, system};
use iced::keyboard::key::{Code, Physical};
use iced::mouse::Button as MouseButton;
-use crate::config::{Config, DSP_COEF_FILE, DSP_ROM_FILE, IPL_FILE};
+use crate::config::{self, Config, DSP_COEF_FILE, DSP_ROM_FILE, IPL_FILE, MEMCARD_A_FILE, SRAM_FILE};
use crate::game::{Format, Game, Platform};
use crate::player::{audio, emu_thread, input};
@@ -24,6 +24,8 @@ struct BootParams {
coef_path: Option<PathBuf>,
ipl_path: Option<PathBuf>,
skip_ipl: bool,
+ sram_path: Option<PathBuf>,
+ memcard_path: Option<PathBuf>,
execution_mode: gecko::ExecutionMode,
input_config: hostinput::InputConfig,
}
@@ -86,6 +88,8 @@ impl PlayerState {
coef_path: coef,
ipl_path: ipl,
skip_ipl: config.skip_ipl,
+ sram_path: config.sram_enabled.then(|| config::exe_relative(SRAM_FILE)),
+ memcard_path: config.memcard_enabled.then(|| config::exe_relative(MEMCARD_A_FILE)),
execution_mode: config.cpu_mode.into(),
input_config: config.input.clone(),
})),
@@ -313,22 +317,43 @@ fn finish_boot<const S: gecko::system::SystemId>(
);
}
+fn ensure_internal_dir(path: Option<&Path>) {
+ if let Some(dir) = path.and_then(Path::parent)
+ && let Err(err) = std::fs::create_dir_all(dir)
+ {
+ tracing::warn!(?err, dir = %dir.display(), "failed to create internal storage dir");
+ }
+}
+
fn build_gamecube(dvd: Box<dyn image::Dvd>, params: &BootParams) -> gecko::system::System<{ system::GC }> {
- let Some(ipl_path) = params.ipl_path.as_deref() else {
- return GameCube::with_ipl_hle(dvd);
+ let mut emu = match params.ipl_path.as_deref() {
+ None => GameCube::with_ipl_hle(dvd),
+ Some(ipl_path) => match std::fs::read(ipl_path) {
+ Ok(ipl_data) => {
+ tracing::warn!(path = %ipl_path.display(), skip_ipl = params.skip_ipl, "booting via real IPL");
+ let mut emu = GameCube::with_ipl(&ipl_data, params.skip_ipl);
+ emu.insert_dvd(dvd);
+ emu
+ }
+ Err(err) => {
+ tracing::warn!(?err, path = %ipl_path.display(), "IPL.bin unreadable; falling back to IPL HLE");
+ GameCube::with_ipl_hle(dvd)
+ }
+ },
};
- match std::fs::read(ipl_path) {
- Ok(ipl_data) => {
- tracing::warn!(path = %ipl_path.display(), skip_ipl = params.skip_ipl, "booting via real IPL");
- let mut emu = GameCube::with_ipl(&ipl_data, params.skip_ipl);
- emu.insert_dvd(dvd);
- emu
- }
- Err(err) => {
- tracing::warn!(?err, path = %ipl_path.display(), "IPL.bin unreadable; falling back to IPL HLE");
- GameCube::with_ipl_hle(dvd)
- }
+
+ // Persist console SRAM and attach the Slot A memory card when enabled.
+ self::ensure_internal_dir(params.sram_path.as_deref().or(params.memcard_path.as_deref()));
+
+ if let Some(sram_path) = &params.sram_path {
+ emu.set_sram_path(sram_path.clone());
}
+
+ if let Some(memcard_path) = &params.memcard_path {
+ emu.insert_memory_card(0, Some(memcard_path.clone()), 256);
+ }
+
+ emu
}
fn configure_emu<const S: gecko::system::SystemId>(
diff --git a/crates/app/src/widgets/menubar.rs b/crates/app/src/widgets/menubar.rs
index e375c7a..cebc165 100644
--- a/crates/app/src/widgets/menubar.rs
+++ b/crates/app/src/widgets/menubar.rs
@@ -16,6 +16,8 @@ pub fn menubar(
theme_pref: ThemePreference,
skip_ipl: bool,
upscale: u32,
+ memcard_enabled: bool,
+ sram_enabled: bool,
) -> Element<'static, Message> {
let bar_bg = palette.bg_2;
let border = palette.border;
@@ -25,7 +27,15 @@ pub fn menubar(
Item::with_menu(self::top_label(palette, "File"), self::file_menu(palette)),
Item::with_menu(
self::top_label(palette, "Settings"),
- self::settings_menu(palette, cpu, theme_pref, skip_ipl, upscale),
+ self::settings_menu(
+ palette,
+ cpu,
+ theme_pref,
+ skip_ipl,
+ upscale,
+ memcard_enabled,
+ sram_enabled,
+ ),
),
Item::with_menu(
self::top_label(palette, "Compatibility"),
@@ -224,6 +234,8 @@ fn settings_menu(
theme_pref: ThemePreference,
skip_ipl: bool,
upscale: u32,
+ memcard_enabled: bool,
+ sram_enabled: bool,
) -> Menu<'static, Message, iced::Theme, iced::Renderer> {
Menu::new(vec![
Item::new(self::section_header(palette, "Execution Engine")),
@@ -247,6 +259,18 @@ fn settings_menu(
Message::MenuToggleSkipIpl,
Some(skip_ipl),
)),
+ Item::new(self::menu_item(
+ palette,
+ "Memory Card (Slot A)",
+ Message::MenuToggleMemoryCard,
+ Some(memcard_enabled),
+ )),
+ Item::new(self::menu_item(
+ palette,
+ "Persist SRAM",
+ Message::MenuToggleSram,
+ Some(sram_enabled),
+ )),
Item::new(self::separator(palette)),
Item::new(self::section_header(palette, "Internal Resolution")),
Item::new(self::menu_item(
diff --git a/crates/gecko/src/flipper/exi.rs b/crates/gecko/src/flipper/exi.rs
index 59e1dca..dd94a90 100644
--- a/crates/gecko/src/flipper/exi.rs
+++ b/crates/gecko/src/flipper/exi.rs
@@ -1,5 +1,6 @@
pub mod device;
pub mod macronix;
+pub mod memcard;
pub mod regs;
use crate::flipper::exi::regs::TransferType;
@@ -80,6 +81,13 @@ impl ExternalInterface {
self.devices[channel][0].as_ref().is_some_and(|d| d.connected())
}
+ pub fn macronix_mut(&mut self) -> Option<&mut macronix::ExiMacronix> {
+ self.devices[macronix::ExiMacronix::CHANNEL][macronix::ExiMacronix::DEVICE]
+ .as_mut()
+ .and_then(|d| d.as_any_mut())
+ .and_then(|any| any.downcast_mut::<macronix::ExiMacronix>())
+ }
+
#[inline(always)]
pub fn interrupt_active(&self) -> bool {
Self::channel_interrupt_active(&self.ch0_csr)
@@ -176,6 +184,16 @@ impl ExternalInterface {
}
}
+ #[inline(always)]
+ fn set_exi_interrupt<const CHANNEL: usize>(&mut self, val: bool) {
+ match CHANNEL {
+ 0 => self.ch0_csr.set_exi_interrupt(val),
+ 1 => self.ch1_csr.set_exi_interrupt(val),
+ 2 => self.ch2_csr.set_exi_interrupt(val),
+ _ => unreachable!(),
+ }
+ }
+
#[inline(always)]
fn finish_transfer<const CHANNEL: usize>(&mut self) {
match CHANNEL {
@@ -232,16 +250,37 @@ pub fn refresh_interrupts<const SYSTEM: SystemId>(sys: &mut System<SYSTEM>) {
#[inline(always)]
pub fn on_chip_select_written<const CHANNEL: usize, const SYSTEM: SystemId>(sys: &mut System<SYSTEM>, new_cs: u8) {
let prev = sys.exi.prev_cs[CHANNEL];
- if new_cs != prev && new_cs != 0 {
- if let Some(slot) = ExternalInterface::cs_to_slot(new_cs)
- && let Some(device) = &mut sys.exi.devices[CHANNEL][slot]
+
+ if new_cs != prev {
+ if new_cs != 0 {
+ if let Some(slot) = ExternalInterface::cs_to_slot(new_cs)
+ && let Some(device) = &mut sys.exi.devices[CHANNEL][slot]
+ {
+ device.on_select();
+ }
+ } else if let Some(slot) = ExternalInterface::cs_to_slot(prev)
+ && let Some(delay) = sys.exi.devices[CHANNEL][slot].as_mut().and_then(|d| d.on_deselect())
{
- device.on_select();
+ sys.scheduler
+ .schedule_in(delay, self::memcard_cmd_done::<CHANNEL, SYSTEM>);
}
}
+
sys.exi.prev_cs[CHANNEL] = new_cs;
}
+fn memcard_cmd_done<const CHANNEL: usize, const SYSTEM: SystemId>(sys: &mut System<SYSTEM>) {
+ let raise = sys.exi.devices[CHANNEL][0]
+ .as_mut()
+ .is_some_and(|d| d.complete_command());
+
+ if raise {
+ sys.exi.set_exi_interrupt::<CHANNEL>(true);
+ }
+
+ self::refresh_interrupts(sys);
+}
+
#[inline(always)]
pub fn run_dma<const CHANNEL: usize, const SYSTEM: SystemId>(sys: &mut System<SYSTEM>) {
let (cs, transfer_type, address, length) = match CHANNEL {
diff --git a/crates/gecko/src/flipper/exi/device.rs b/crates/gecko/src/flipper/exi/device.rs
index fbc3bb0..6513f1a 100644
--- a/crates/gecko/src/flipper/exi/device.rs
+++ b/crates/gecko/src/flipper/exi/device.rs
@@ -23,6 +23,18 @@ pub trait ExiDevice: Send {
fn is_stub(&self) -> bool {
false
}
+
+ fn on_deselect(&mut self) -> Option<u64> {
+ None
+ }
+
+ fn complete_command(&mut self) -> bool {
+ false
+ }
+
+ fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
+ None
+ }
}
pub struct ExiDummy;
@@ -40,3 +52,34 @@ impl ExiDevice for ExiDummy {
true
}
}
+
+/// Load a fixed-size backing file into `dst`, leaving `dst` untouched (its
+/// default contents) if the file is missing or the wrong size.
+pub fn load_backing(path: &std::path::Path, dst: &mut [u8], label: &str) {
+ match std::fs::read(path) {
+ Ok(bytes) if bytes.len() == dst.len() => {
+ dst.copy_from_slice(&bytes);
+ tracing::info!(path = %path.display(), label, "loaded backing file");
+ }
+ Ok(bytes) => tracing::warn!(
+ path = %path.display(),
+ label,
+ got = bytes.len(),
+ expected = dst.len(),
+ "backing file size mismatch, using default"
+ ),
+ Err(_) => tracing::info!(path = %path.display(), label, "backing file not found, using default"),
+ }
+}
+
+pub fn persist_backing(path: &std::path::Path, data: &[u8], label: &str) {
+ if let Some(parent) = path.parent()
+ && !parent.as_os_str().is_empty()
+ {
+ let _ = std::fs::create_dir_all(parent);
+ }
+
+ if let Err(error) = std::fs::write(path, data) {
+ tracing::warn!(path = %path.display(), label, %error, "failed to persist backing file");
+ }
+}
diff --git a/crates/gecko/src/flipper/exi/macronix.rs b/crates/gecko/src/flipper/exi/macronix.rs
index 35a86c3..cfe1e0b 100644
--- a/crates/gecko/src/flipper/exi/macronix.rs
+++ b/crates/gecko/src/flipper/exi/macronix.rs
@@ -1,14 +1,14 @@
// GameCube IPL ROM / SRAM / RTC device (EXI channel 0, device 1)
// Macronix device according to yagcd, TODO: update name
// - Address 0x000000..0x1FFFFF: Mask ROM (2 MB)
-// - Address 0x800000..0x80003F: SRAM (64 bytes)
+// - Address 0x800004..0x800043: SRAM (64 bytes; 0x800000..0x800003 is the RTC counter)
// - Address 0x840000: RTC (seconds since 2000-01-01?)
const IPL_START: u32 = 0x000000;
const IPL_END: u32 = 0x1FFFFF;
-const SRAM_START: u32 = 0x800000;
-const SRAM_END: u32 = 0x80003F;
+const SRAM_START: u32 = 0x800004;
+const SRAM_END: u32 = 0x800043;
const SRAM_SIZE: usize = 64;
const RTC_START: u32 = 0x840000;
@@ -17,6 +17,8 @@ const RTC_END: u32 = 0x840004;
pub struct ExiMacronix {
rom: Vec<u8>,
sram: Sram,
+ sram_path: Option<std::path::PathBuf>,
+ sram_dirty: bool,
command: u32,
bytes_received: usize,
cursor: usize,
@@ -30,12 +32,28 @@ impl ExiMacronix {
Self {
rom,
sram: Sram::ntsc_default(),
+ sram_path: None,
+ sram_dirty: false,
command: 0,
bytes_received: 0,
cursor: 0,
}
}
+ /// Back the SRAM with a file: load it now if present and persist any
+ /// guest writes so console settings, clock bias and the memory card's
+ /// flash id survive across runs.
+ pub fn set_sram_path(&mut self, path: std::path::PathBuf) {
+ super::device::load_backing(&path, &mut self.sram.data, "SRAM");
+ self.sram_path = Some(path);
+ }
+
+ fn flush_sram(&self) {
+ if let Some(path) = &self.sram_path {
+ super::device::persist_backing(path, &self.sram.data, "SRAM");
+ }
+ }
+
fn address(&self) -> u32 {
(self.command >> 6) & 0x1FF_FFFF
}
@@ -88,6 +106,7 @@ impl super::device::ExiDevice for ExiMacronix {
let offset = ((addr - SRAM_START) as usize + self.cursor) % SRAM_SIZE;
if self.is_write() {
self.sram.data[offset] = *byte;
+ self.sram_dirty = true;
tracing::debug!(
addr = format!("{:06X}", addr),
cursor = self.cursor,
@@ -181,8 +200,22 @@ impl super::device::ExiDevice for ExiMacronix {
for (i, b) in buf.iter().enumerate() {
self.sram.data[(base + i) % SRAM_SIZE] = *b;
}
+ self.sram_dirty = true;
}
}
+
+ fn on_deselect(&mut self) -> Option<u64> {
+ if self.sram_dirty {
+ self.flush_sram();
+ self.sram_dirty = false;
+ }
+
+ None
+ }
+
+ fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
+ Some(self)
+ }
}
#[derive(Debug, Clone)]
@@ -194,7 +227,7 @@ impl Sram {
/// Dumped from NTSC IPL
#[rustfmt::skip]
pub fn ntsc_default() -> Self {
- Self {
+ let mut sram = Self {
data: [
0x01, 0x04, 0xFE, 0xFB,
0x00, 0x14, 0xFF, 0xE8,
@@ -213,26 +246,32 @@ impl Sram {
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
],
- }
+ };
+
+ sram.fix_flash_id_checksums();
+
+ sram
}
pub fn empty() -> Self {
- Self { data: [0; SRAM_SIZE] }
- }
+ let mut sram = Self { data: [0; SRAM_SIZE] };
- // TODO: WIP
- pub fn fix_checksums(&mut self) {
- let (a, b) = Self::compute_checksums(&self.data);
- self.data[0x00..0x02].copy_from_slice(&a.to_be_bytes());
- self.data[0x02..0x04].copy_from_slice(&b.to_be_bytes());
+ sram.fix_flash_id_checksums();
+
+ sram
}
- fn compute_checksums(data: &[u8; SRAM_SIZE]) -> (u16, u16) {
- let mut sum: u16 = 0;
- for i in (0x04..0x40).step_by(2) {
- let word = u16::from_be_bytes([data[i], data[i + 1]]);
- sum = sum.wrapping_add(word);
+ fn fix_flash_id_checksums(&mut self) {
+ const FLASH_ID_BASE: usize = 0x14;
+ const FLASH_ID_LEN: usize = 12;
+ const FLASH_ID_CKSUM: usize = 0x3A;
+
+ for slot in 0..2 {
+ let base = FLASH_ID_BASE + slot * FLASH_ID_LEN;
+ let sum = self.data[base..base + FLASH_ID_LEN]
+ .iter()
+ .fold(0u8, |acc, &b| acc.wrapping_add(b));
+ self.data[FLASH_ID_CKSUM + slot] = sum ^ 0xFF;
}
- (sum, !sum)
}
}
diff --git a/crates/gecko/src/flipper/exi/memcard.rs b/crates/gecko/src/flipper/exi/memcard.rs
new file mode 100644
index 0000000..86b9e07
--- /dev/null
+++ b/crates/gecko/src/flipper/exi/memcard.rs
@@ -0,0 +1,244 @@
+use std::path::PathBuf;
+
+const BLOCK_SIZE: u32 = 0x2000;
+const PAGE_SIZE: usize = 128;
+
+const MC_STATUS_BUSY: u8 = 0x80;
+const MC_STATUS_UNLOCKED: u8 = 0x40;
+const MC_STATUS_ERASE_ERROR: u8 = 0x10;
+const MC_STATUS_PROGRAM_ERROR: u8 = 0x08;
+const MC_STATUS_READY: u8 = 0x01;
+const MC_STATUS_INIT: u8 = MC_STATUS_UNLOCKED | MC_STATUS_READY;
+
+const FLASH_ID: u16 = 0xC221;
+const CMD_DONE_DELAY_CYCLES: u64 = 5000;
+
+#[derive(PartialEq, Eq, Clone, Copy)]
+enum Command {
+ NintendoId,
+ ReadArray,
+ SetInterrupt,
+ ReadStatus,
+ ReadId,
+ ClearStatus,
+ SectorErase,
+ PageProgram,
+ ChipErase,
+ Unknown,
+}
+
+impl Command {
+ fn from_byte(byte: u8) -> Self {
+ match byte {
+ 0x00 => Command::NintendoId,
+ 0x52 => Command::ReadArray,
+ 0x81 => Command::SetInterrupt,
+ 0x83 => Command::ReadStatus,
+ 0x85 => Command::ReadId,
+ 0x89 => Command::ClearStatus,
+ 0xF1 => Command::SectorErase,
+ 0xF2 => Command::PageProgram,
+ 0xF4 => Command::ChipErase,
+ _ => Command::Unknown,
+ }
+ }
+}
+
+pub struct ExiMemoryCard {
+ data: Vec<u8>,
+ path: Option<PathBuf>,
+ size_mask: u32,
+ card_id: u32,
+
+ command: Command,
+ position: u32,
+ address: u32,
+ status: u8,
+ interrupt_switch: u8,
+ program_buffer: [u8; PAGE_SIZE],
+}
+
+impl ExiMemoryCard {
+ pub fn new(path: Option<PathBuf>, total_blocks: u32) -> Self {
+ let size_bytes = (total_blocks * BLOCK_SIZE) as usize;
+
+ let mut data = vec![0xFF; size_bytes];
+
+ if let Some(path) = &path {
+ super::device::load_backing(path, &mut data, "memory card");
+ }
+
+ Self {
+ data,
+ path,
+ size_mask: size_bytes as u32 - 1,
+ card_id: total_blocks / 16,
+ command: Command::NintendoId,
+ position: 0,
+ address: 0,
+ status: MC_STATUS_INIT,
+ interrupt_switch: 0,
+ program_buffer: [0; PAGE_SIZE],
+ }
+ }
+
+ fn flush(&self) {
+ if let Some(path) = &self.path {
+ super::device::persist_backing(path, &self.data, "memory card");
+ }
+ }
+
+ fn accumulate_address(&mut self, byte: u8) {
+ match self.position {
+ 1 => self.address = (byte as u32) << 17,
+ 2 => self.address |= (byte as u32) << 9,
+ 3 => self.address |= ((byte as u32) & 3) << 7,
+ 4 => self.address |= (byte as u32) & 0x7F,
+ _ => {}
+ }
+ }
+
+ fn advance_address(&mut self) {
+ self.address = (self.address & !0x1FF) | ((self.address + 1) & 0x1FF);
+ }
+}
+
+impl super::device::ExiDevice for ExiMemoryCard {
+ fn on_select(&mut self) {
+ self.position = 0;
+ }
+
+ fn transfer_byte(&mut self, byte: &mut u8) {
+ if self.position == 0 {
+ let opcode = *byte;
+ self.command = Command::from_byte(opcode);
+ *byte = 0xFF;
+
+ tracing::debug!(opcode = format!("{:02X}", opcode), "memory card command");
+
+ if self.command == Command::ClearStatus {
+ self.status &= !(MC_STATUS_PROGRAM_ERROR | MC_STATUS_ERASE_ERROR);
+ self.status |= MC_STATUS_READY;
+ self.position = 0;
+ }
+ } else {
+ match self.command {
+ Command::NintendoId => {
+ if self.position == 1 {
+ *byte = 0x80;
+ } else {
+ let shift = 24 - (((self.position - 2) & 3) * 8);
+ *byte = (self.card_id >> shift) as u8;
+ }
+ }
+ Command::ReadArray => {
+ self.accumulate_address(*byte);
+
+ if self.position == 1 {
+ *byte = 0xFF;
+ } else {
+ *byte = self.data[(self.address & self.size_mask) as usize];
+
+ if self.position >= 9 {
+ self.advance_address();
+ }
+ }
+ }
+ Command::ReadStatus => *byte = self.status,
+ Command::ReadId => {
+ *byte = if self.position == 1 || self.position & 1 == 0 {
+ (FLASH_ID >> 8) as u8
+ } else {
+ FLASH_ID as u8
+ };
+ }
+ Command::SectorErase => {
+ self.accumulate_address(*byte);
+ *byte = 0xFF;
+ }
+ Command::SetInterrupt => {
+ if self.position == 1 {
+ self.interrupt_switch = *byte;
+ }
+ *byte = 0xFF;
+ }
+ Command::PageProgram => {
+ self.accumulate_address(*byte);
+
+ if self.position >= 5 {
+ self.program_buffer[((self.position - 5) & 0x7F) as usize] = *byte;
+ }
+ *byte = 0xFF;
+ }
+ _ => *byte = 0xFF,
+ }
+ }
+
+ self.position += 1;
+ }
+
+ fn on_deselect(&mut self) -> Option<u64> {
+ match self.command {
+ Command::SectorErase if self.position > 2 => {
+ let block = (self.address & self.size_mask) & !(BLOCK_SIZE - 1);
+ let start = block as usize;
+ self.data[start..start + BLOCK_SIZE as usize].fill(0xFF);
+
+ self.status |= MC_STATUS_BUSY;
+ self.status &= !MC_STATUS_READY;
+
+ self.flush();
+ tracing::debug!(block = block / BLOCK_SIZE, "memory card sector erase");
+
+ Some(CMD_DONE_DELAY_CYCLES)
+ }
+ Command::PageProgram if self.position >= 5 => {
+ self.status &= !MC_STATUS_BUSY;
+
+ let count = self.position - 5;
+ for i in 0..count {
+ self.data[(self.address & self.size_mask) as usize] = self.program_buffer[(i & 0x7F) as usize];
+ self.advance_address();
+ }
+
+ self.flush();
+ tracing::debug!(bytes = count, "memory card page program");
+
+ Some(CMD_DONE_DELAY_CYCLES)
+ }
+ Command::ChipErase if self.position > 2 => {
+ self.data.fill(0xFF);
+ self.status &= !MC_STATUS_BUSY;
+
+ self.flush();
+ tracing::debug!("memory card chip erase");
+
+ None
+ }
+ _ => None,
+ }
+ }
+
+ fn complete_command(&mut self) -> bool {
+ self.status |= MC_STATUS_READY;
+ self.status &= !MC_STATUS_BUSY;
+ self.interrupt_switch != 0
+ }
+
+ fn dma_read(&mut self, buf: &mut [u8]) {
+ let mask = self.size_mask as usize;
+ let start = (self.address & self.size_mask) as usize;
+ for (i, b) in buf.iter_mut().enumerate() {
+ *b = self.data[(start + i) & mask];
+ }
+ }
+
+ fn dma_write(&mut self, buf: &[u8]) {
+ let mask = self.size_mask as usize;
+ let start = (self.address & self.size_mask) as usize;
+ for (i, b) in buf.iter().enumerate() {
+ self.data[(start + i) & mask] = *b;
+ }
+ self.flush();
+ }
+}
diff --git a/crates/gecko/src/system.rs b/crates/gecko/src/system.rs
index 4e91389..5239666 100644
--- a/crates/gecko/src/system.rs
+++ b/crates/gecko/src/system.rs
@@ -207,6 +207,22 @@ impl<const SYSTEM: SystemId> System<SYSTEM> {
self.gx.execution_mode = mode;
}
+ /// Attach a GameCube memory card on the given EXI channel (0 = slot A,
+ /// 1 = slot B), device slot 0. `total_blocks` sets the card size
+ /// (256 blocks = "Memory Card 251" / 2 MB card).
+ pub fn insert_memory_card(&mut self, channel: usize, path: Option<std::path::PathBuf>, total_blocks: u32) {
+ let card = crate::flipper::exi::memcard::ExiMemoryCard::new(path, total_blocks);
+ self.exi.attach_device(channel, 0, Box::new(card));
+ }
+
+ /// Back the GameCube SRAM (console settings, clock bias, memory card flash
+ /// id) with a file so it persists across runs.
+ pub fn set_sram_path(&mut self, path: std::path::PathBuf) {
+ if let Some(macronix) = self.exi.macronix_mut() {
+ macronix.set_sram_path(path);
+ }
+ }
+
/// Drain pending scheduler events, then execute one CPU instruction.
#[inline(always)]
pub fn step(&mut self) {
diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rs
index bd9fd42..45a0a9c 100644
--- a/crates/tinyapp/src/main.rs
+++ b/crates/tinyapp/src/main.rs
@@ -183,6 +183,17 @@ struct Args {
/// first presented frame until the app exits
#[arg(long)]
fifo_record: Option<String>,
+
+ /// Path to a GameCube Slot A memory card image (.raw), created blank if
+ /// missing. No card is attached unless this is given.
+ #[arg(long)]
+ memcard: Option<String>,
+
+ /// Path to a GameCube SRAM image (64 bytes), persisting console settings,
+ /// clock bias and the memory card flash id across runs. Created on first
+ /// write. The IPL boot uses an in-memory default if this is not given.
+ #[arg(long)]
+ sram: Option<String>,
}
fn main() {
@@ -289,6 +300,16 @@ fn configure<const SYSTEM: SystemId>(emulator: &mut System<SYSTEM>, args: &Args)
emulator.dsp.load_coef(&coef_data);
}
+ if SYSTEM == gecko::GC {
+ if let Some(path) = &args.memcard {
+ emulator.insert_memory_card(0, Some(std::path::PathBuf::from(path)), 256);
+ }
+
+ if let Some(path) = &args.sram {
+ emulator.set_sram_path(std::path::PathBuf::from(path));
+ }
+ }
+
#[cfg(feature = "scripting")]
if let Some(ref path) = args.script {
// Already attached for Wii apploader HLE; only attach here for other