// SPDX-License-Identifier: MIT //! A desktop window: play a cartridge with the picture and the keyboard (the reference's //! `python -m a7800_python.frontend`, milestone 8), on SDL2 (feature `frontend`). //! //! ```text //! a7800-play CART [--palette cool|warm|hot] [--composite] [--scale 3] [--machine ntsc|pal] //! [--direct] [--frames N] [--screenshot OUT.png] //! a7800-play --judge [CART] [--frames N] [--skip N] [--fault keys|pixels|composite] //! a7800-play --dump-palettes # the three palettes and a composite row, as text //! ``` //! //! Keys (frontend.rs): arrows = joystick 1, Z / X = its left and right buttons (Space = //! both), Enter = Reset, Tab = Select, P = Pause, F1 / F2 toggle the difficulty switches, //! Escape quits. As in the reference, the window shows every frame the board makes and //! never waits, and has no sound. //! //! `--judge` is the reference's `scripts/m8_frontend.py`, headless (SDL's dummy video //! driver): (1) each palette's hue step measured back from its RGB table through an //! independent RGB -> YUV inversion equals the wiki's figure within 0.2 degrees, hue 0 //! has no chroma and luminance rises with the low nibble; (2) Joust (USA) from the NTSC //! BIOS to frame `--skip` (default 200), then `--frames` (default 20) frames through the //! window, each read back from the window's canvas and compared pixel for pixel with the //! board's frame through the palette; (3) synthetic key events pushed to SDL's queue must //! reach the board (Right clears SWCHA D7 while held, Enter clears SWCHB D0, Space sets //! both ProLine buttons); (4) on a synthetic 320-mode row, alternating light and dark //! pixels give chroma of opposite signs for the two phases, a uniform row none. Seeded //! faults `keys`, `pixels`, `composite` must each make it fail. No human has looked at //! this window on a screen: the judge reads the canvas back. //! //! Rust-forced differences: pygame-ce is the `sdl2` crate; the window is a software //! canvas with a streaming texture; `--dump-palettes` lets the ladder compare the //! palettes and the composite option with the reference's byte for byte. use std::path::PathBuf; use sdl2::event::{Event, EventSender}; use sdl2::keyboard::Keycode; use sdl2::pixels::PixelFormatEnum; use sdl2::rect::Rect; use a7800::cartridge::formats::{LoadOptions, Source}; use a7800::frontend::{action_of, chroma, palette, render, step_of, Keys, PALETTES}; use a7800::machine::{Machine, NTSC, PAL}; use a7800::romsets::{no_intro, LICENSED_7800}; use a7800::system::System; use a7800::television::{crop_for, png, Television, WIDTH}; struct Args { cart: Option, palette: String, composite: bool, scale: u32, machine: Machine, direct: bool, frames: Option, skip: u64, screenshot: Option, judge: bool, dump: bool, faults: Vec<&'static str>, } fn parse() -> Result { let mut a = Args { cart: None, palette: "warm".into(), composite: false, scale: 3, machine: NTSC, direct: false, frames: None, skip: 200, screenshot: None, judge: false, dump: false, faults: Vec::new(), }; let mut it = std::env::args().skip(1); while let Some(arg) = it.next() { let mut value = || it.next().ok_or(format!("{arg} needs a value")); match arg.as_str() { "--palette" => { a.palette = value()?; step_of(&a.palette).ok_or("--palette is cool, warm or hot")?; } "--composite" => a.composite = true, "--scale" => a.scale = value()?.parse().map_err(|e| format!("{e}"))?, "--machine" => a.machine = if value()? == "pal" { PAL } else { NTSC }, "--direct" => a.direct = true, "--frames" => a.frames = Some(value()?.parse().map_err(|e| format!("{e}"))?), "--skip" => a.skip = value()?.parse().map_err(|e| format!("{e}"))?, "--screenshot" => a.screenshot = Some(value()?.into()), "--judge" => a.judge = true, "--dump-palettes" => a.dump = true, "--fault" => { a.faults.push(match value()?.as_str() { "keys" => "keys", "pixels" => "pixels", "composite" => "composite", other => return Err(format!("unknown fault {other}")), }); } other if other.starts_with("--") => return Err(format!("unknown option {other}")), other => a.cart = Some(other.into()), } } Ok(a) } /// The board, its television and the window (`Frontend` in the reference). struct Frontend { system: System, tv: Television, kind: String, composite: bool, lines: u32, keys: Keys, running: bool, } impl Frontend { fn new(mut system: System, kind: &str, composite: bool) -> Frontend { let (first, lines) = crop_for(&system.machine); let tv = Television::new(&mut system.board_mut().maria, 1, first, lines); Frontend { system, tv, kind: kind.to_string(), composite, lines, keys: Keys::default(), running: true, } } fn handle(&mut self, event: &Event) { match event { Event::Quit { .. } | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => self.running = false, Event::KeyDown { keycode: Some(key), repeat: false, .. } | Event::KeyUp { keycode: Some(key), repeat: false, .. } => { let down = matches!(event, Event::KeyDown { .. }); let name = key.name().to_lowercase(); if let Some(action) = action_of(&name) { self.keys.handle(&mut self.system, action, down); } } _ => {} } } /// Events, then the board to its next frame. fn run_frame(&mut self, pump: &mut sdl2::EventPump) { let events: Vec = pump.poll_iter().collect(); for event in &events { self.handle(event); } let before = self.tv.count(); while self.tv.count() == before { self.system.step(); } } fn picture(&self) -> Vec { let frame = self.tv.last_frame().expect("a frame"); let mut kind = self.kind.as_str(); if self.keys.faults.contains("pixels") { // seeded: the wrong palette kind = if kind != "cool" { "cool" } else { "hot" }; } render(&frame, kind, self.composite && !self.keys.faults.contains("composite")) } } fn draw( canvas: &mut sdl2::render::Canvas, rgb: &[u8], lines: u32, scale: u32, ) -> Result<(), String> { let creator = canvas.texture_creator(); let mut texture = creator .create_texture_streaming(PixelFormatEnum::RGB24, WIDTH as u32, lines) .map_err(|e| e.to_string())?; texture.update(None, rgb, WIDTH * 3).map_err(|e| e.to_string())?; canvas.clear(); canvas.copy(&texture, None, Rect::new(0, 0, WIDTH as u32 * scale, lines * scale))?; canvas.present(); Ok(()) } fn to_yuv(rgb: [u8; 3]) -> (f64, f64, f64) { let (r, g, b) = (rgb[0] as f64 / 255.0, rgb[1] as f64 / 255.0, rgb[2] as f64 / 255.0); let y = 0.299 * r + 0.587 * g + 0.114 * b; (y, 0.492 * (b - y), 0.877 * (r - y)) } fn check_palettes() -> Vec { let mut fails = Vec::new(); for (kind, step) in PALETTES { let table = palette(kind); let mut steps = Vec::new(); for hue in 1..15u8 { let (_, u1, v1) = to_yuv(table[(hue << 4 | 7) as usize]); let (_, u2, v2) = to_yuv(table[((hue + 1) << 4 | 7) as usize]); let d = (v2.atan2(u2) - v1.atan2(u1)).to_degrees().rem_euclid(360.0); steps.push(d); } let mean = steps.iter().sum::() / steps.len() as f64; let ok = (mean - step).abs() < 0.2; let greys = (0..16).all(|c| table[c][0] == table[c][1] && table[c][1] == table[c][2]); let rising = (0..15).all(|l| to_yuv(table[0x40 | l]).0 <= to_yuv(table[0x40 | (l + 1)]).0 + 1e-9); println!("palette {kind}: hue step {mean:.2} (wiki {step}); hue 0 grey {greys}; luminance rising {rising}"); if !(ok && greys && rising) { fails.push(format!("palette {kind}")); } } fails } fn check_composite(faults: &[&str]) -> Vec { let alternating: Vec> = vec![[0x0F, 0x00].repeat(160)]; let swapped: Vec> = vec![[0x00, 0x0F].repeat(160)]; let uniform: Vec> = vec![vec![0x08; 320]]; let using = !faults.contains(&"composite"); let (a, s, u) = ( render(&alternating, "warm", using), render(&swapped, "warm", using), render(&uniform, "warm", using), ); let (ca, cs, cu) = ( to_yuv([a[0], a[1], a[2]]), to_yuv([s[0], s[1], s[2]]), to_yuv([u[0], u[1], u[2]]), ); let chroma_a = ca.1.hypot(ca.2); let opposite = ca.1 * cs.1 + ca.2 * cs.2 < 0.0; let flat = cu.1.hypot(cu.2) < 1e-3; println!("composite: alternating chroma {chroma_a:.3}, phases opposite {opposite}, uniform flat {flat}"); if chroma_a > 0.02 && opposite && flat { Vec::new() } else { vec!["composite".to_string()] } } fn judge(args: &Args) -> Result { let mut fails = check_palettes(); fails.extend(check_composite(&args.faults)); let cart = match &args.cart { Some(c) => c.clone(), None => no_intro(LICENSED_7800).map_err(|e| e.0)?.join("Joust (USA).zip"), }; let system = System::from_rom(Source::Path(&cart), NTSC, &LoadOptions::default(), None, "bios")?; let mut fe = Frontend::new(system, "warm", false); fe.keys.faults = args.faults.iter().copied().collect(); while fe.tv.count() < args.skip { fe.system.step(); } let sdl = sdl2::init()?; let video = sdl.video()?; let window = video .window("a7800-play judge", WIDTH as u32, fe.lines) .build() .map_err(|e| e.to_string())?; let mut canvas = window.into_canvas().software().build().map_err(|e| e.to_string())?; let mut pump = sdl.event_pump()?; let frames = args.frames.unwrap_or(20); let mut differ = 0; for _ in 0..frames { fe.run_frame(&mut pump); let rgb = fe.picture(); draw(&mut canvas, &rgb, fe.lines, 1)?; let back = canvas .read_pixels(Rect::new(0, 0, WIDTH as u32, fe.lines), PixelFormatEnum::RGB24) .map_err(|e| e.to_string())?; let frame = fe.tv.last_frame().expect("a frame"); let expected = render(&frame, "warm", false); if back != expected { differ += 1; } } if differ > 0 { fails.push(format!( "window: {differ} of {frames} frames read back differ from the board's" )); } // The keys: synthetic events through SDL's queue. let sender: EventSender = sdl.event()?.event_sender(); let key = |down: bool, k: Keycode| { if down { Event::KeyDown { timestamp: 0, window_id: 0, keycode: Some(k), scancode: None, keymod: sdl2::keyboard::Mod::NOMOD, repeat: false, } } else { Event::KeyUp { timestamp: 0, window_id: 0, keycode: Some(k), scancode: None, keymod: sdl2::keyboard::Mod::NOMOD, repeat: false, } } }; let riot = fe.system.board().riot.clone(); let pad = fe.system.controllers.state.clone(); let mut press = |fe: &mut Frontend, k: Keycode, down: bool| -> Result<(), String> { sender.push_event(key(down, k))?; fe.run_frame(&mut pump); Ok(()) }; press(&mut fe, Keycode::Right, true)?; let right_held = pad.borrow().directions[0] == 0x08; // RIGHT (controllers.rs): SWCHA D7 for port 0 press(&mut fe, Keycode::Right, false)?; let right_free = pad.borrow().directions[0] == 0; press(&mut fe, Keycode::Return, true)?; let reset_held = riot.borrow().input_b & 0x01 == 0; press(&mut fe, Keycode::Return, false)?; let reset_free = riot.borrow().input_b & 0x01 != 0; press(&mut fe, Keycode::Space, true)?; let both = pad.borrow().buttons[0] == [true, true]; press(&mut fe, Keycode::Space, false)?; println!( "keys: Right held {right_held}, released {right_free}; Enter -> SWCHB D0 low {reset_held}, released {reset_free}; Space -> both buttons {both}" ); if !(right_held && right_free && reset_held && reset_free && both) { fails.push("keys".to_string()); } for f in &fails { println!(" FAIL {f}"); } println!( "window judge: {} ({frames} frames read back, {differ} differ; faults {:?})", if fails.is_empty() { "PASS" } else { "FAIL" }, args.faults ); Ok(fails.is_empty()) } fn dump_palettes() { for (kind, _) in PALETTES { let table = palette(kind); let text: Vec = table .iter() .map(|c| format!("{:02x}{:02x}{:02x}", c[0], c[1], c[2])) .collect(); println!("{kind} {}", text.join(" ")); } let row: Vec = (0..WIDTH).map(|x| ((x * 37) & 0xFF) as u8).collect(); for kind in ["warm", "hot"] { let out = render(std::slice::from_ref(&row), kind, true); let hex: String = out.iter().map(|b| format!("{b:02x}")).collect(); println!("composite-{kind} {hex}"); } let (u, v) = chroma(0x35, 26.7); println!("chroma {u:.17} {v:.17}"); } fn play(args: &Args) -> Result<(), String> { let cart = args.cart.clone().ok_or("a cartridge")?; let start = if args.direct { "direct" } else { "bios" }; let system = System::from_rom(Source::Path(&cart), args.machine, &LoadOptions::default(), None, start)?; let mut fe = Frontend::new(system, &args.palette, args.composite); let sdl = sdl2::init()?; let video = sdl.video()?; let name = cart .file_name() .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default(); let window = video .window( &format!("a7800-play: {name}"), WIDTH as u32 * args.scale, fe.lines * args.scale, ) .build() .map_err(|e| e.to_string())?; let mut canvas = window.into_canvas().software().build().map_err(|e| e.to_string())?; let mut pump = sdl.event_pump()?; let mut frames = 0u64; let mut shown = Vec::new(); while fe.running { fe.run_frame(&mut pump); shown = fe.picture(); draw(&mut canvas, &shown, fe.lines, args.scale)?; frames += 1; if args.frames.is_some_and(|limit| frames >= limit) { break; } } if let Some(path) = &args.screenshot { let rows: Vec> = shown.chunks(WIDTH * 3).map(|r| r.to_vec()).collect(); std::fs::write(path, png(WIDTH, &rows)).map_err(|e| e.to_string())?; } Ok(()) } fn main() { let result = parse().and_then(|args| { if args.dump { dump_palettes(); Ok(true) } else if args.judge { judge(&args) } else { play(&args).map(|_| true) } }); match result { Ok(true) => {} Ok(false) => std::process::exit(1), Err(e) => { eprintln!("a7800-play: {e}"); std::process::exit(2); } } }