lemur/src/emulator.rs

764 lines
24 KiB
Rust
Raw Normal View History

2024-11-03 16:32:53 +00:00
use std::{
2024-11-11 05:50:57 +00:00
collections::HashMap,
2024-12-31 02:55:30 +00:00
fmt::Display,
2024-12-07 05:00:40 +00:00
fs::{self, File},
io::{Read, Seek, SeekFrom, Write},
2024-11-04 14:59:58 +00:00
path::{Path, PathBuf},
2024-11-05 03:18:57 +00:00
sync::{
2025-01-03 03:02:51 +00:00
atomic::{AtomicBool, Ordering},
2024-11-10 21:08:49 +00:00
mpsc::{self, RecvError, TryRecvError},
Arc, Weak,
2024-11-05 03:18:57 +00:00
},
2024-11-03 16:32:53 +00:00
};
use anyhow::Result;
2025-01-03 03:02:51 +00:00
use atomic::Atomic;
use bytemuck::NoUninit;
2024-12-10 04:18:42 +00:00
use egui_toast::{Toast, ToastKind, ToastOptions};
2025-01-15 04:33:30 +00:00
use tracing::{error, warn};
2024-11-03 16:32:53 +00:00
use crate::{
audio::Audio,
graphics::TextureSink,
memory::{MemoryRange, MemoryRegion},
};
2025-01-05 05:47:58 +00:00
use shrooms_vb_core::{Sim, StopReason, EXPECTED_FRAME_SIZE};
2025-01-13 05:30:47 +00:00
pub use shrooms_vb_core::{VBKey, VBRegister, VBWatchpointType};
2024-11-11 05:50:57 +00:00
2025-01-13 05:30:47 +00:00
mod address_set;
2024-11-11 05:50:57 +00:00
mod shrooms_vb_core;
2024-11-04 14:59:58 +00:00
2024-11-11 05:50:57 +00:00
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub enum SimId {
Player1,
Player2,
}
impl SimId {
pub const fn values() -> [Self; 2] {
[Self::Player1, Self::Player2]
}
pub const fn to_index(self) -> usize {
2024-11-11 05:50:57 +00:00
match self {
Self::Player1 => 0,
Self::Player2 => 1,
}
}
}
2024-12-31 02:55:30 +00:00
impl Display for SimId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Player1 => "Player 1",
Self::Player2 => "Player 2",
})
}
}
2024-11-11 05:50:57 +00:00
2024-12-07 05:00:40 +00:00
struct Cart {
rom_path: PathBuf,
rom: Vec<u8>,
sram_file: File,
sram: Vec<u8>,
}
impl Cart {
fn load(rom_path: &Path, sim_id: SimId) -> Result<Self> {
let rom = fs::read(rom_path)?;
let mut sram_file = File::options()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(sram_path(rom_path, sim_id))?;
sram_file.set_len(8 * 1024)?;
let mut sram = vec![];
sram_file.read_to_end(&mut sram)?;
Ok(Cart {
rom_path: rom_path.to_path_buf(),
rom,
sram_file,
sram,
})
}
}
fn sram_path(rom_path: &Path, sim_id: SimId) -> PathBuf {
match sim_id {
2024-12-08 19:53:11 +00:00
SimId::Player1 => rom_path.with_extension("p1.sram"),
SimId::Player2 => rom_path.with_extension("p2.sram"),
2024-12-07 05:00:40 +00:00
}
}
2025-01-03 03:02:51 +00:00
pub struct EmulatorBuilder {
rom: Option<PathBuf>,
commands: mpsc::Receiver<EmulatorCommand>,
sim_state: Arc<[Atomic<SimState>; 2]>,
state: Arc<Atomic<EmulatorState>>,
audio_on: Arc<[AtomicBool; 2]>,
linked: Arc<AtomicBool>,
2025-01-05 16:24:59 +00:00
start_paused: bool,
2025-01-03 03:02:51 +00:00
}
2024-11-04 14:59:58 +00:00
impl EmulatorBuilder {
pub fn new() -> (Self, EmulatorClient) {
let (queue, commands) = mpsc::channel();
let builder = Self {
rom: None,
commands,
2025-01-03 03:02:51 +00:00
sim_state: Arc::new([
Atomic::new(SimState::Uninitialized),
Atomic::new(SimState::Uninitialized),
]),
state: Arc::new(Atomic::new(EmulatorState::Paused)),
2024-11-24 01:17:28 +00:00
audio_on: Arc::new([AtomicBool::new(true), AtomicBool::new(true)]),
linked: Arc::new(AtomicBool::new(false)),
2025-01-05 16:24:59 +00:00
start_paused: false,
2024-11-05 03:18:57 +00:00
};
let client = EmulatorClient {
queue,
2025-01-03 03:02:51 +00:00
sim_state: builder.sim_state.clone(),
state: builder.state.clone(),
2024-11-24 01:17:28 +00:00
audio_on: builder.audio_on.clone(),
linked: builder.linked.clone(),
2024-11-04 14:59:58 +00:00
};
(builder, client)
}
pub fn with_rom(self, path: &Path) -> Self {
Self {
rom: Some(path.into()),
..self
}
}
2025-01-05 16:24:59 +00:00
pub fn start_paused(self, paused: bool) -> Self {
Self {
start_paused: paused,
..self
}
}
2024-11-04 14:59:58 +00:00
pub fn build(self) -> Result<Emulator> {
let mut emulator = Emulator::new(
self.commands,
2025-01-03 03:02:51 +00:00
self.sim_state,
self.state,
2024-11-24 01:17:28 +00:00
self.audio_on,
self.linked,
)?;
2024-11-04 14:59:58 +00:00
if let Some(path) = self.rom {
2024-12-07 05:00:40 +00:00
emulator.load_cart(SimId::Player1, &path)?;
2024-11-04 14:59:58 +00:00
}
2025-01-05 16:24:59 +00:00
if self.start_paused {
emulator.pause_sims()?;
}
2024-11-04 14:59:58 +00:00
Ok(emulator)
}
}
2024-11-03 16:32:53 +00:00
pub struct Emulator {
2024-11-11 05:50:57 +00:00
sims: Vec<Sim>,
2024-12-07 05:00:40 +00:00
carts: [Option<Cart>; 2],
2024-11-04 14:59:58 +00:00
audio: Audio,
2024-11-03 16:32:53 +00:00
commands: mpsc::Receiver<EmulatorCommand>,
2025-01-03 03:02:51 +00:00
sim_state: Arc<[Atomic<SimState>; 2]>,
state: Arc<Atomic<EmulatorState>>,
2024-11-24 01:17:28 +00:00
audio_on: Arc<[AtomicBool; 2]>,
linked: Arc<AtomicBool>,
renderers: HashMap<SimId, TextureSink>,
2024-12-10 04:18:42 +00:00
messages: HashMap<SimId, mpsc::Sender<Toast>>,
2025-01-04 06:04:21 +00:00
debuggers: HashMap<SimId, DebugInfo>,
watched_regions: HashMap<MemoryRange, Weak<MemoryRegion>>,
2024-12-28 04:37:42 +00:00
eye_contents: Vec<u8>,
audio_samples: Vec<f32>,
buffer: Vec<u8>,
2024-11-03 16:32:53 +00:00
}
impl Emulator {
fn new(
commands: mpsc::Receiver<EmulatorCommand>,
2025-01-03 03:02:51 +00:00
sim_state: Arc<[Atomic<SimState>; 2]>,
state: Arc<Atomic<EmulatorState>>,
2024-11-24 01:17:28 +00:00
audio_on: Arc<[AtomicBool; 2]>,
linked: Arc<AtomicBool>,
) -> Result<Self> {
2024-11-04 14:59:58 +00:00
Ok(Self {
2024-11-11 05:50:57 +00:00
sims: vec![],
2024-12-07 05:00:40 +00:00
carts: [None, None],
2024-11-04 14:59:58 +00:00
audio: Audio::init()?,
commands,
2025-01-03 03:02:51 +00:00
sim_state,
state,
2024-11-24 01:17:28 +00:00
audio_on,
linked,
renderers: HashMap::new(),
2024-12-10 04:18:42 +00:00
messages: HashMap::new(),
2025-01-04 06:04:21 +00:00
debuggers: HashMap::new(),
watched_regions: HashMap::new(),
2024-12-28 04:37:42 +00:00
eye_contents: vec![0u8; 384 * 224 * 2],
2025-01-04 17:17:56 +00:00
audio_samples: Vec::with_capacity(EXPECTED_FRAME_SIZE),
buffer: vec![],
2024-11-04 14:59:58 +00:00
})
2024-11-03 16:32:53 +00:00
}
2024-12-07 05:00:40 +00:00
pub fn load_cart(&mut self, sim_id: SimId, path: &Path) -> Result<()> {
let cart = Cart::load(path, sim_id)?;
self.reset_sim(sim_id, Some(cart))?;
2024-11-11 05:50:57 +00:00
Ok(())
}
pub fn start_second_sim(&mut self, rom: Option<PathBuf>) -> Result<()> {
2024-12-07 05:00:40 +00:00
let rom_path = if let Some(path) = rom {
Some(path)
2024-11-11 05:50:57 +00:00
} else {
2024-12-07 05:00:40 +00:00
self.carts[0].as_ref().map(|c| c.rom_path.clone())
};
let cart = match rom_path {
Some(rom_path) => Some(Cart::load(&rom_path, SimId::Player2)?),
None => None,
2024-11-11 05:50:57 +00:00
};
2024-12-07 05:00:40 +00:00
self.reset_sim(SimId::Player2, cart)?;
self.link_sims();
2024-11-11 05:50:57 +00:00
Ok(())
}
2024-12-07 05:00:40 +00:00
fn reset_sim(&mut self, sim_id: SimId, new_cart: Option<Cart>) -> Result<()> {
self.save_sram(sim_id)?;
let index = sim_id.to_index();
while self.sims.len() <= index {
2024-11-11 05:50:57 +00:00
self.sims.push(Sim::new());
2025-01-03 03:02:51 +00:00
self.sim_state[index].store(SimState::NoGame, Ordering::Release);
2024-11-11 05:50:57 +00:00
}
let sim = &mut self.sims[index];
2024-11-11 05:50:57 +00:00
sim.reset();
2024-12-07 05:00:40 +00:00
if let Some(cart) = new_cart {
sim.load_cart(cart.rom.clone(), cart.sram.clone())?;
self.carts[index] = Some(cart);
2025-01-03 03:02:51 +00:00
self.sim_state[index].store(SimState::Ready, Ordering::Release);
}
2025-01-03 03:02:51 +00:00
if self.sim_state[index].load(Ordering::Acquire) == SimState::Ready {
self.resume_sims();
}
2024-11-03 16:32:53 +00:00
Ok(())
}
fn link_sims(&mut self) {
let (first, second) = self.sims.split_at_mut(1);
let Some(first) = first.first_mut() else {
return;
};
let Some(second) = second.first_mut() else {
return;
};
first.link(second);
self.linked.store(true, Ordering::Release);
}
fn unlink_sims(&mut self) {
let Some(first) = self.sims.first_mut() else {
return;
};
first.unlink();
self.linked.store(false, Ordering::Release);
}
2025-01-03 03:02:51 +00:00
fn pause_sims(&mut self) -> Result<()> {
if self
.state
.compare_exchange(
EmulatorState::Running,
EmulatorState::Paused,
Ordering::AcqRel,
Ordering::Relaxed,
)
.is_ok()
{
for sim_id in SimId::values() {
self.save_sram(sim_id)?;
}
}
Ok(())
}
fn resume_sims(&mut self) {
let _ = self.state.compare_exchange(
EmulatorState::Paused,
EmulatorState::Running,
Ordering::AcqRel,
Ordering::Relaxed,
);
}
fn save_sram(&mut self, sim_id: SimId) -> Result<()> {
2024-12-07 05:00:40 +00:00
let sim = self.sims.get_mut(sim_id.to_index());
let cart = self.carts[sim_id.to_index()].as_mut();
if let (Some(sim), Some(cart)) = (sim, cart) {
sim.read_sram(&mut cart.sram);
cart.sram_file.seek(SeekFrom::Start(0))?;
cart.sram_file.write_all(&cart.sram)?;
}
Ok(())
}
pub fn stop_second_sim(&mut self) -> Result<()> {
self.save_sram(SimId::Player2)?;
2024-11-11 05:50:57 +00:00
self.renderers.remove(&SimId::Player2);
self.sims.truncate(1);
2025-01-03 03:02:51 +00:00
self.sim_state[SimId::Player2.to_index()].store(SimState::Uninitialized, Ordering::Release);
2025-01-04 17:17:56 +00:00
self.stop_debugging(SimId::Player2);
self.linked.store(false, Ordering::Release);
Ok(())
2024-11-11 05:50:57 +00:00
}
2025-01-04 06:04:21 +00:00
fn start_debugging(&mut self, sim_id: SimId, sender: DebugSender) {
if self.sim_state[sim_id.to_index()].load(Ordering::Acquire) != SimState::Ready {
// Can't debug unless a game is connected
return;
}
2025-01-04 06:04:21 +00:00
let debug = DebugInfo {
sender,
2025-01-19 00:10:55 +00:00
stop_reason: Some(DebugStopReason::Paused),
2025-01-04 06:04:21 +00:00
};
self.debuggers.insert(sim_id, debug);
self.state
.store(EmulatorState::Debugging, Ordering::Release);
}
fn stop_debugging(&mut self, sim_id: SimId) {
2025-01-05 05:47:58 +00:00
if let Some(sim) = self.sims.get_mut(sim_id.to_index()) {
2025-01-05 18:44:59 +00:00
sim.clear_debug_state();
2025-01-05 05:47:58 +00:00
}
2025-01-04 06:04:21 +00:00
self.debuggers.remove(&sim_id);
if self.debuggers.is_empty() {
2025-01-04 17:17:56 +00:00
let _ = self.state.compare_exchange(
EmulatorState::Debugging,
EmulatorState::Running,
Ordering::AcqRel,
Ordering::Relaxed,
);
2025-01-04 06:04:21 +00:00
}
}
fn debug_interrupt(&mut self, sim_id: SimId) {
2025-01-19 00:10:55 +00:00
self.debug_stop(sim_id, DebugStopReason::Paused);
2025-01-05 05:47:58 +00:00
}
fn debug_stop(&mut self, sim_id: SimId, reason: DebugStopReason) {
2025-01-04 06:04:21 +00:00
let Some(debugger) = self.debuggers.get_mut(&sim_id) else {
self.stop_debugging(sim_id);
return;
};
2025-01-05 05:47:58 +00:00
if debugger.stop_reason != Some(reason) {
debugger.stop_reason = Some(reason);
if debugger.sender.send(DebugEvent::Stopped(reason)).is_err() {
2025-01-04 06:04:21 +00:00
self.stop_debugging(sim_id);
}
}
}
2025-01-05 18:44:59 +00:00
fn debug_continue(&mut self, sim_id: SimId) -> bool {
2025-01-04 06:04:21 +00:00
let Some(debugger) = self.debuggers.get_mut(&sim_id) else {
self.stop_debugging(sim_id);
2025-01-05 18:44:59 +00:00
return false;
2025-01-04 06:04:21 +00:00
};
debugger.stop_reason = None;
2025-01-05 18:44:59 +00:00
true
}
fn debug_step(&mut self, sim_id: SimId) {
if self.debug_continue(sim_id) {
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
return;
};
sim.step();
}
2025-01-04 06:04:21 +00:00
}
fn watch_memory(&mut self, range: MemoryRange, region: Weak<MemoryRegion>) {
self.watched_regions.insert(range, region);
}
2024-11-03 16:32:53 +00:00
pub fn run(&mut self) {
loop {
2024-12-28 04:37:42 +00:00
let idle = self.tick();
2024-11-10 21:08:49 +00:00
if idle {
// The game is paused, and we have output all the video/audio we have.
// Block the thread until a new command comes in.
match self.commands.recv() {
Ok(command) => self.handle_command(command),
Err(RecvError) => {
return;
}
}
}
2024-11-03 16:32:53 +00:00
loop {
match self.commands.try_recv() {
Ok(command) => self.handle_command(command),
Err(TryRecvError::Empty) => {
break;
}
Err(TryRecvError::Disconnected) => {
return;
}
}
}
self.watched_regions.retain(|range, region| {
let Some(region) = region.upgrade() else {
return false;
};
let Some(sim) = self.sims.get_mut(range.sim.to_index()) else {
return false;
};
self.buffer.clear();
sim.read_memory(range.start, range.length, &mut self.buffer);
region.update(&self.buffer);
true
});
2024-11-03 16:32:53 +00:00
}
}
2024-12-28 04:37:42 +00:00
// returns true if the emulator is "idle" (i.e. this didn't output anything)
pub fn tick(&mut self) -> bool {
2025-01-03 03:02:51 +00:00
let p1_state = self.sim_state[SimId::Player1.to_index()].load(Ordering::Acquire);
let p2_state = self.sim_state[SimId::Player2.to_index()].load(Ordering::Acquire);
let state = self.state.load(Ordering::Acquire);
2025-01-04 17:17:56 +00:00
// Emulation
2025-01-04 06:04:21 +00:00
// Don't emulate if the state is "paused", or if any sim is paused in the debugger
let running = match state {
EmulatorState::Paused => false,
EmulatorState::Running => true,
EmulatorState::Debugging => self.debuggers.values().all(|d| d.stop_reason.is_none()),
};
let p1_running = running && p1_state == SimState::Ready;
let p2_running = running && p2_state == SimState::Ready;
2025-01-03 03:02:51 +00:00
let mut idle = !p1_running && !p2_running;
2024-12-28 04:37:42 +00:00
if p1_running && p2_running {
Sim::emulate_many(&mut self.sims);
} else if p1_running {
self.sims[SimId::Player1.to_index()].emulate();
} else if p2_running {
self.sims[SimId::Player2.to_index()].emulate();
}
2025-01-05 05:47:58 +00:00
// Debug state
if state == EmulatorState::Debugging {
for sim_id in SimId::values() {
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
continue;
};
if let Some(reason) = sim.stop_reason() {
let stop_reason = match reason {
2025-01-05 18:44:59 +00:00
StopReason::Stepped => DebugStopReason::Trace,
2025-01-13 05:30:47 +00:00
StopReason::Watchpoint(watch, address) => {
DebugStopReason::Watchpoint(watch, address)
}
2025-01-05 05:47:58 +00:00
StopReason::Breakpoint => DebugStopReason::Breakpoint,
};
self.debug_stop(sim_id, stop_reason);
}
}
}
2025-01-04 17:17:56 +00:00
// Video
2024-12-28 04:37:42 +00:00
for sim_id in SimId::values() {
let Some(renderer) = self.renderers.get_mut(&sim_id) else {
continue;
};
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
continue;
};
if sim.read_pixels(&mut self.eye_contents) {
idle = false;
if renderer.queue_render(&self.eye_contents).is_err() {
self.renderers.remove(&sim_id);
}
}
}
2025-01-04 17:17:56 +00:00
// Audio
// Audio playback speed is how we keep the emulator running in real time.
// Even if we're muted, call `read_samples` to know how many frames of silence to play.
2024-12-28 04:37:42 +00:00
let p1_audio =
p1_running && self.audio_on[SimId::Player1.to_index()].load(Ordering::Acquire);
let p2_audio =
p2_running && self.audio_on[SimId::Player2.to_index()].load(Ordering::Acquire);
2025-01-04 17:17:56 +00:00
let (p1_weight, p2_weight) = match (p1_audio, p2_audio) {
(true, true) => (0.5, 0.5),
(true, false) => (1.0, 0.0),
(false, true) => (0.0, 1.0),
(false, false) => (0.0, 0.0),
};
if let Some(sim) = self.sims.get_mut(SimId::Player1.to_index()) {
sim.read_samples(&mut self.audio_samples, p1_weight);
2024-12-28 04:37:42 +00:00
}
2025-01-04 17:17:56 +00:00
if let Some(sim) = self.sims.get_mut(SimId::Player2.to_index()) {
sim.read_samples(&mut self.audio_samples, p2_weight);
2024-12-28 04:37:42 +00:00
}
2025-01-04 17:17:56 +00:00
if !self.audio_samples.is_empty() {
2024-12-28 04:37:42 +00:00
idle = false;
}
self.audio.update(&self.audio_samples);
self.audio_samples.clear();
idle
}
2024-11-03 16:32:53 +00:00
fn handle_command(&mut self, command: EmulatorCommand) {
match command {
2024-12-10 04:18:42 +00:00
EmulatorCommand::ConnectToSim(sim_id, renderer, messages) => {
2024-11-11 05:50:57 +00:00
self.renderers.insert(sim_id, renderer);
2024-12-10 04:18:42 +00:00
self.messages.insert(sim_id, messages);
2024-11-03 16:32:53 +00:00
}
2024-11-11 05:50:57 +00:00
EmulatorCommand::LoadGame(sim_id, path) => {
2024-12-07 05:00:40 +00:00
if let Err(error) = self.load_cart(sim_id, &path) {
2024-12-10 04:18:42 +00:00
self.report_error(sim_id, format!("Error loading rom: {error}"));
2024-11-05 03:18:57 +00:00
}
}
2024-11-11 05:50:57 +00:00
EmulatorCommand::StartSecondSim(path) => {
if let Err(error) = self.start_second_sim(path) {
2024-12-10 04:18:42 +00:00
self.report_error(
SimId::Player2,
format!("Error starting second sim: {error}"),
);
2024-11-11 05:50:57 +00:00
}
}
EmulatorCommand::StopSecondSim => {
if let Err(error) = self.stop_second_sim() {
2024-12-10 04:18:42 +00:00
self.report_error(
SimId::Player2,
format!("Error stopping second sim: {error}"),
);
}
2024-11-11 05:50:57 +00:00
}
2024-11-05 03:18:57 +00:00
EmulatorCommand::Pause => {
2025-01-03 03:02:51 +00:00
if let Err(error) = self.pause_sims() {
self.report_error(SimId::Player1, format!("Error pausing: {error}"));
}
2024-11-05 03:18:57 +00:00
}
EmulatorCommand::Resume => {
2025-01-03 03:02:51 +00:00
self.resume_sims();
2024-11-05 03:18:57 +00:00
}
2025-01-04 06:04:21 +00:00
EmulatorCommand::StartDebugging(sim_id, debugger) => {
self.start_debugging(sim_id, debugger);
}
EmulatorCommand::StopDebugging(sim_id) => {
self.stop_debugging(sim_id);
}
EmulatorCommand::DebugInterrupt(sim_id) => {
self.debug_interrupt(sim_id);
}
EmulatorCommand::DebugContinue(sim_id) => {
self.debug_continue(sim_id);
}
2025-01-05 18:44:59 +00:00
EmulatorCommand::DebugStep(sim_id) => {
self.debug_step(sim_id);
}
2025-01-02 02:48:33 +00:00
EmulatorCommand::ReadRegister(sim_id, register, done) => {
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
return;
};
let value = sim.read_register(register);
let _ = done.send(value);
}
2025-01-18 05:20:57 +00:00
EmulatorCommand::WriteRegister(sim_id, register, value) => {
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
return;
};
sim.write_register(register, value);
}
EmulatorCommand::ReadMemory(sim_id, start, length, mut buffer, done) => {
2025-01-02 06:10:19 +00:00
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
return;
};
sim.read_memory(start, length, &mut buffer);
2025-01-02 06:10:19 +00:00
let _ = done.send(buffer);
}
2025-01-18 06:03:22 +00:00
EmulatorCommand::WriteMemory(sim_id, start, buffer, done) => {
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
return;
};
sim.write_memory(start, &buffer);
let _ = done.send(buffer);
}
EmulatorCommand::WatchMemory(range, region) => {
self.watch_memory(range, region);
}
2025-01-05 05:47:58 +00:00
EmulatorCommand::AddBreakpoint(sim_id, address) => {
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
return;
};
sim.add_breakpoint(address);
}
EmulatorCommand::RemoveBreakpoint(sim_id, address) => {
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
return;
};
sim.remove_breakpoint(address);
}
2025-01-13 05:30:47 +00:00
EmulatorCommand::AddWatchpoint(sim_id, address, length, watch) => {
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
return;
};
sim.add_watchpoint(address, length, watch);
}
EmulatorCommand::RemoveWatchpoint(sim_id, address, length, watch) => {
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
return;
};
sim.remove_watchpoint(address, length, watch);
}
2024-11-24 01:17:28 +00:00
EmulatorCommand::SetAudioEnabled(p1, p2) => {
self.audio_on[SimId::Player1.to_index()].store(p1, Ordering::Release);
self.audio_on[SimId::Player2.to_index()].store(p2, Ordering::Release);
}
EmulatorCommand::Link => {
self.link_sims();
}
EmulatorCommand::Unlink => {
self.unlink_sims();
}
EmulatorCommand::Reset(sim_id) => {
if let Err(error) = self.reset_sim(sim_id, None) {
2024-12-10 04:18:42 +00:00
self.report_error(sim_id, format!("Error resetting sim: {error}"));
2024-11-11 05:50:57 +00:00
}
2024-11-05 03:18:57 +00:00
}
2024-11-11 05:50:57 +00:00
EmulatorCommand::SetKeys(sim_id, keys) => {
if let Some(sim) = self.sims.get_mut(sim_id.to_index()) {
sim.set_keys(keys);
}
2024-11-03 16:32:53 +00:00
}
EmulatorCommand::Exit(done) => {
for sim_id in SimId::values() {
if let Err(error) = self.save_sram(sim_id) {
2024-12-10 04:18:42 +00:00
self.report_error(sim_id, format!("Error saving sram on exit: {error}"));
}
}
let _ = done.send(());
}
2024-11-03 16:32:53 +00:00
}
}
2024-12-10 04:18:42 +00:00
fn report_error(&self, sim_id: SimId, message: String) {
let messages = self
.messages
.get(&sim_id)
.or_else(|| self.messages.get(&SimId::Player1));
if let Some(msg) = messages {
let toast = Toast::new()
.kind(ToastKind::Error)
.options(ToastOptions::default().duration_in_seconds(5.0))
.text(&message);
if msg.send(toast).is_ok() {
return;
}
}
2025-01-15 04:33:30 +00:00
error!("{}", message);
2024-12-10 04:18:42 +00:00
}
2024-11-03 16:32:53 +00:00
}
#[derive(Debug)]
pub enum EmulatorCommand {
2024-12-10 04:18:42 +00:00
ConnectToSim(SimId, TextureSink, mpsc::Sender<Toast>),
2024-11-11 05:50:57 +00:00
LoadGame(SimId, PathBuf),
StartSecondSim(Option<PathBuf>),
StopSecondSim,
2024-11-05 03:18:57 +00:00
Pause,
Resume,
2025-01-04 06:04:21 +00:00
StartDebugging(SimId, DebugSender),
StopDebugging(SimId),
DebugInterrupt(SimId),
DebugContinue(SimId),
2025-01-05 18:44:59 +00:00
DebugStep(SimId),
2025-01-02 02:48:33 +00:00
ReadRegister(SimId, VBRegister, oneshot::Sender<u32>),
2025-01-18 05:20:57 +00:00
WriteRegister(SimId, VBRegister, u32),
ReadMemory(SimId, u32, usize, Vec<u8>, oneshot::Sender<Vec<u8>>),
2025-01-18 06:03:22 +00:00
WriteMemory(SimId, u32, Vec<u8>, oneshot::Sender<Vec<u8>>),
WatchMemory(MemoryRange, Weak<MemoryRegion>),
2025-01-05 05:47:58 +00:00
AddBreakpoint(SimId, u32),
RemoveBreakpoint(SimId, u32),
2025-01-13 05:30:47 +00:00
AddWatchpoint(SimId, u32, usize, VBWatchpointType),
RemoveWatchpoint(SimId, u32, usize, VBWatchpointType),
2024-11-24 01:17:28 +00:00
SetAudioEnabled(bool, bool),
Link,
Unlink,
Reset(SimId),
2024-11-11 05:50:57 +00:00
SetKeys(SimId, VBKey),
Exit(oneshot::Sender<()>),
2024-11-03 16:32:53 +00:00
}
2025-01-03 03:02:51 +00:00
#[derive(Clone, Copy, Debug, PartialEq, Eq, NoUninit)]
#[repr(usize)]
pub enum SimState {
Uninitialized,
NoGame,
Ready,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, NoUninit)]
#[repr(usize)]
pub enum EmulatorState {
Paused,
Running,
2025-01-04 06:04:21 +00:00
Debugging,
}
type DebugSender = tokio::sync::mpsc::UnboundedSender<DebugEvent>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DebugStopReason {
2025-01-05 18:44:59 +00:00
// We are stepping
Trace,
2025-01-05 05:47:58 +00:00
// We hit a breakpoint
Breakpoint,
2025-01-13 05:30:47 +00:00
// We hit a watchpoint
Watchpoint(VBWatchpointType, u32),
2025-01-04 06:04:21 +00:00
// The debugger told us to pause
2025-01-19 00:10:55 +00:00
Paused,
2025-01-04 06:04:21 +00:00
}
struct DebugInfo {
sender: DebugSender,
stop_reason: Option<DebugStopReason>,
}
pub enum DebugEvent {
Stopped(DebugStopReason),
2025-01-03 03:02:51 +00:00
}
#[derive(Clone)]
2024-11-03 16:32:53 +00:00
pub struct EmulatorClient {
queue: mpsc::Sender<EmulatorCommand>,
2025-01-03 03:02:51 +00:00
sim_state: Arc<[Atomic<SimState>; 2]>,
state: Arc<Atomic<EmulatorState>>,
2024-11-24 01:17:28 +00:00
audio_on: Arc<[AtomicBool; 2]>,
linked: Arc<AtomicBool>,
2024-11-03 16:32:53 +00:00
}
impl EmulatorClient {
2025-01-03 03:02:51 +00:00
pub fn sim_state(&self, sim_id: SimId) -> SimState {
self.sim_state[sim_id.to_index()].load(Ordering::Acquire)
}
2025-01-03 03:02:51 +00:00
pub fn emulator_state(&self) -> EmulatorState {
self.state.load(Ordering::Acquire)
}
2025-01-03 03:02:51 +00:00
pub fn is_audio_enabled(&self, sim_id: SimId) -> bool {
self.audio_on[sim_id.to_index()].load(Ordering::Acquire)
2024-11-05 03:18:57 +00:00
}
pub fn are_sims_linked(&self) -> bool {
self.linked.load(Ordering::Acquire)
}
pub fn send_command(&self, command: EmulatorCommand) -> bool {
match self.queue.send(command) {
Ok(()) => true,
Err(err) => {
2025-01-15 04:33:30 +00:00
warn!(
"could not send command {:?} as emulator is shut down",
err.0
);
false
}
2024-11-03 16:32:53 +00:00
}
}
}