1use pcengine_rust::machine::{PC_ENGINE, TURBOGRAFX_16};
12use pcengine_rust::pads::{self, Pad2};
13use pcengine_rust::sockets::ResetKind;
14use pcengine_rust::system::System;
15use pcengine_rust::trace::{held, parse_press, Press};
16use sha1::{Digest, Sha1};
17
18use crate::board::{unit, CdSwitches, PcEngineCd};
19use crate::disc::Disc;
20
21#[derive(Clone, Debug)]
24pub struct Setup {
25 pub card: Vec<u8>,
27 pub disc: Option<String>,
29 pub arcade: bool,
30 pub frames: i64,
31 pub presses: Vec<Press>,
32 pub machine: String,
33 pub super_system_card: Option<bool>,
34 pub region_us: bool,
35 pub bram: Option<Vec<u8>>,
36 pub switches: CdSwitches,
37 pub resets: Vec<(i64, ResetKind)>,
39 pub detail: Option<i64>,
40 pub out: Option<String>,
41 pub rest: Vec<String>,
43}
44
45fn integer(text: &str) -> Result<i64, String> {
46 let parsed = match text.strip_prefix("0x") {
47 Some(hex) => i64::from_str_radix(hex, 16),
48 None => text.parse(),
49 };
50 parsed.map_err(|_| format!("not a number: {text}"))
51}
52
53fn real(text: &str) -> Result<f64, String> {
54 text.parse().map_err(|_| format!("not a number: {text}"))
55}
56
57fn flag(text: &str) -> bool {
58 matches!(text.to_lowercase().as_str(), "true" | "1")
59}
60
61fn list<const N: usize>(text: &str) -> Result<[i64; N], String> {
62 let values: Vec<i64> = text.split(',').map(integer).collect::<Result<_, _>>()?;
63 values
64 .try_into()
65 .map_err(|_| format!("{N} numbers, not {text}"))
66}
67
68pub fn set_switch(switches: &mut CdSwitches, spec: &str) -> Result<(), String> {
70 let (target, text) = spec
71 .split_once('=')
72 .ok_or_else(|| format!("--switch WHERE.NAME=VALUE, not {spec}"))?;
73 let s = switches;
74 match target {
75 "scsi.SEL_TO_COMMAND_PHASE" => s.scsi.sel_to_command_phase = integer(text)?,
76 "scsi.NEXT_COMMAND_BYTE_REQ" => s.scsi.next_command_byte_req = integer(text)?,
77 "scsi.TEST_UNIT_READY" => s.scsi.test_unit_ready = integer(text)?,
78 "scsi.TOC_ANSWER" => s.scsi.toc_answer = integer(text)?,
79 "scsi.SUBQ_ANSWER" => s.scsi.subq_answer = integer(text)?,
80 "scsi.DONE_STATUS" => s.scsi.done_status = integer(text)?,
81 "scsi.ABORT_TO_COMMAND" => s.scsi.abort_to_command = integer(text)?,
82 "scsi.ACK_CLEAR" => s.scsi.ack_clear = integer(text)?,
83 "scsi.SECTOR_CLOCKS" => s.scsi.sector_clocks = integer(text)?,
84 "scsi.REREAD_PENALTY_MS" => s.scsi.reread_penalty_ms = integer(text)?,
85 "scsi.SEEK_SCALE" => s.scsi.seek_scale = real(text)?,
86 "scsi.TOC_ANSWER_BYTES" => s.scsi.toc_answer_bytes = list::<3>(text)?.map(|n| n as usize),
87 "scsi.UNKNOWN_COMMAND_CHECK_CONDITION" => {
88 s.scsi.unknown_command_check_condition = flag(text)
89 }
90 "unit.CHANNEL_LATCH_GUARD" => s.unit.channel_latch_guard = integer(text)?,
91 "unit.DMA_BYTE_CLOCKS" => s.unit.dma_byte_clocks = integer(text)?,
92 "cdda.FADE_SLOW_SECONDS" => s.fader.fade_slow_seconds = real(text)?,
93 "cdda.FADE_FAST_SECONDS" => s.fader.fade_fast_seconds = real(text)?,
94 "cdda.PCETECH_SLOW_SECONDS" => s.fader.pcetech_slow_seconds = real(text)?,
95 "cdda.PCETECH_FAST_SECONDS" => s.fader.pcetech_fast_seconds = real(text)?,
96 "cdda.PCETECH_FADE" => s.fader.pcetech_fade = flag(text),
97 "cdda.SUBQ_STATUS" => s.subq_status = Some(list::<4>(text)?.map(|n| n as u8)),
98 "adpcm.BASE_HZ" => s.adpcm.base_hz = real(text)?,
99 "adpcm.READ_CLOCKS" => s.adpcm.read_clocks = integer(text)?,
100 "adpcm.WRITE_CLOCKS" => s.adpcm.write_clocks = integer(text)?,
101 "adpcm.SATURATE" => s.adpcm.saturate = flag(text),
102 "adpcm.OUTPUT_SCALE" => s.adpcm.output_scale = integer(text)? as i32,
103 "adpcm.END_ON_WRITE_AT_ZERO" => s.adpcm.end_on_write_at_zero = flag(text),
104 "arcade.UNMAPPED_READ" => s.arcade.unmapped_read = integer(text)? as u8,
105 "arcade.SHIFT_READ_MASK" => s.arcade.shift_read_mask = integer(text)? as u8,
106 "arcade.TRIGGER_REG_READ" => s.arcade.trigger_reg_read = integer(text)? as u8,
107 "arcade.POWER_ON_RAM_BYTE" => s.arcade.power_on_ram_byte = integer(text)? as u8,
108 "arcade.RESET_CLEARS_REGISTERS" => s.arcade.reset_clears_registers = flag(text),
109 _ => return Err(format!("no switch {target}")),
110 }
111 Ok(())
112}
113
114#[cfg(not(target_arch = "wasm32"))]
115fn open_disc(path: &str) -> Result<Disc, String> {
116 Disc::from_cue_path(path)
117}
118
119#[cfg(target_arch = "wasm32")]
121fn open_disc(path: &str) -> Result<Disc, String> {
122 Err(format!("{path}: no filesystem here"))
123}
124
125impl Setup {
126 pub fn parse(args: &[String]) -> Result<Setup, String> {
130 let mut setup = Setup {
131 card: Vec::new(),
132 disc: None,
133 arcade: false,
134 frames: 60,
135 presses: Vec::new(),
136 machine: "pce".to_string(),
137 super_system_card: None,
138 region_us: false,
139 bram: None,
140 switches: CdSwitches::default(),
141 resets: Vec::new(),
142 detail: None,
143 out: None,
144 rest: Vec::new(),
145 };
146 let mut path = None;
147 let mut iter = args.iter();
148 let file = |path: &String| std::fs::read(path).map_err(|error| format!("{path}: {error}"));
149 while let Some(arg) = iter.next() {
150 let mut value = || iter.next().ok_or_else(|| format!("{arg} needs a value"));
151 match arg.as_str() {
152 "--disc" => setup.disc = Some(value()?.clone()),
153 "--arcade" => setup.arcade = true,
154 "--frames" => setup.frames = integer(value()?)?,
155 "--press" => setup.presses.push(parse_press(value()?)?),
156 "--machine" => setup.machine = value()?.clone(),
157 "--super" => setup.super_system_card = Some(value()? == "yes"),
158 "--region-us" => setup.region_us = true,
159 "--bram" => setup.bram = Some(file(value()?)?),
160 "--switch" => set_switch(&mut setup.switches, value()?)?,
161 "--reset" => {
162 let text = value()?;
163 let (frame, kind) = text
164 .split_once(':')
165 .ok_or_else(|| format!("--reset FRAME:button|power, not {text}"))?;
166 let kind = match kind {
167 "button" => ResetKind::Button,
168 "power" => ResetKind::PowerOn,
169 _ => return Err(format!("--reset FRAME:button|power, not {text}")),
170 };
171 setup.resets.push((integer(frame)?, kind));
172 }
173 "--detail" => setup.detail = Some(integer(value()?)?),
174 "--out" => setup.out = Some(value()?.clone()),
175 _ if path.is_none() && !arg.starts_with("--") => path = Some(arg.clone()),
176 _ => setup.rest.push(arg.clone()),
177 }
178 }
179 setup.card = file(&path.ok_or("no System Card image given")?)?;
180 Ok(setup)
181 }
182
183 pub fn build(&self) -> Result<System, String> {
185 let disc = match &self.disc {
186 Some(path) => Some(open_disc(path)?),
187 None => None,
188 };
189 let mut machine = PcEngineCd::new(&self.card, disc);
190 machine.super_system_card = self.super_system_card;
191 machine.region_us = self.region_us;
192 machine.bram = self.bram.clone();
193 machine.arcade_card = self.arcade;
194 machine.switches = self.switches;
195 machine.board.machine = match self.machine.as_str() {
196 "pce" => PC_ENGINE,
197 "tg16" => TURBOGRAFX_16,
198 other => return Err(format!("no machine {other}: pce or tg16")),
199 };
200 machine.board.pad = Some(Box::new(Pad2::new()));
201 let mut system = machine.build()?;
202 if let Some(unit) = unit(system.board_mut()) {
203 unit.bus.record_log = true;
204 }
205 Ok(system)
206 }
207
208 pub fn before_frame(&self, system: &mut System) {
210 let frame = system.frame();
211 system
212 .board_mut()
213 .set_pressed(0, held(&self.presses, frame));
214 for &(at, kind) in &self.resets {
215 if at == frame {
216 system.board_mut().reset(kind);
217 }
218 }
219 }
220}
221
222pub fn frame_line(system: &mut System) -> String {
224 let line = pcengine_rust::trace::frame_line(system);
225 let mut commands = Sha1::new();
226 let mut count = 0;
227 if let Some(unit) = unit(system.board_mut()) {
228 count = unit.bus.log.len();
229 for (at, text) in unit.bus.log.drain(..) {
230 commands.update(format!("{at} {text}\n"));
231 }
232 }
233 let digest: String = commands
234 .finalize()
235 .iter()
236 .map(|byte| format!("{byte:02x}"))
237 .collect();
238 format!("{line} cmd={count}:{digest}")
239}
240
241pub fn run_frames(setup: &Setup, system: &mut System, frames: i64) -> Vec<String> {
243 (0..frames)
244 .map(|_| {
245 setup.before_frame(system);
246 system.run_frame();
247 frame_line(system)
248 })
249 .collect()
250}
251
252fn started(setup: &Setup) -> Result<System, String> {
253 let mut system = setup.build()?;
254 system.board_mut().bus_log = Some(Vec::new());
255 Ok(system)
256}
257
258fn settle(system: &mut System) {
259 if let Some(log) = system.board_mut().bus_log.as_mut() {
260 log.clear();
261 }
262 system.board_mut().take_audio();
263 if let Some(unit) = unit(system.board_mut()) {
264 unit.bus.log.clear();
265 }
266}
267
268pub fn roundtrip(setup: &Setup, at: i64, to: i64, extra: i64) -> Result<String, String> {
275 use pcengine_rust::state::{load_state, save_state};
276 let mut first = started(setup)?;
277 run_frames(setup, &mut first, at);
278 for _ in 0..extra {
279 first.step();
280 }
281 let state = save_state(&first);
282 settle(&mut first);
283 let expected = run_frames(setup, &mut first, to - at);
284 for (label, warm) in [
285 ("a fresh machine", 0),
286 ("a machine that had run", 1.max(at / 2)),
287 ] {
288 let mut second = started(setup)?;
289 run_frames(setup, &mut second, warm);
290 load_state(&mut second, &state).map_err(|error| format!("{label}: {error}"))?;
291 if save_state(&second) != state {
292 return Err(format!(
293 "{label}: saved again at once, the state is not the same bytes"
294 ));
295 }
296 settle(&mut second);
297 let got = run_frames(setup, &mut second, to - at);
298 for (n, (a, b)) in expected.iter().zip(&got).enumerate() {
299 if a != b {
300 return Err(format!(
301 "{label}: differs in frame {} after the save\n expected {a}\n got {b}",
302 n + 1
303 ));
304 }
305 }
306 }
307 Ok(format!(
308 "{} bytes; {} frames after the save equal, twice",
309 state.len(),
310 to - at
311 ))
312}
313
314pub fn runahead(setup: &Setup, from: i64, frames: i64, ahead: i64) -> Result<String, String> {
318 use pcengine_rust::state::{load_snapshot, save_snapshot, save_state};
319 let mut plain = started(setup)?;
320 run_frames(setup, &mut plain, from);
321 let expected = run_frames(setup, &mut plain, frames);
322 let mut system = started(setup)?;
323 run_frames(setup, &mut system, from);
324 let mut bytes = 0;
325 for (n, wanted) in expected.iter().enumerate() {
326 setup.before_frame(&mut system);
327 system.run_frame();
328 let line = frame_line(&mut system);
329 if &line != wanted {
330 return Err(format!(
331 "frame {} differs after a snapshot was put back\n expected {wanted}\n got {line}",
332 n + 1
333 ));
334 }
335 let snapshot = save_snapshot(&system);
336 bytes = snapshot.len();
337 for _ in 0..ahead {
338 system
339 .board_mut()
340 .set_pressed(0, pads::RUN | pads::I | pads::RIGHT);
341 system.run_frame();
342 }
343 load_snapshot(&mut system, &snapshot)?;
344 settle_logs(&mut system);
345 }
346 if save_state(&system) != save_state(&plain) {
347 return Err("the end state is not the plain run's".to_string());
348 }
349 Ok(format!(
350 "{frames} frames from {from}, {ahead} ahead of each, equal to the plain run; a snapshot is {bytes} bytes"
351 ))
352}
353
354fn settle_logs(system: &mut System) {
355 if let Some(log) = system.board_mut().bus_log.as_mut() {
356 log.clear();
357 }
358 if let Some(unit) = unit(system.board_mut()) {
359 unit.bus.log.clear();
360 }
361}