// SPDX-License-Identifier: MIT //! Rung 2, unit-level lockstep: tests/vectors/units.txt (scripts/make_unit_vectors.py, //! written on the reference) replayed call by call into this board's device -- the 68000's //! and the Z80's accesses, the SH-2 side's bus cycles, line records, socket 7's lines, //! socket 8's samples, catch-ups and peeks -- each answer and the CRC of the device's //! whole state after it compared, and every 64th call the state itself. use std::sync::{Arc, Mutex}; use megadrive_rust::cartridge::Cartridge; use megadrive_rust::sockets::{PictureLine, VideoLine, M68K}; use megadrive_rust::vdp::{tables, HName}; use megadrive_rust::System; use sega32x_rust::bootrom::BootROMs; use sega32x_rust::console::Slot; use sega32x_rust::slot::{Sega32X, Stop}; use sega32x_rust::trace::{crc32, device_lines}; use sh2::BusContext; fn hex(text: &str) -> u32 { u32::from_str_radix(text, 16).expect("hex") } fn unhex(text: &str) -> Vec { (0..text.len()).step_by(2).map(|i| u8::from_str_radix(&text[i..i + 2], 16).expect("hex")).collect() } /// The reference's `cartridge_image`. fn cartridge_image() -> Vec { let mut image = vec![0u8; 0x80000]; for i in (0..image.len()).step_by(2) { let word = ((i * 7 + 3) & 0xFFFF) as u16; image[i..i + 2].copy_from_slice(&word.to_be_bytes()); } image[0x100..0x110].copy_from_slice(b"SEGA 32X "); image[0..4].copy_from_slice(&0x00FF0000u32.to_be_bytes()); image[4..8].copy_from_slice(&0x00000200u32.to_be_bytes()); image[0x200..0x202].copy_from_slice(&0x60FEu16.to_be_bytes()); image } /// The reference's `picture`. fn picture(seed: u64, width: usize) -> (Vec, Vec) { let rgb = (0..width as u64).map(|i| ((seed * 2654435761 + i * 40503) & 0xFFFFFF) as u32).collect(); let ys = (0..width as u64).map(|i| (((seed >> (i % 30)) ^ i) & 1) as u8).collect(); (rgb, ys) } fn result(out: Result) -> String { match out { Ok(value) => value.to_string(), Err(Stop::Lockup(_)) => "stop Lockup".into(), Err(Stop::BootROM(_)) => "stop BootROMError".into(), } } fn unit(out: Result<(), Stop>) -> String { match out { Ok(()) => "None".into(), other => result(other.map(|_| 0)), } } #[test] fn units_replay_identically() { let text = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/vectors/units.txt")) .expect("tests/vectors/units.txt"); let mut lines = text.lines().filter(|l| !l.starts_with('#')).peekable(); let mut roms: Vec> = Vec::new(); while let Some(line) = lines.next_if(|l| l.starts_with("B ")) { roms.push(unhex(line.split(' ').nth(2).expect("a ROM"))); } let roms = BootROMs { m68k: roms[0].clone(), master: roms[1].clone(), slave: roms[2].clone() }; let device = Sega32X::new(true, None, None, Some(&roms)).expect("a 32X"); let shared = Arc::new(Mutex::new(device)); let slot = Slot { device: shared.clone(), cartridge: Some(Cartridge::new(cartridge_image(), "rom", 0, "")) }; let md = megadrive_rust::machine("genesis").expect("genesis"); let mut system = System::with_sockets(md, None, None, None, Some(Box::new(slot)), None); let t = tables(); let mut calls = 0; let mut answer = String::new(); let mut checked_states = 0; for line in lines { let f: Vec<&str> = line.split(' ').collect(); let mut d = shared.lock().expect("the 32X"); let board = &mut system.board().dev; match f[0] { "L" => { let (start, v, h40, pal, late): (i64, i64, bool, bool, i64) = (f[1].parse().unwrap(), f[2].parse().unwrap(), f[3] == "1", f[4] == "1", f[5].parse().unwrap()); let mode = if h40 { &t.h40 } else { &t.h32 }; d.video_line(&VideoLine { start, length: mode.length, v, hmode: mode.name, hblank_set: f[6].parse().unwrap(), hblank_clear: f[7].parse().unwrap(), vblank: false, vsync: false, interlace: false, odd: false, pal, pixels: &mode.starts, published: start + late, }); } "O" => { calls += 1; answer = match f[1] { "WW" => unit(d.write_word(board, hex(f[2]), hex(f[3]) as u16, f[4].parse().unwrap())), "WB" => unit(d.write_byte( board, hex(f[2]), hex(f[3]) as u8, f[4].parse().unwrap(), f[5].parse().unwrap(), )), "RW" => result(d.read_word(board, hex(f[2]), f[3].parse().unwrap())), "RB" => result(d.read_byte(board, hex(f[2]), f[3].parse().unwrap(), f[4].parse().unwrap())), "SR" | "SW" => { let index: usize = f[2].parse().unwrap(); let address = hex(f[3]); let width: u32 = f[4].parse().unwrap(); let (value, kind, clock): (u32, u32, i64) = if f[1] == "SW" { (hex(f[5]), f[6].parse().unwrap(), f[7].parse().unwrap()) } else { (0, f[5].parse().unwrap(), f[6].parse().unwrap()) }; let chip = d.sh2.as_mut().unwrap().chip(index); chip.clock = clock; chip.wait = 0; let mut cx = BusContext { clock: chip.clock, wait: chip.wait, cycle_states: chip.bsc.cycle_states, waits: chip.bsc.waits, wait_pin: chip.bsc.wait_pin, pins: chip.pins(), }; // The chip out of the side for its cycle, as a step takes it out. let taken = d.sh2.as_mut().unwrap().chips[index].take(); let out = if f[1] == "SW" { d.sh2_write(index, address, width, value, kind, &mut cx, board); "None".to_string() } else { d.sh2_read(index, address, width, kind, &mut cx, board).to_string() }; d.sh2.as_mut().unwrap().chips[index] = taken; let chip = d.sh2.as_mut().unwrap().chip(index); chip.wait = cx.wait; chip.set_pins(cx.pins); let text = format!("{out} wait={}", chip.wait); chip.wait = 0; text } "C" => { d.catch_up(board, f[2].parse().unwrap()); "None".into() } "P" => { let mclk_hz = d.mclk_hz; let (pwm, mut links) = d.pwm_links(); let samples = pwm.take_samples(f[2].parse().unwrap(), mclk_hz, &mut links); let data: Vec = samples .iter() .flat_map(|(l, r)| l.to_le_bytes().into_iter().chain(r.to_le_bytes())) .collect(); let rate: String = d.pwm.rate().to_le_bytes().iter().map(|b| format!("{b:02x}")).collect(); format!("{}:{:08X} rate={rate}", samples.len(), crc32(&data)) } "PL" => { let start: i64 = f[2].parse().unwrap(); let h40 = f[3] == "1"; let seed: u64 = f[4].parse().unwrap(); let width = if h40 { 320 } else { 256 }; let (rgb, ys) = picture(seed, width); let v = d.vdp.timings.last().map_or(0, |t| t.v); let row = d.picture_line(PictureLine { row: (v % 240) as usize, start, hmode: if h40 { HName::H40 } else { HName::H32 }, width, pixel_mclk: if h40 { 8 } else { 10 }, display_at: start + 100, output_delay: 4, rgb, ys, shade: vec![0; width], }); match row { None => "none".into(), Some(row) => { let row = row.lock().unwrap(); let data: Vec = row.iter().flat_map(|p| p.to_le_bytes()).collect(); format!("{}:{:08X}", row.len(), crc32(&data)) } } } "K" => d.peek_byte(board, hex(f[2])).to_string(), other => panic!("unknown call {other}"), }; let _ = M68K; if d.take_claims_changed() { drop(d); system.board().dev.update_claims(); continue; } } "E" => { assert_eq!(answer, line[2..], "call {calls}: the answer"); } "D" => { let state = device_lines(&mut d, board); assert_eq!(format!("{:08X}", crc32(state.as_bytes())), f[1], "call {calls}: the state's CRC\n{state}"); } "S" => { let state = device_lines(&mut d, board); assert!(state.lines().any(|l| l == &line[2..]), "call {calls}: state line {}", &line[2..]); checked_states += 1; } other => panic!("unknown line {other}"), } } assert_eq!(calls, 6000); assert!(checked_states > 0); }