// SPDX-License-Identifier: MIT //! The lockstep gate's board side: this crate, traced slice by slice, line for //! line as `scripts/a2600_trace.py` traces the reference (its docstring has the //! format, the ROM forms, the machine keys, the devices and the input words). //! //! a2600-trace ROM --slices N [--machine KEY] [--scheme S] [--left DEV] [--right DEV] //! [--input FILE] [--detail SLICE] [--hand-over SLICE] [--save-at SLICE] --out FILE //! //! `--hand-over SLICE` as the reference's tool: the running CPU handed to a //! new board on the running chips ([`System::with_cpu`]), no power-on. //! //! `--save-at SLICE` (this board's alone): before that slice runs, save the //! console's state (and the devices' own: the SaveKey's chip, the Driving //! controller, paddle positions and pressed keys), build a fresh console from //! the same ROM and row, load the state into it and go on there. The trace //! must not change. use std::cell::RefCell; use std::collections::BTreeSet; use std::fs::File; use std::io::{BufWriter, Read, Write}; use std::path::Path; use std::rc::Rc; use a2600::board::Board; use a2600::cartridge::connector::NoCartridge; use a2600::cartridge::{load, mame_hash, read_image, Options, Rom}; use a2600::controllers::{BoosterGrip, DrivingController, Joystick, Keypads, Paddles, Stick}; use a2600::machine::{console_row, Machine, NTSC_7800, VCS_NTSC, VCS_PAL, VCS_SECAM}; use a2600::savekey::{SaveKey, EEPROM24LC256}; use a2600::state::{load_state, save_state}; use a2600::system::System; use a2600::tia::TIA; const SLICE_CYCLES: u64 = 262 * 76; const KEYS: &str = "123456789*0#"; fn machine_row(key: &str) -> Machine { match key { "ntsc" => VCS_NTSC, "pal" => VCS_PAL, "secam" => VCS_SECAM, "ntsc7800" => NTSC_7800, other => console_row(other).unwrap_or_else(|| panic!("no machine {other}")), } } fn rom_image(text: &str) -> Vec { if let Some((archive, member)) = text.split_once("::") { let mut zip = zip::ZipArchive::new(File::open(archive).expect("archive")).expect("zip"); let mut data = Vec::new(); zip.by_name(member) .expect("member") .read_to_end(&mut data) .expect("read"); return data; } read_image(Path::new(text)).expect("ROM").0 } fn read_inputs(path: Option<&str>) -> Vec<(u64, Vec)> { let mut out: Vec<(u64, Vec)> = Vec::new(); let Some(path) = path else { return out }; for line in std::fs::read_to_string(path).expect("input file").lines() { let words: Vec<&str> = line.split_whitespace().collect(); if words.is_empty() || words[0].starts_with(';') { continue; } let slice: u64 = words[0].parse().expect("a slice number"); let rest: Vec = words[1..].iter().map(|w| w.to_string()).collect(); match out.iter_mut().find(|(s, _)| *s == slice) { Some((_, list)) => list.extend(rest), None => out.push((slice, rest)), } } out } enum Left { Joystick(Joystick), Driving(DrivingController), Booster(BoosterGrip), None, } /// The ports' devices, as the reference's play.py Controls plugs them in. struct Devices { left_kind: String, right_kind: String, paddles: Option, keypads: Option, left: Left, right: Option, savekey: Option, } /// The devices' own state, for `--save-at`. #[derive(serde::Serialize, serde::Deserialize)] struct DeviceState { paddles: Option<[Option; 4]>, keys: Option<[BTreeSet<(u8, u8)>; 2]>, wheel: Option, savekey: Option, } impl Devices { fn new(system: &mut System, left: &str, right: &str) -> Devices { let clock = system.machine.timing.colour_clock_hz; let cpu_hz = system.machine.timing.cpu_hz(); let board = system.board_mut(); let riot_rc = board.riot.clone(); let tia = &mut board.tia; let paddles = if left == "paddles" || right == "paddles" || left == "booster" { Some(Paddles::new(tia, clock)) } else { None }; let keypads = if left == "keypad" || right == "keypad" { Some(Keypads::new(tia, riot_rc.clone())) } else { None }; let mut riot = riot_rc.borrow_mut(); let left_device = match left { "joystick" => Left::Joystick(Joystick::new(0)), "driving" => Left::Driving(DrivingController::new(tia, &mut riot, 0)), "booster" => Left::Booster(BoosterGrip::new(paddles.clone().expect("paddles"), 0)), _ => Left::None, }; let right_device = if right == "joystick" { Some(Joystick::new(1)) } else { None }; let savekey = if right == "savekey" { Some(SaveKey::new(&mut riot, cpu_hz, 1, None)) } else { None }; if let Some(p) = paddles.as_ref() { for (i, kind) in [(0, left), (2, right)] { if kind == "paddles" { let mut position = p.position.borrow_mut(); position[i] = Some(0.5); position[i + 1] = Some(0.5); } } } Devices { left_kind: left.to_string(), right_kind: right.to_string(), paddles, keypads, left: left_device, right: right_device, savekey, } } fn snapshot(&self) -> DeviceState { DeviceState { paddles: self.paddles.as_ref().map(|p| *p.position.borrow()), keys: self.keypads.as_ref().map(|k| k.pressed.borrow().clone()), wheel: match &self.left { Left::Driving(w) => Some(w.clone()), _ => None, }, savekey: self.savekey.as_ref().map(|k| k.chip.borrow().clone()), } } fn restore(&mut self, state: DeviceState, system: &mut System) { if let (Some(p), Some(saved)) = (self.paddles.as_ref(), state.paddles) { *p.position.borrow_mut() = saved; } if let (Some(k), Some(saved)) = (self.keypads.as_ref(), state.keys) { *k.pressed.borrow_mut() = saved; } if let (Left::Driving(w), Some(saved)) = (&mut self.left, state.wheel) { *w = saved; } if let (Some(_), Some(chip)) = (self.savekey.as_ref(), state.savekey) { let riot = system.board().riot.clone(); self.savekey = Some(SaveKey::with_chip( &mut riot.borrow_mut(), Rc::new(RefCell::new(chip)), 1, )); } } fn apply(&mut self, word: &str, system: &mut System) { let (name, value) = word.split_once('=').unwrap_or((word, "")); let parts: BTreeSet<&str> = if value == "-" { BTreeSet::new() } else { value.split('+').collect() }; let stick = Stick { up: parts.contains("up"), down: parts.contains("down"), left: parts.contains("left"), right: parts.contains("right"), fire: parts.contains("fire"), }; let board = system.board_mut(); let riot_rc = board.riot.clone(); let mut riot = riot_rc.borrow_mut(); let tia: &mut TIA = &mut board.tia; if name == "p0" { match &mut self.left { Left::Booster(grip) if self.left_kind == "booster" => { grip.set(tia, &mut riot, parts.contains("pin5"), parts.contains("pin9"), stick) } Left::Joystick(j) => j.set(tia, &mut riot, stick), _ => panic!("p0 needs a joystick or booster on the left"), } } else if name == "p1" { self.right .as_ref() .expect("a right joystick") .set(tia, &mut riot, stick); } else if name == "wheel" { let Left::Driving(w) = &mut self.left else { panic!("no wheel") }; w.turn(tia, &mut riot, value.parse().expect("clicks")); } else if name == "wheelfire" { let Left::Driving(w) = &mut self.left else { panic!("no wheel") }; w.press(tia, &mut riot, value == "1"); } else if let Some(i) = name.strip_prefix("padfire") { let bit = [0x80u8, 0x40, 0x08, 0x04][i.parse::().expect("pad")]; let input = riot.input_a; riot.set_input_a(if value == "1" { input & !bit } else { input | bit }); } else if let Some(i) = name.strip_prefix("pad") { self.paddles.as_ref().expect("paddles").position.borrow_mut()[i.parse::().expect("pad")] = Some(value.parse().expect("position")); } else if let Some(i) = name.strip_prefix("keys") { let keypads = self.keypads.as_ref().expect("keypads"); let mut pressed = keypads.pressed.borrow_mut(); let port = &mut pressed[i.parse::().expect("port")]; port.clear(); for key in parts { let index = KEYS.find(key).expect("a key legend") as u8; port.insert((index / 3, index % 3)); } } else if name == "switches" { let held = (if parts.contains("reset") { 0x01 } else { 0 }) | (if parts.contains("select") { 0x02 } else { 0 }); riot.input_b = (riot.input_b | 0x03) & !held; } else if name == "colour" { riot.input_b = if value == "1" { riot.input_b | 0x08 } else { riot.input_b & !0x08 }; } else if name == "diff0" || name == "diff1" { let bit = if name == "diff0" { 0x40 } else { 0x80 }; riot.input_b = if value == "a" { riot.input_b | bit } else { riot.input_b & !bit }; } else { panic!("unknown input word {word:?}"); } let _ = &self.right_kind; } } struct Args { rom: String, slices: u64, machine: String, scheme: Option, left: String, right: String, input: Option, detail: i64, save_at: Option, hand_over: Option, out: String, } fn parse_args() -> Args { let mut it = std::env::args().skip(1); let mut args = Args { rom: String::new(), slices: 0, machine: "ntsc".into(), scheme: None, left: "joystick".into(), right: "joystick".into(), input: None, detail: -1, save_at: None, hand_over: None, out: String::new(), }; while let Some(a) = it.next() { let mut value = || it.next().unwrap_or_else(|| panic!("{a} needs a value")); match a.as_str() { "--slices" => args.slices = value().parse().expect("slices"), "--machine" => args.machine = value(), "--scheme" => args.scheme = Some(value()), "--left" => args.left = value(), "--right" => args.right = value(), "--input" => args.input = Some(value()), "--detail" => args.detail = value().parse().expect("detail"), "--save-at" => args.save_at = Some(value().parse().expect("save-at")), "--hand-over" => args.hand_over = Some(value().parse().expect("hand-over")), "--out" => args.out = value(), _ if a.starts_with("--") => panic!("unknown option {a}"), _ => args.rom = a, } } args } struct Tap { bus: Vec, detail_on: bool, detail: Vec, picture: u32, lines: u64, } fn build(image: &[u8], args: &Args, machine: Machine, tap: &Rc>) -> (System, String) { let loaded = load( Rom::Bytes(image), args.scheme.as_deref(), None, &mame_hash(), // The row's clock goes to the cartridge, as System::from_rom passes it. Options { cpu_hz: Some(machine.timing.cpu_hz()), ..Options::default() }, ) .expect("load"); let name = loaded.cartridge.name().to_string(); let mut system = System::new(loaded.cartridge, machine, None).expect("system"); let observer = tap.clone(); system .board_mut() .bus_observers .push(Box::new(move |kind, address, value, cycle| { let mut t = observer.borrow_mut(); t.bus.push(if kind == 'R' { 0 } else { 1 }); t.bus.extend_from_slice(&address.to_le_bytes()); t.bus.push(value); t.bus.extend_from_slice(&cycle.to_le_bytes()); if t.detail_on { t.detail.push(format!(" {kind} {address:04x} {value:02x} {cycle}")); } })); let lines = tap.clone(); system.board_mut().tia.on_line = Some(Box::new(move |tia: &TIA| { let mut t = lines.borrow_mut(); let mut crc = crc32fast::Hasher::new_with_initial(t.picture); crc.update(&tia.pixels); t.picture = crc.finalize(); t.lines += 1; })); (system, name) } fn main() { let args = parse_args(); let machine = machine_row(&args.machine); let image = rom_image(&args.rom); let tap = Rc::new(RefCell::new(Tap { bus: Vec::new(), detail_on: false, detail: Vec::new(), picture: 0, lines: 0, })); let (mut system, scheme) = build(&image, &args, machine, &tap); let mut devices = Devices::new(&mut system, &args.left, &args.right); let inputs = read_inputs(args.input.as_deref()); let mut out = BufWriter::new(File::create(&args.out).expect("out")); writeln!(out, "# scheme={scheme} machine={}", machine.name).unwrap(); for k in 0..args.slices { if args.save_at == Some(k) { let saved = save_state(&system); let devices_saved = devices.snapshot(); let (mut fresh, _) = build(&image, &args, machine, &tap); let mut fresh_devices = Devices::new(&mut fresh, &args.left, &args.right); load_state(&mut fresh, &saved).expect("load state"); fresh_devices.restore(devices_saved, &mut fresh); system = fresh; devices = fresh_devices; } if args.hand_over == Some(k) { // The CPU, TIA and RIOT handed to a new board as they stand // (System::with_cpu, as tests/sockets.rs's mid-run hand-over). let System { mut cpu, instructions, .. } = system; let old = &mut cpu.bus; let tia = std::mem::take(&mut old.tia); let cartridge = std::mem::replace(&mut old.cartridge, Box::new(NoCartridge)); let mut board = Board::new(machine, cartridge, Some(tia), Some(old.riot.clone()), old.cycles).expect("board"); board.data_bus = old.data_bus; board.bus_observers = std::mem::take(&mut old.bus_observers); let (mut handed, _old) = System::with_cpu(board, machine, cpu); handed.instructions = instructions; system = handed; } if let Some((_, words)) = inputs.iter().find(|(s, _)| *s == k) { for word in words { devices.apply(word, &mut system); } } tap.borrow_mut().detail_on = k as i64 == args.detail; let end = (k + 1) * SLICE_CYCLES; while system.board().cycles < end { system.step(); } let samples = system.board_mut().tia.audio.take_samples(); let mut sound = crc32fast::Hasher::new(); for s in &samples { sound.update(&s.to_le_bytes()); } let board = system.board(); let (tia, riot, cpu) = (&board.tia, board.riot.borrow(), &system.cpu); let mut t = tap.borrow_mut(); let bus_crc = crc32fast::hash(&t.bus); writeln!( out, "{k} pc={:04x} a={:02x} x={:02x} y={:02x} s={:02x} p={:02x} cyc={} halt={} ins={} line={} step={} frame={} \ riot={:02x}/{:02x}/{:02x}/{:02x}/{:02x} bus={:08x}/{} pic={:08x}/{} snd={:08x}/{}", cpu.pc, cpu.a, cpu.x, cpu.y, cpu.s, cpu.p, board.cycles, board.halted_cycles, system.instructions, tia.line, tia.step_in_line, tia.frame, riot.value, riot.flags, riot.ddr_a, riot.out_a, riot.input_a, bus_crc, t.bus.len() / 12, t.picture, t.lines, sound.finalize(), samples.len() ) .unwrap(); if !t.detail.is_empty() { writeln!(out, "{}", t.detail.join("\n")).unwrap(); t.detail.clear(); } t.bus.clear(); t.picture = 0; t.lines = 0; } }