//! Galaxian on the certified core: galemu transcribed. pub mod board; pub mod bytes; pub mod roms; pub mod sound; pub mod trace; pub mod video; use board::{Machine, MachineState}; use roms::RomSet; use sound::{sound_events, SoundState, SAMPLES_PER_FRAME}; use video::{Assets, Frame, View}; /// The game at a frame boundary, for rewind: the machine and the sound. #[derive(Clone, Debug, PartialEq)] pub struct Snapshot { machine: MachineState, sound: SoundState, } impl Snapshot { /// The snapshot as bytes (a save state's body: the machine, then the /// sound). The wrapper puts a format version in front. pub fn to_bytes(&self) -> Vec { let mut w = bytes::Writer::default(); self.machine.write(&mut w); self.sound.write(&mut w); w.out } /// Back from [`Snapshot::to_bytes`]; refused if the bytes are not exactly one. pub fn from_bytes(data: &[u8]) -> Result { let mut r = bytes::Reader::new(data); let machine = MachineState::read(&mut r)?; let sound = SoundState::read(&mut r)?; r.finish()?; Ok(Snapshot { machine, sound }) } } /// A loaded, verified board with its decoded video assets and sound state. pub struct Galaxian { pub machine: Machine, pub assets: Assets, pub frame: Frame, pub sound: SoundState, pub pcm: [i16; SAMPLES_PER_FRAME], } impl Galaxian { pub fn new(roms: &RomSet, enable_vblank: bool) -> Result { Ok(Galaxian { machine: Machine::new(&roms.program, enable_vblank)?, assets: Assets::new(&roms.graphics, &roms.palette)?, frame: Frame::new(), sound: SoundState::default(), pcm: [0; SAMPLES_PER_FRAME], }) } /// One frame as the display runs it: the ROM to the next vblank, the /// frame's sound writes into 792 samples, the frame composed. The /// board's events are consumed. pub fn run_frame(&mut self) -> Result<(), String> { self.machine.run_frame().map_err(|f| f.to_string())?; let events = std::mem::take(&mut self.machine.board_mut().events); self.sound .synthesize_frame(&sound_events(&events), &mut self.pcm); self.compose(); Ok(()) } pub fn snapshot(&self) -> Snapshot { Snapshot { machine: self.machine.capture(), sound: self.sound.clone(), } } /// Back to a snapshot: the run goes on as it did from there. The frame is /// composed again and the sound of the frame is silence. pub fn restore(&mut self, snapshot: &Snapshot) { self.machine.restore(&snapshot.machine); self.sound = snapshot.sound.clone(); self.pcm = [0; SAMPLES_PER_FRAME]; self.compose(); } /// Compose the current frame from the board's video memory. pub fn compose(&mut self) { let board = self.machine.board(); self.frame.compose( &self.assets, &View { video_ram: &board.video_ram, object_ram: &board.object_ram, starfield_enabled: board.starfield_enabled, flip_x: board.flip_x, flip_y: board.flip_y, scroll: self.machine.vblank_count as u32, }, ); } }