// SPDX-License-Identifier: MIT //! Save states of the whole machine: the Mega Drive (megadrive-rust's own state) and the //! 32X (both SH-2s, the 32X's registers, VDP, PWM, composite, and the rows the composite //! handed the Mega Drive's renderer), between two of the 68000's steps. //! //! The reference's `savestate.py` pickles the whole object graph; Rust has no such thing, //! so the state is written field by field (what Rust forced). What a state holds is //! everything that changes as the machine runs; what it does not hold is wiring, taken //! from the system it is loaded into: the models and quirks, the boot ROMs and the //! cartridge (named by SHA-1 and checked), the socket objects. A state holds no ROM or //! BIOS bytes. The formats are not shared with the reference's (the famicom line's //! precedent, as megadrive-rust's): the rung that proves a state is //! `scripts/state_rung.py` (save, load into a fresh machine, continue: identical to the //! uninterrupted run, and so to the reference's). //! //! Not in the reference's sense of a state, and not held: the composite's map cache //! (`Composite::maps`, recomputed to the same values) and the lockstep's bus CRCs. use std::sync::{Arc, Mutex}; use megadrive_rust::render::PictureSide; use megadrive_rust::sockets::{PictureLine, PictureRow}; use megadrive_rust::vdp::HName; use megadrive_rust::System; use serde::{Deserialize, Serialize}; use sh2::{ChipState, Pins}; use crate::bootrom::BootROMs; use crate::composite::Composite; use crate::console::Shared; use crate::pwm::PWM; use crate::sh2side::SH2Side; use crate::slot::Sega32X; use crate::vdp::VDP32X; pub const MAGIC: &[u8] = b"sega32x-rust state\n"; /// Raised when what a state holds changes meaning; a state of another version is refused. pub const VERSION: u32 = 1; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub struct Header { pub version: u32, pub rom_sha1: String, pub boot_sha1: [String; 3], pub machine: String, pub model: String, pub frame: u64, } /// A chip: sh2-rust's `ChipState` (names as strings), its pins and its wait. #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Chip { pub r: [u32; 16], pub sr: u32, pub gbr: u32, pub vbr: u32, pub mach: u32, pub macl: u32, pub pr: u32, pub pc: u32, pub delay_target: i64, pub sleeping: bool, pub no_interrupt: bool, pub address_error: bool, pub nmi_pending: bool, pub clock: i64, pub pipeline: Vec, pub modules: Vec<(String, Vec<(String, i64)>)>, pub dma_address_error: bool, pub internal: Vec<(String, Vec)>, pub pins: [u32; 6], pub wait: i64, } impl Chip { fn from(state: &ChipState, pins: Pins, wait: i64) -> Chip { Chip { r: state.r, sr: state.sr, gbr: state.gbr, vbr: state.vbr, mach: state.mach, macl: state.macl, pr: state.pr, pc: state.pc, delay_target: state.delay_target, sleeping: state.sleeping, no_interrupt: state.no_interrupt, address_error: state.address_error, nmi_pending: state.nmi_pending, clock: state.clock, pipeline: state.pipeline.clone(), modules: state .modules .iter() .map(|(name, values)| (name.to_string(), values.iter().map(|(k, v)| (k.to_string(), *v)).collect())) .collect(), dma_address_error: state.dma_address_error, internal: state.internal.iter().map(|(name, values)| (name.to_string(), values.clone())).collect(), pins: [pins.irl, pins.nmi, pins.dreq0, pins.dreq1, pins.ftci, pins.fti], wait, } } /// The `ChipState`, its names the live chip's own (`template`, a capture of it). fn to_state(&self, template: &ChipState) -> Result { let name = |names: Vec<&'static str>, wanted: &str| -> Result<&'static str, String> { names.into_iter().find(|n| *n == wanted).ok_or(format!("a state of a chip without {wanted}")) }; let mut modules = Vec::new(); for (module, values) in &self.modules { let live = template.modules.iter().find(|(n, _)| n == module).ok_or(format!("no module {module}"))?; let mut out = Vec::new(); for (key, value) in values { out.push((name(live.1.iter().map(|(k, _)| *k).collect(), key)?, *value)); } modules.push((live.0, out)); } let mut internal = Vec::new(); for (module, values) in &self.internal { let mut names: Vec<&'static str> = vec!["chip"]; names.extend(template.modules.iter().map(|(n, _)| *n)); let live = name(names, module)?; internal.push((live, values.clone())); } Ok(ChipState { r: self.r, sr: self.sr, gbr: self.gbr, vbr: self.vbr, mach: self.mach, macl: self.macl, pr: self.pr, pc: self.pc, delay_target: self.delay_target, sleeping: self.sleeping, no_interrupt: self.no_interrupt, address_error: self.address_error, nmi_pending: self.nmi_pending, clock: self.clock, pipeline: self.pipeline.clone(), modules, dma_address_error: self.dma_address_error, internal, }) } fn pins(&self) -> Pins { let [irl, nmi, dreq0, dreq1, ftci, fti] = self.pins; Pins { irl, nmi, dreq0, dreq1, ftci, fti } } } /// The SH-2 side but its chips' wiring. #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Side { pub sdram: Vec, pub chips: Vec, pub skew: [i64; 2], pub time: i64, pub running: bool, pub pending: [u32; 2], pub masks: [u32; 2], pub ftoa: [u32; 2], pub rv_blocked: [bool; 2], pub instructions: [u64; 2], pub unmapped: Vec<(usize, u32, u32)>, pub bus_owner: usize, pub bus_start: i64, pub bus_until: i64, pub last: [(i64, u32, u32, bool); 2], pub access_start: [i64; 2], pub fb_fifo: Vec, pub cart_sh2: (i64, i64), pub cart_m68k: (i64, i64), } /// A socket-7 line (megadrive-rust's `PictureLine`). #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Line { pub row: usize, pub start: i64, pub h40: bool, pub width: usize, pub pixel_mclk: i64, pub display_at: i64, pub output_delay: i64, pub rgb: Vec, pub ys: Vec, pub shade: Vec, } impl Line { fn from(line: &PictureLine) -> Line { Line { row: line.row, start: line.start, h40: line.hmode == HName::H40, width: line.width, pixel_mclk: line.pixel_mclk, display_at: line.display_at, output_delay: line.output_delay, rgb: line.rgb.clone(), ys: line.ys.clone(), shade: line.shade.clone(), } } fn to_line(&self) -> PictureLine { PictureLine { row: self.row, start: self.start, hmode: if self.h40 { HName::H40 } else { HName::H32 }, width: self.width, pixel_mclk: self.pixel_mclk, display_at: self.display_at, output_delay: self.output_delay, rgb: self.rgb.clone(), ys: self.ys.clone(), shade: self.shade.clone(), } } } /// The composite, its returned rows by number in [`Device::rows`]. #[derive(Serialize, Deserialize, Clone, Debug)] pub struct CompositeState { pub drawn: Vec<(i64, (Option>, u16))>, pub pending: Vec<(i64, (Line, usize))>, pub composed: u64, } /// Everything of the 32X that runs, and the renderer's rows the device returned. #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Device { pub has_cartridge: bool, pub mclk_hz: i64, pub clock: i64, pub pending: Option, pub master: u8, pub peeking: bool, pub dma: bool, pub sh2: Option, pub pwm: PWM, pub adapter: u16, pub interrupt_control: u16, pub bank: u16, pub dreq_control: u16, pub dreq_source: u32, pub dreq_destination: u32, pub dreq_length: u16, pub fifo_last: u16, pub sega_tv: u16, pub comm: [u16; 8], pub hint_vector: u32, pub framebuffers: [Vec; 2], pub vdp: VDP32X, pub composite: Option, pub fifo: Vec, pub standby: u16, pub hcount: u16, pub hen: bool, pub button_with_rv: bool, /// Every row shared between the renderer and the composite, once each. pub rows: Vec>, pub handing: Option<(usize, i64, usize, u8)>, pub ys: Vec, pub renderer_rows: Vec>, pub renderer_done_rows: Vec>, /// The mixer's resampling of the further sound sources (socket 8: the PWM), which the /// board's state leaves to the device (`AudioPath::source_side`). pub audio_sources: Vec<(usize, Vec<(f64, f64)>, f64)>, } /// The shared rows, numbered once each (by the row itself, as the reference's pickle /// keeps one object once). struct Rows { rows: Vec, } impl Rows { fn number(&mut self, row: &PictureRow) -> usize { if let Some(index) = self.rows.iter().position(|r| Arc::ptr_eq(r, row)) { return index; } self.rows.push(row.clone()); self.rows.len() - 1 } } fn capture_device(d: &mut Sega32X, system: &mut System) -> Device { let side_present = d.sh2.is_some(); let chips: Vec = if side_present { (0..2) .map(|index| { let state = d.sh2_with_chip(index, &mut system.board().dev, |chip| chip.capture_state()); let chip = d.sh2.as_ref().expect("the side").chip_ref(index); Chip::from(&state, chip.pins(), chip.wait) }) .collect() } else { Vec::new() }; let sh2 = d.sh2.as_ref().map(|s: &SH2Side| Side { sdram: s.sdram.clone(), chips, skew: s.skew, time: s.time, running: s.running, pending: s.pending, masks: s.masks, ftoa: s.ftoa, rv_blocked: s.rv_blocked, instructions: s.instructions, unmapped: s.unmapped.clone(), bus_owner: s.bus_owner, bus_start: s.bus_start, bus_until: s.bus_until, last: s.last, access_start: s.access_start, fb_fifo: s.fb_fifo.clone(), cart_sh2: s.cart_sh2, cart_m68k: s.cart_m68k, }); let side = system.board().vdp.renderer.picture_side(); let mut rows = Rows { rows: Vec::new() }; let renderer_rows = side.composite.iter().map(|r| r.as_ref().map(|r| rows.number(r))).collect(); let renderer_done_rows = side.done_composite.iter().map(|r| r.as_ref().map(|r| rows.number(r))).collect(); let composite = d.composite.as_ref().map(|c| CompositeState { drawn: c.drawn.clone(), pending: c.pending.iter().map(|(start, (line, row))| (*start, (Line::from(line), rows.number(row)))).collect(), composed: c.composed, }); Device { has_cartridge: d.has_cartridge, mclk_hz: d.mclk_hz, clock: d.clock, pending: d.pending, master: d.master, peeking: d.peeking, dma: d.dma, sh2, pwm: d.pwm.clone(), adapter: d.adapter, interrupt_control: d.interrupt_control, bank: d.bank, dreq_control: d.dreq_control, dreq_source: d.dreq_source, dreq_destination: d.dreq_destination, dreq_length: d.dreq_length, fifo_last: d.fifo_last, sega_tv: d.sega_tv, comm: d.comm, hint_vector: d.hint_vector, framebuffers: d.framebuffers.clone(), vdp: d.vdp.clone(), composite, fifo: d.fifo.clone(), standby: d.standby, hcount: d.hcount, hen: d.hen, button_with_rv: d.button_with_rv, rows: rows.rows.iter().map(|r| r.lock().expect("a row").clone()).collect(), handing: side.handing, ys: side.ys, renderer_rows, renderer_done_rows, audio_sources: system.audio.source_side(), } } fn restore_device(d: &mut Sega32X, system: &mut System, s: Device) -> Result<(), String> { if s.has_cartridge != d.has_cartridge || s.sh2.is_some() != d.sh2.is_some() { return Err("a state of a 32X wired otherwise".into()); } let rows: Vec = s.rows.into_iter().map(|r| Arc::new(Mutex::new(r))).collect(); d.mclk_hz = s.mclk_hz; d.clock = s.clock; d.pending = s.pending; d.master = s.master; d.peeking = s.peeking; d.dma = s.dma; d.pwm = s.pwm; d.adapter = s.adapter; d.interrupt_control = s.interrupt_control; d.bank = s.bank; d.dreq_control = s.dreq_control; d.dreq_source = s.dreq_source; d.dreq_destination = s.dreq_destination; d.dreq_length = s.dreq_length; d.fifo_last = s.fifo_last; d.sega_tv = s.sega_tv; d.comm = s.comm; d.hint_vector = s.hint_vector; d.framebuffers = s.framebuffers; let quirks = d.machine.quirks; d.vdp = s.vdp; d.vdp.quirks = Some(quirks); d.composite = s.composite.map(|c| { let mut composite = Composite::new(&quirks); composite.drawn = c.drawn; composite.pending = c.pending.into_iter().map(|(start, (line, row))| (start, (line.to_line(), rows[row].clone()))).collect(); composite.composed = c.composed; composite }); d.fifo = s.fifo; d.standby = s.standby; d.hcount = s.hcount; d.hen = s.hen; d.button_with_rv = s.button_with_rv; if let Some(side) = s.sh2 { { let live = d.sh2.as_mut().expect("the side"); live.sdram = side.sdram; live.skew = side.skew; live.time = side.time; live.running = side.running; live.pending = side.pending; live.masks = side.masks; live.ftoa = side.ftoa; live.rv_blocked = side.rv_blocked; live.instructions = side.instructions; live.unmapped = side.unmapped; live.bus_owner = side.bus_owner; live.bus_start = side.bus_start; live.bus_until = side.bus_until; live.last = side.last; live.access_start = side.access_start; live.fb_fifo = side.fb_fifo; live.cart_sh2 = side.cart_sh2; live.cart_m68k = side.cart_m68k; } for (index, chip) in side.chips.iter().enumerate() { let template = d.sh2_with_chip(index, &mut system.board().dev, |c| c.capture_state()); let state = chip.to_state(&template)?; let pins = chip.pins(); let wait = chip.wait; d.sh2_with_chip(index, &mut system.board().dev, |c| { c.set_pins(pins); c.wait = wait; c.restore_state(&state); c.set_pins(pins); c.wait = wait; }); } } let mut side: PictureSide = system.board().vdp.renderer.picture_side(); side.handing = s.handing; side.ys = s.ys; side.composite = s.renderer_rows.into_iter().map(|r| r.map(|i| rows[i].clone())).collect(); side.done_composite = s.renderer_done_rows.into_iter().map(|r| r.map(|i| rows[i].clone())).collect(); system.board().vdp.renderer.set_picture_side(side); system.audio.set_source_side(s.audio_sources); Ok(()) } fn header(system: &System, image_sha1: &str, boot: &BootROMs, machine: &str, model: &str, frame: u64) -> Header { let _ = system; let sha = |bytes: &[u8]| sha1_smol::Sha1::from(bytes).digest().to_string(); Header { version: VERSION, rom_sha1: image_sha1.to_string(), boot_sha1: [sha(&boot.m68k), sha(&boot.master), sha(&boot.slave)], machine: machine.to_string(), model: model.to_string(), frame, } } /// The state of `system` with `device` in its slot, between two 68000 steps. pub fn save( system: &mut System, device: &Shared, image_sha1: &str, boot: &BootROMs, machine: &str, model: &str, frame: u64, ) -> Vec { let md = megadrive_rust::state::save_state(system); let dev = { let mut d = device.lock().expect("the 32X"); capture_device(&mut d, system) }; let mut out = MAGIC.to_vec(); out.extend(bincode::serialize(&header(system, image_sha1, boot, machine, model, frame)).expect("a header")); out.extend(bincode::serialize(&(md, dev)).expect("a body")); out } /// Load a state into `system` (built fresh with `console::build` from the same /// cartridge, boot ROMs, machine and model); its frame count. pub fn load( system: &mut System, device: &Shared, data: &[u8], image_sha1: &str, boot: &BootROMs, machine: &str, model: &str, ) -> Result { if data.len() < MAGIC.len() || &data[..MAGIC.len()] != MAGIC { return Err("not a sega32x-rust save state".into()); } let mut rest = &data[MAGIC.len()..]; let saved: Header = bincode::deserialize_from(&mut rest).map_err(|e| format!("a damaged header: {e}"))?; let live = header(system, image_sha1, boot, machine, model, saved.frame); if saved != live { return Err(format!("the state was made from another machine: {saved:?}")); } let (md, dev): (Vec, Device) = bincode::deserialize_from(&mut rest).map_err(|e| format!("a damaged body: {e}"))?; megadrive_rust::state::load_state(system, &md)?; { let mut d = device.lock().expect("the 32X"); restore_device(&mut d, system, dev)?; } // The board's page table is wiring (megadrive-rust's state takes it from the system // loaded into): read the restored device's claims again (ADEN, RV). system.board().dev.update_claims(); Ok(saved.frame) }