// SPDX-License-Identifier: MIT //! Big Top Bounce on the family's 2600 board (a2600-rust-fast), headless. //! //! bigtop-harness palettes write tools/palettes.txt (NTSC/PAL RGB) //! bigtop-harness run ROM [opts] run frames with scripted inputs, check lines //! bigtop-harness bot ROM [opts] a paddle bot plays; lines, probes, events, PNGs //! //! Common options: --machine ntsc|pal (the console's row), --lines 262|312 (the //! count every frame must have), --lbl FILE (ld65 labels; default ROM with .lbl), //! --start-bank N (the F6 bank at power-on), --out DIR (PNGs), --frames N. //! bot: --seed S, --game G (1-4), --skill F (0..1), --drop-top P (0..1: the chance of //! letting the ball fall from the top floor on purpose while bricks or targets remain). //! run: --script "FRAME:ACTION,..." where ACTION is reset, select, fire, pos=P, //! diffA, diffB (left switch), diffRA, diffRB (right), png=NAME, ram, probe, //! dump=A-B, poke=NAME[+OFF]=V, expect=NAME[+OFF]=V or NAME[+OFF]!=V (fails the run). //! Both commands report the stack's lowest byte and fail if it reaches the variables; //! `run` checks the pixel probes every 7th frame like the bot. use std::cell::RefCell; use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; use std::rc::Rc; use a2600::cartridge::{Options, Rom}; use a2600::controllers::Paddles; use a2600::machine::machine; use a2600::palettes::{palette, palettes, Palette}; use a2600::television::frame_png; use a2600::System; type Frame = Vec>; #[derive(Default)] struct Lines { count: usize, vsync: bool, frames: Vec, cur: Frame, last: Option, } #[derive(Default, Debug, Clone)] pub struct Timing { write: u64, value: u64, armed: bool, pub min_vb: i64, pub min_os: i64, pub samples: u64, /// lowest RAM byte written through page 1 (the stack; RAM mirrors there) pub min_stack: u16, } struct Game { timing: Rc>, sys: System, pads: Paddles, lines: Rc>, syms: HashMap, pal: &'static Palette, base_switches: u8, pub pos: f64, pub fire: bool, pub select: bool, pub reset: bool, pub left_a: bool, pub right_a: bool, checked: usize, expect: usize, play0: usize, pub bad_frames: Vec<(usize, usize)>, } impl Game { fn new(rom: &Path, lbl: &Path, mach: &str, start_bank: Option, expect: usize) -> Game { let row = machine(&format!("Atari VCS ({})", mach.to_uppercase())).expect("machine"); let opts = Options { start_bank, ..Options::default() }; let mut sys = System::from_rom(Rom::Path(rom), row, Some("F6"), opts).expect("load"); let lines = Rc::new(RefCell::new(Lines::default())); let l2 = lines.clone(); let tia = &mut sys.board_mut().tia; tia.on_line = Some(Box::new(move |tia| { let mut l = l2.borrow_mut(); let v = tia.vsync; if l.vsync && !v { let n = l.count; l.frames.push(n); l.count = 0; let f = std::mem::take(&mut l.cur); l.last = Some(f); } l.vsync = v; l.count += 1; if l.cur.len() < 400 { l.cur.push(tia.pixels[68..].to_vec()); } })); let pads = Paddles::new(&mut sys.board_mut().tia, row.timing.colour_clock_hz); let mut syms = HashMap::new(); for line in std::fs::read_to_string(lbl).expect("labels").lines() { let f: Vec<&str> = line.split_whitespace().collect(); if f.len() == 3 && f[0] == "al" { let a = u16::from_str_radix(f[1], 16).unwrap(); syms.insert(f[2].trim_start_matches('.').to_string(), a); } } let pal = palette(row.palette); let base_switches = row.switches; // timer margins: from each TIM64T write to the first arrival at the wait loop let timing = Rc::new(RefCell::new(Timing { min_vb: i64::MAX, min_os: i64::MAX, min_stack: 0xFF, ..Timing::default() })); let t2 = timing.clone(); let wvb = syms.get("WaitVB").copied().unwrap_or(0) & 0x1FFF; let wos = syms.get("WaitOS").copied().unwrap_or(0) & 0x1FFF; sys.board_mut().bus_observers.push(Box::new(move |kind, address, value, cycle| { let a = address & 0x1FFF; let mut t = t2.borrow_mut(); if kind == 'W' && a & 0x1380 == 0x0180 { t.min_stack = t.min_stack.min(a & 0xFF); } if kind == 'W' && a & 0x1297 == 0x0296 { t.write = cycle; t.value = value as u64; t.armed = true; } else if kind == 'R' && t.armed && (a == wvb || a == wos) { // TIMINT sets when the counter passes zero: (value + 1) intervals after the write let expiry = t.write + 1 + 64 * t.value; let margin = expiry as i64 - cycle as i64; if a == wvb { t.min_vb = t.min_vb.min(margin); } else { t.min_os = t.min_os.min(margin); } t.samples += 1; t.armed = false; } })); Game { timing, sys, pads, lines, syms, pal, base_switches, pos: 0.15, fire: false, select: false, reset: false, left_a: false, right_a: false, checked: 0, expect, play0: PLAY0_262 + expect.saturating_sub(262) / 2, bad_frames: Vec::new(), } } fn addr(&self, name: &str) -> u16 { *self.syms.get(name).unwrap_or_else(|| panic!("no symbol {name}")) } fn ram(&self, name: &str) -> u8 { let a = self.addr(name); self.sys.board().riot.borrow().ram[(a - 0x80) as usize] } fn ram_at(&self, name: &str, off: u16) -> u8 { let a = self.addr(name) + off; self.sys.board().riot.borrow().ram[(a - 0x80) as usize] } /// The highest RAM variable's address (the stack must stay above it). fn ram_top(&self) -> u16 { self.syms.values().copied().filter(|&a| (0x80..0x100).contains(&a)).max().unwrap_or(0x80) } fn poke(&mut self, name: &str, off: u16, v: u8) { let a = self.addr(name) + off; self.sys.board_mut().riot.borrow_mut().ram[(a - 0x80) as usize] = v; } /// Floors whose net is open (bit f), when the ROM has open nets (FloorOpen). fn open_mask(&self) -> u8 { // OpenTopOnly (2026-11-22): only the top floor, always. TopAlwaysOpen // (ff11fbf): the top always, the middle once its targets are cleared. // FloorOpen alone: the middle as above, the top while it has no balloons. if self.syms.contains_key("OpenTopOnly") { return 4; } if !self.syms.contains_key("FloorOpen") { return 0; } let top_empty = self.syms.contains_key("TopAlwaysOpen") || (0..3).all(|r| self.ram_at("balloons", r) == 0); (self.ram("cleared") & 2) | if top_empty { 4 } else { 0 } } fn snapshot(&self) -> Vec { self.sys.board().riot.borrow().ram.clone() } /// One frame with the held inputs; returns the number of frames whose line /// count was wrong so far. fn step(&mut self) { { *self.pads.position.borrow_mut() = [Some(self.pos.clamp(0.0, 1.0)), None, None, None]; let board = self.sys.board_mut(); let mut riot = board.riot.borrow_mut(); let a = if self.fire { 0x7F } else { 0xFF }; if riot.input_a != a { riot.set_input_a(a); } riot.input_b = (self.base_switches & 0x34) | 0x08 | (!self.reset as u8) | ((!self.select as u8) << 1) | ((self.left_a as u8) << 6) | ((self.right_a as u8) << 7); } self.sys.run_frames(1); let l = self.lines.borrow(); while self.checked < l.frames.len() { let n = l.frames[self.checked]; // the first two frames after power-on are partial if self.checked >= 2 && n != self.expect { self.bad_frames.push((self.checked, n)); } self.checked += 1; } } fn frame(&self) -> Option { self.lines.borrow().last.clone() } fn frames_seen(&self) -> usize { self.lines.borrow().frames.len() } fn png(&self, path: &Path) { if let Some(f) = self.frame() { std::fs::write(path, frame_png(&f, 2, Some(self.pal))).expect("png"); } } } // -------------------------------------------------------------------------- // Colours from src/colours.inc (NTSC or PAL branch). fn colours(root: &Path, pal: bool) -> HashMap { let text = std::fs::read_to_string(root.join("src/colours.inc")).expect("colours.inc"); let mut in_pal = false; let mut in_ntsc = false; let mut m = HashMap::new(); for line in text.lines() { if line.starts_with(".ifdef PALCOL") { in_pal = true; continue; } if line.starts_with(".else") { in_pal = false; in_ntsc = true; continue; } if line.starts_with(".endif") { break; } if let Some((k, v)) = line.split_once('=') { if (pal && in_pal) || (!pal && in_ntsc) { let v = u8::from_str_radix(v.trim().trim_start_matches('$'), 16).unwrap(); m.insert(k.trim().trim_start_matches("C_").to_string(), v); } } } m } // Play-area line i is frame line PLAY0_262 + i on a 262-line build (measured: // see `probe`); the 312-line build blanks 25 more lines above the picture. const PLAY0_262: usize = 59; /// Pixel probes: where the objects are drawn against where the RAM says they are. /// Returns (name, expected, measured) for each probe that applies this frame. /// The picture after step k shows what VBLANK k-1 prepared: objects moved in /// overscan as RAM stood after step k-2 (`s2`), the bat as after step k-1 (`s1`). fn probe(g: &Game, s1: &[u8], s2: &[u8], cols: &HashMap) -> Vec<(String, String, String)> { let mut out = Vec::new(); let Some(f) = g.frame() else { return out }; let play0 = g.play0; let r1 = |n: &str| s1[(g.addr(n) - 0x80) as usize]; let r2 = |n: &str| s2[(g.addr(n) - 0x80) as usize]; let r2o = |n: &str, o: u16| s2[(g.addr(n) + o - 0x80) as usize]; if f.len() < play0 + 170 { return out; } let state = r2("gameState"); if state != 1 && state != 2 || r1("gameState") != state || r1("floor") != r2("floor") { return out; } let floor = r2("floor"); let lit = |line: usize, c: u8| -> Vec { (0..160).filter(|&x| f[play0 + line][x] | 1 == c | 1 && f[play0 + line][x] != 0).collect() }; // open nets: the floor's bat is absent (both RAM states must agree) let open_in = |s: &[u8]| -> Option { if g.syms.contains_key("OpenTopOnly") { return Some(floor == 2); } if !g.syms.contains_key("FloorOpen") { return Some(false); } let b = |o: u16| s[(g.addr("balloons") + o - 0x80) as usize]; Some(match floor { 1 => s[(g.addr("cleared") - 0x80) as usize] & 2 != 0, 2 => g.syms.contains_key("TopAlwaysOpen") || b(0) | b(1) | b(2) == 0, _ => false, }) }; let open = open_in(s1); if open != open_in(s2) { return out; } let open = open == Some(true); // the bat's body (Y = 9, play line 161), first lit clock let batx = r1("batX") as usize; let kick = r1("kick"); // the ball (playfield colour, drawn above the players) hides what it covers: // skip a probe whose line the ball's 4 lines touch let ball_on = |line: usize| { [r1("ballY") as usize, r2("ballY") as usize].iter().any(|&y| y <= line && line < y + 4) }; if open { if !ball_on(161) { let mut xs = lit(161, cols["BAT"]); xs.extend(lit(161, cols["BATK"])); out.push(("net".into(), "None".into(), format!("{:?}", xs.first()))); } } else if kick == 0 && r2("kick") == 0 && !ball_on(161) && lit(161, cols["BATK"]).is_empty() { let c = if kick >= 16 { cols["BATK"] } else { cols["BAT"] }; let xs = lit(161, c); out.push(("bat".into(), format!("{batx}"), format!("{:?}", xs.first()))); } // the ball, when it is wholly inside an empty band let by = r2("ballY") as usize; let bx = r2("ballX") as usize; // since 2026-11-23 the ball and the walls of floors 1 and 2 take the power colour // of the ball's speed (PowerCol); both RAM states must agree on the speed let power = g.syms.contains_key("PowerCol") && floor > 0; if power && r1("speed") != r2("speed") { return out; } let wall = if power { let (s, p) = (r2("speed"), punch_speed()); if s >= p { cols["POW3"] } else if s + 1 == p { cols["POW2"] } else if s + 2 == p { cols["POW1"] } else { cols["WALL1"] } } else { cols[&format!("WALL{floor}")] }; if power { // the right wall on an empty line shows the power colour out.push(("power".into(), format!("{}", wall | 1), format!("{}", f[play0 + 120][150] | 1))); } let empty = match floor { 0 => (60..150).contains(&by), 1 => (60..86).contains(&by) || (102..150).contains(&by), _ => (60..150).contains(&by), }; if empty { let mut found = None; // search the empty bands only (the clown, the targets and the balloons may // share a power colour) for line in (58..152).filter(|l| floor != 1 || !(86..102).contains(l)) { let xs: Vec = lit(line, wall).into_iter().filter(|&x| (16..144).contains(&x)).collect(); if !xs.is_empty() { found = Some((line, xs[0], xs.len())); break; } } out.push(("ball".into(), format!("{:?}", Some((by, bx, 2))), format!("{found:?}"))); } if floor == 2 { // balloon rows: body line b6 = play line 20 + 19r (all 8 clocks lit) for r in 0..3u16 { let line = 20 + 19 * r as usize; let rx = r2o("rowX", r) as usize; let m = r2o("balloons", r); let mut want = Vec::new(); for k in 0..6 { let bit = [1, 8, 2, 16, 4, 32][k]; if m & bit != 0 { // a row drifting in is hidden behind the right wall from x 144 want.extend((rx + 16 * k..rx + 16 * k + 8).filter(|&x| x < 144)); } } // since 2026-11-22 a row's colour is the hits its balloons still need // (cleared bits 2+2r..3+2r); the probe then also checks the colour // (the 2026-11-22 build only; its HIT colours left colours.inc on 2026-11-23, // so for that build the row probes are skipped) if g.syms.contains_key("BalHitCol") { continue; } let (ca, cb) = { (cols[&format!("BAL{r}A")] | 1, cols[&format!("BAL{r}B")] | 1) }; let got: Vec = (16..144).filter(|&x| f[play0 + line][x] != 0 && (f[play0 + line][x] | 1 == ca || f[play0 + line][x] | 1 == cb)).collect(); if !ball_on(line) { out.push((format!("row{r}"), format!("{want:?}"), format!("{got:?}"))); } } } if floor == 1 { let cx = r2("clownX") as usize; if r2("clownHit") == 0 && !ball_on(10) { let xs = lit(10, cols["CL_WHITE"]); out.push(("clown".into(), format!("{:?}", Some(cx)), format!("{:?}", xs.first()))); } let b = r1("bumpCol"); let xs = lit(27, b); let starts: Vec = xs.iter().copied().filter(|&x| x == 0 || !xs.contains(&(x - 1))).collect(); let _ = starts; if !ball_on(27) { out.push(("bumpers".into(), "[44, 76, 108]".into(), format!("{:?}", group_starts(&xs, 8)))); } } out } /// Whether a probe's measurement matches what RAM says. fn probe_ok(name: &str, want: &str, got: &str) -> bool { if name == "bat" { got == format!("Some({want})") } else { got == want } } fn group_starts(xs: &[usize], gap: usize) -> Vec { let mut v = Vec::new(); let mut last: Option = None; for &x in xs { if last.map_or(true, |l| x > l + gap) { v.push(x); } last = Some(x); } v } // -------------------------------------------------------------------------- struct Rng(u64); impl Rng { fn next(&mut self) -> u64 { self.0 ^= self.0 << 13; self.0 ^= self.0 >> 7; self.0 ^= self.0 << 17; self.0 } fn f(&mut self) -> f64 { (self.next() >> 11) as f64 / (1u64 << 53) as f64 } fn range(&mut self, a: i64, b: i64) -> i64 { a + (self.next() % ((b - a + 1) as u64)) as i64 } } fn s16(lo: u8, hi: u8) -> f64 { ((hi as i8 as i32) * 256 + lo as i32) as f64 / 256.0 } /// The paddle position (0..1) that should put the bat's left edge at `x`. /// Charge time in lines is linear in the pot's resistance (DOC: the board's /// controllers.rs model, 380 lines at 1 MOhm); L counts lines from line 59. fn pos_for(x: f64, batw: f64) -> f64 { let l = 144.0 - batw - x + 2.0; ((l + 0.5) / 380.0 * 1.0018 - 0.0018).clamp(0.0, 1.0) } fn main() { let args: Vec = std::env::args().skip(1).collect(); let cmd = args.first().cloned().unwrap_or_default(); let mut opt: BTreeMap = BTreeMap::new(); let mut rom = None; let mut i = 1; while i < args.len() { if let Some(k) = args[i].strip_prefix("--") { opt.insert(k.to_string(), args.get(i + 1).cloned().unwrap_or_default()); i += 2; } else { rom = Some(PathBuf::from(&args[i])); i += 1; } } let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../.."); match cmd.as_str() { "palettes" => { let mut s = String::new(); for p in palettes() { if p.name == "ntsc" || p.name == "pal" { for (i, c) in p.colours.iter().enumerate() { s += &format!("{} {} {} {} {}\n", p.name, i, c.0, c.1, c.2); } } } std::fs::write(root.join("tools/palettes.txt"), s).unwrap(); } "run" | "bot" => { let rom = rom.expect("ROM"); let lbl = opt.get("lbl").map(PathBuf::from).unwrap_or_else(|| rom.with_extension("lbl")); let mach = opt.get("machine").cloned().unwrap_or("ntsc".into()); let expect: usize = opt.get("lines").map(|s| s.parse().unwrap()).unwrap_or(262); let start_bank = opt.get("start-bank").map(|s| s.parse().unwrap()); let frames: usize = opt.get("frames").map(|s| s.parse().unwrap()).unwrap_or(600); let out = opt.get("out").map(PathBuf::from); if let Some(o) = &out { std::fs::create_dir_all(o).unwrap(); } let mut g = Game::new(&rom, &lbl, &mach, start_bank, expect); let cols = colours(&root, mach != "ntsc"); if cmd == "run" { run_script(&mut g, frames, opt.get("script").cloned().unwrap_or_default(), out.as_deref(), &cols); } else { let seed: u64 = opt.get("seed").map(|s| s.parse().unwrap()).unwrap_or(1); let game: u8 = opt.get("game").map(|s| s.parse().unwrap()).unwrap_or(1); let skill: f64 = opt.get("skill").map(|s| s.parse().unwrap()).unwrap_or(0.85); let drop_top: f64 = opt.get("drop-top").map(|s| s.parse().unwrap()).unwrap_or(0.0); let ok = bot(&mut g, frames, seed, game, skill, drop_top, out.as_deref(), &cols); if !ok { std::process::exit(1); } } } _ => { eprintln!("usage: bigtop-harness palettes | run ROM [opts] | bot ROM [opts]"); std::process::exit(2); } } } fn run_script(g: &mut Game, frames: usize, script: String, out: Option<&Path>, cols: &HashMap) { let mut actions: BTreeMap> = BTreeMap::new(); for item in script.split(',').filter(|s| !s.is_empty()) { let (f, a) = item.split_once(':').expect("FRAME:ACTION"); actions.entry(f.parse().unwrap()).or_default().push(a.to_string()); } let mut hist_ram: Vec> = Vec::new(); let mut seen: std::collections::BTreeSet<(u8, u8, u8)> = Default::default(); let (mut probe_checks, mut probe_fail, mut net_checks, mut open_frames) = (0usize, 0usize, 0usize, 0usize); let (mut expect_ok, mut expect_fail) = (0usize, 0usize); for n in 0..frames { g.fire = false; g.select = false; g.reset = false; if let Some(acts) = actions.get(&n) { for a in acts { match a.as_str() { "reset" => g.reset = true, "select" => g.select = true, "fire" => g.fire = true, "diffA" => g.left_a = true, "diffB" => g.left_a = false, "diffRA" => g.right_a = true, "diffRB" => g.right_a = false, _ if a.starts_with("expect=") => { // expect=NAME[+OFF]=VALUE or NAME[+OFF]!=VALUE: a RAM check that fails the run let body = &a[7..]; let (lhs, v, eq) = match body.split_once("!=") { Some((l, v)) => (l, v, false), None => { let (l, v) = body.rsplit_once('=').expect("expect=NAME=VALUE"); (l, v, true) } }; let (name, off) = lhs.split_once('+').map_or((lhs, 0), |(n, o)| (n, o.parse().unwrap())); let got = g.ram_at(name, off); let want: u8 = v.parse().unwrap(); if (got == want) != eq { println!("frame {n} EXPECT FAILED: {body} (is {got})"); expect_fail += 1; } else { expect_ok += 1; } } _ if a.starts_with("poke=") => { // poke=NAME[+OFF]=VALUE: set a RAM variable (to reach states quickly) let (lhs, v) = a[5..].rsplit_once('=').expect("poke=NAME=VALUE"); let (name, off) = lhs.split_once('+').map_or((lhs, 0), |(n, o)| (n, o.parse().unwrap())); g.poke(name, off, v.parse().unwrap()); } _ if a.starts_with("pos=") => g.pos = a[4..].parse().unwrap(), _ if a.starts_with("png=") => { if let Some(o) = out { g.png(&o.join(&a[4..])); } } _ if a.starts_with("probe") => { // after step k: s1 = after k-1, s2 = after k-2 if hist_ram.len() == 3 { let (s1, s2) = (hist_ram[1].clone(), hist_ram[0].clone()); for (name, want, got) in probe(g, &s1, &s2, cols) { println!("frame {n} probe {name}: want {want} got {got}"); } } } _ if a.starts_with("dump") => { // dump=FIRST-LAST: play lines, one character per clock (. blank) let (a0, a1) = a[5..].split_once('-').unwrap(); let (a0, a1): (usize, usize) = (a0.parse().unwrap(), a1.parse().unwrap()); if let Some(f) = g.frame() { for l in a0..=a1 { let row: String = f[g.play0 + l].iter().map(|&c| if c == 0 { '.' } else { char::from_digit(((c >> 4) as u32) % 16, 16).unwrap() }).collect(); println!("{l:3} {row}"); } } } _ if a.starts_with("ram") => { let names = ["gameState", "floor", "ballX", "ballY", "batX", "batW", "curPlayer", "padY", "score", "balls", "level", "cleared", "msgT", "msgIdx", "balT", "drops", "dropT", "multK"]; let s: Vec = names.iter().filter(|k| g.syms.contains_key(**k)).map(|k| format!("{k}={}", g.ram(k))).collect(); println!("frame {n} {}", s.join(" ")); } _ => panic!("unknown action {a}"), } } } seen.insert((g.ram("gameState"), g.ram("floor"), g.ram("curPlayer"))); // every 7th frame: the pixel probes, as in the bot if n % 7 == 0 && hist_ram.len() == 3 { // the frame shown is after step n-1: s1 = after n-2, s2 = after n-3 for (name, want, got) in probe(g, &hist_ram[1], &hist_ram[0], cols) { probe_checks += 1; if !probe_ok(&name, &want, &got) { probe_fail += 1; if probe_fail <= 12 { println!("frame {n} probe {name}: want {want} got {got}"); } } if name == "net" { net_checks += 1; } } } if g.open_mask() & (1 << g.ram("floor")) != 0 && g.ram("gameState") == 2 { open_frames += 1; } g.step(); hist_ram.push(g.snapshot()); if hist_ram.len() > 3 { hist_ram.remove(0); } } println!("probes {probe_checks} ({net_checks} open-net), failed {probe_fail}; frames in play on an open floor {open_frames}"); println!("expectations {expect_ok} passed, {expect_fail} failed"); if expect_fail > 0 { println!("FAIL: {expect_fail} expectations"); std::process::exit(1); } let lines: Vec = g.lines.borrow().frames.clone(); let mut hist: BTreeMap = BTreeMap::new(); for &n in lines.iter().skip(2) { *hist.entry(n).or_default() += 1; } println!("frames {} line counts {:?} bad {}", g.frames_seen(), hist, g.bad_frames.len()); let states: std::collections::BTreeSet = seen.iter().map(|t| t.0).collect(); let players: std::collections::BTreeSet = seen.iter().map(|t| t.2).collect(); println!("states seen {:?} (0 title, 1 serve, 2 play, 3 lost, 4 over) players {:?} (state, floor, player) {:?}", states, players, seen); let t = g.timing.borrow().clone(); println!("timer margins (cycles left when the logic finished): VBLANK min {} overscan min {} ({} samples)", t.min_vb, t.min_os, t.samples); println!("stack: lowest byte ${:02X}, last RAM variable ${:02X}", t.min_stack, g.ram_top()); if t.min_stack <= g.ram_top() { println!("FAIL: the stack reached the variables"); std::process::exit(1); } if probe_fail > 0 { println!("FAIL: {probe_fail} of {probe_checks} probes"); std::process::exit(1); } if std::env::var("SHOW_FRAMES").is_ok() { println!("{:?}", lines); } if let Some(&(f, n)) = g.bad_frames.first() { println!("first bad frame {f}: {n} lines"); std::process::exit(1); } } #[derive(Default, Debug)] struct Stats { games: usize, floor_visits: [usize; 3], floor_frames: [usize; 3], clears: usize, bigtops: usize, balls_lost: usize, max_score: u32, kicks: usize, bat_hits: usize, probe_checks: usize, probe_fail: usize, game_over: usize, max_level: u8, drops: usize, /// play frames on a floor whose net is open open_frames: usize, /// the ball fell off a floor whose net was open open_falls: usize, /// the ball came down from the middle floor to the bricks down_to_bricks: usize, /// a balloon row started drifting back in refills: usize, /// middle-floor entries from the top floor, and those that went back up /// within BOUNCE_FRAMES (all causes, and with a clown hit in between) entries_from_top: usize, bounce_back: usize, bounce_clown: usize, /// approaches on the top floor let fall on purpose (--drop-top) top_drops: usize, /// every balloon popped / every drop target down, in play top_clears: usize, drop_clears: usize, /// balls that ended (lost), with how many balloon clears each had and the /// highest multiplier each reached balls_ended: usize, clears_per_ball: BTreeMap, mult_per_ball: BTreeMap, /// final scores of the games that ended game_scores: Vec, /// balloons popped while the speed was at PUNCH_SPEED or more (through), and /// below it (bounced); punch-through events (a run of through-pops until the /// speed falls below the threshold) and the pops in each punch_pops: usize, plain_pops: usize, punch_events: Vec, /// play frames at each speed step, and the lengths of runs at or above the threshold speed_frames: [usize; 8], above_runs: Vec, } /// The ROM's PUNCH_SPEED (src/physics.s), for the statistics and the power probe; /// BIGTOP_PUNCH overrides it for tuning builds. fn punch_speed() -> u8 { std::env::var("BIGTOP_PUNCH").ok().and_then(|s| s.parse().ok()).unwrap_or(5) } /// A middle-floor entry from above that returns to the top floor within this /// many frames counts as a bounce-back. const BOUNCE_FRAMES: usize = 30; fn bcd(g: &Game) -> u32 { let mut v = 0u32; for i in 0..3 { let b = g.ram_at("score", i); v = v * 100 + (b >> 4) as u32 * 10 + (b & 15) as u32; } v } #[allow(clippy::too_many_arguments)] fn bot(g: &mut Game, frames: usize, seed: u64, game: u8, skill: f64, drop_top: f64, out: Option<&Path>, cols: &HashMap) -> bool { let mut rng = Rng(seed.wrapping_mul(0x9E3779B97F4A7C15) | 1); let mut st = Stats::default(); // A shot is taken a few frames after its event: the picture lags the logic // (the frame shown after step k was prepared from the state of step k-1). let mut shots: HashMap = HashMap::new(); let pending: RefCell> = RefCell::new(Vec::new()); let mut shot = |_g: &Game, name: &str, n: usize| { if out.is_some() && !shots.contains_key(name) { shots.insert(name.to_string(), true); let delay = if name.starts_with("floor") && name != "floor-clear" || name == "kick" { 0 } else { 8 }; pending.borrow_mut().push((n + delay, name.to_string())); } }; let mut wait = 0i64; let mut aim = 0.0f64; let mut miss = false; let mut dropping = false; let mut last_vy_down = false; let mut corr = 0.0f64; let mut last_target = -1.0f64; let mut prev_state = 255u8; let mut prev_floor = 255u8; let mut still = 0usize; let mut last_pos = (0u8, 0u8, 0u8); let mut last_score_change = 0usize; let mut last_score = 0u32; let mut prev_cleared = 0u8; let mut prev_level = 0u8; let mut fail = false; let mut games_started = 0usize; let want_game = (game - 1) & 3; let mut fire_hold = 0; let mut failures: Vec = Vec::new(); let mut snaps: Vec> = Vec::new(); let mut fail_kinds: BTreeMap = BTreeMap::new(); let mut prev_open = 0u8; let mut prev_rowx = [0u8; 3]; let mut entry: Option = None; // frame of the last middle-floor entry from the top let mut prev_clown_hit = 0u8; let mut prev_bal = 0u8; let mut prev_drops = 0u8; let mut ball_clears = 0usize; let mut ball_mult = 1u8; let has_mult = g.syms.contains_key("multK"); let mut prev_speed = 0u8; let mut prev_count = 0u32; let mut cur_event = 0usize; let mut cur_run = 0usize; #[allow(non_snake_case)] let PUNCH_SPEED = punch_speed(); let mut last_clown_hit = 0usize; // frame the clown was last hit (its tumble timer started) for n in 0..frames { let state = g.ram("gameState"); let floor = g.ram("floor"); let open = g.open_mask(); let ch = g.ram("clownHit"); if ch > prev_clown_hit { last_clown_hit = n; } prev_clown_hit = ch; let bal = g.ram_at("balloons", 0) | g.ram_at("balloons", 1) | g.ram_at("balloons", 2); let drops = g.ram("drops"); if state == 2 && prev_state == 2 { if prev_bal != 0 && bal == 0 { st.top_clears += 1; ball_clears += 1; } if prev_drops != 0 && drops == 0 { st.drop_clears += 1; } } prev_bal = bal; // pops and speed let speed = g.ram("speed").min(7); let count: u32 = (0..3).map(|r| g.ram_at("balloons", r).count_ones()).sum(); if state == 2 && prev_state == 2 && count < prev_count { let d = (prev_count - count) as usize; if prev_speed >= PUNCH_SPEED { st.punch_pops += d; cur_event += d; } else { st.plain_pops += d; } } if cur_event > 0 && (speed < PUNCH_SPEED || state != 2) { st.punch_events.push(cur_event); if cur_event >= 2 { shot(g, "punch-through", n); } cur_event = 0; } if state == 2 { st.speed_frames[speed as usize] += 1; if speed >= PUNCH_SPEED { cur_run += 1; if floor > 0 { shot(g, &format!("power-floor{floor}"), n); } } } if cur_run > 0 && (speed < PUNCH_SPEED || state != 2) { st.above_runs.push(cur_run); cur_run = 0; } prev_speed = speed; prev_count = count; prev_drops = drops; // only in play: after a lost ball multK keeps its value until the next serve if has_mult && state == 2 { ball_mult = ball_mult.max(g.ram("multK") / 6 + 1); } if state == 3 && prev_state != 3 { st.balls_ended += 1; *st.clears_per_ball.entry(ball_clears).or_default() += 1; *st.mult_per_ball.entry(ball_mult).or_default() += 1; ball_clears = 0; ball_mult = 1; } if state == 2 && prev_state == 2 && floor != prev_floor { if floor < prev_floor && prev_open & (1 << prev_floor) != 0 { st.open_falls += 1; } if floor == 0 && prev_floor == 1 { st.down_to_bricks += 1; } if floor == 2 && prev_floor == 1 { if let Some(f) = entry { if n - f <= BOUNCE_FRAMES { st.bounce_back += 1; if last_clown_hit >= f { st.bounce_clown += 1; } println!("frame {n}: back up to the top floor {} frames after entering the middle", n - f); } } } entry = None; if floor == 1 && prev_floor == 2 { st.entries_from_top += 1; entry = Some(n); } } if state == 2 && open & (1 << floor) != 0 { st.open_frames += 1; shot(g, &format!("open-net{floor}"), n); } for r in 0..3u16 { let x = g.ram_at("rowX", r); if prev_rowx[r as usize] < 58 && x >= 140 { st.refills += 1; shot(g, "balloon-refill", n + 40); } prev_rowx[r as usize] = x; } prev_open = open; g.select = false; g.reset = false; if fire_hold > 0 { fire_hold -= 1; g.fire = true; } else { g.fire = false; } // difficulty: seeds alternate the bat width g.left_a = seed % 3 == 2; g.right_a = seed % 2 == 1; let batw = g.ram("batW") as f64; let batx = g.ram("batX") as f64; if state != prev_state { match state { 0 => shot(g, "title", n), 1 => shot(g, &format!("serve-p{}", g.ram("curPlayer") + 1), n), 3 => { st.balls_lost += 1; shot(g, "ball-lost", n); } 4 => { st.game_over += 1; shot(g, "game-over", n); st.game_scores.push(bcd(g)); let bricks: u32 = (0..6).map(|r| g.ram_at("bricks", r).count_ones()).sum(); println!( "frame {n}: game over, score {} level {} bricks left {bricks} targets left {}", bcd(g), g.ram("level"), g.ram("drops").count_ones() ); } _ => {} } if state == 1 && prev_state == 0 { games_started += 1; st.games += 1; } wait = rng.range(20, 90); } if state == 2 && floor != prev_floor { st.floor_visits[floor as usize] += 1; } if state == 2 { st.floor_frames[floor as usize] += 1; let by = g.ram("ballY"); if (70..140).contains(&by) { shot(g, &format!("floor{floor}"), n); } } let cleared = g.ram("cleared") & 3; // (bits 2-7: balloon toughness since 2026-11-22) let level = g.ram("level"); if cleared & !prev_cleared != 0 { st.clears += 1; shot(g, "floor-clear", n); println!("frame {n}: floor cleared ({cleared:03b}), score {}", bcd(g)); } if level > prev_level && state != 1 || (level > prev_level && prev_state == 2) { st.bigtops += 1; shot(g, "big-top", n); println!("frame {n}: BIG TOP, level {level}"); } st.max_level = st.max_level.max(level); prev_cleared = cleared; prev_level = level; if g.ram("msgT") > 0 && g.ram("msgIdx") == 6 && state == 1 { shot(g, "serve-p2-msg", n); } let score = bcd(g); if score != last_score { last_score = score; last_score_change = n; } st.max_score = st.max_score.max(score); match state { 0 => { // title: step to the wanted game with Select, then start with the button g.pos = 0.15; let gn = g.ram("gameNum"); if wait > 0 { wait -= 1; } else if gn != want_game { g.select = n % 2 == 0; if gn == 1 { shot(g, "select-game2", n); } } else if games_started % 2 == 1 { g.reset = true; // every other game starts with Game Reset wait = 40; } else { fire_hold = 2; wait = 40; } } 1 => { let t = rng.range(16, 120 - batw as i64) as f64; if wait > 0 { wait -= 1; if wait == 10 { last_target = t; } } else if fire_hold == 0 { fire_hold = 2; wait = 200; } if last_target >= 0.0 { g.pos = (pos_for(last_target, batw) + corr).clamp(0.0, 1.0); } } 2 => { let bx = g.ram("ballX") as f64 + g.ram("ballXL") as f64 / 256.0; let by = g.ram("ballY") as f64 + g.ram("ballYL") as f64 / 256.0; let vx = s16(g.ram("vxL"), g.ram("vxH")); let vy = s16(g.ram("vyL"), g.ram("vyH")); let down = vy > 0.0; if down && !last_vy_down { // a new approach: pick where on the bat to take it, and maybe miss let half = batw / 2.0 - 2.0; aim = rng.f() * 2.0 * half - half; miss = rng.f() > skill; // --drop-top P: a player after Big Top lets the ball fall from the // top floor on purpose (no cost) while the bricks or the drop // targets remain (draws no random number when P is 0) if drop_top > 0.0 && floor == 2 && g.ram("cleared") & 3 != 3 && rng.f() < drop_top { if !miss { st.top_drops += 1; } miss = true; } } if !down && last_vy_down && by > 140.0 { st.bat_hits += 1; } last_vy_down = down; let target_ball = if down && by < 156.0 { let t = (156.0 - by) / vy; let mut x = bx + vx * t; // reflect between 16 and 142 let span = 126.0; let mut u = (x - 16.0).rem_euclid(2.0 * span); if u > span { u = 2.0 * span - u; } x = 16.0 + u; x } else { bx }; let mut target = target_ball + 1.0 - batw / 2.0 + aim; // an emptied upper floor: let the ball drop to the floors still to clear let drop = floor > 0 && g.ram("cleared") & 3 & (1 << floor) != 0; if drop && down && by > 100.0 && !dropping { dropping = true; st.drops += 1; } if !down || floor == 0 { dropping = false; } if (miss || dropping) && down { target = if target_ball > 80.0 { 16.0 } else { 128.0 - batw + 16.0 }; } target = target.clamp(16.0, 144.0 - batw); // learn the mapping's offset from where the bat really went if last_target >= 0.0 && (last_target - batx).abs() < 30.0 { corr += (batx - last_target) * 0.15 / 380.0; corr = corr.clamp(-0.05, 0.05); } last_target = target; g.pos = (pos_for(target, batw) + corr).clamp(0.0, 1.0); // kick: just before the ball reaches the bat if down && by > 156.0 - vy * 6.0 && by < 156.0 && !miss && !dropping && g.ram("kick") == 0 && rng.f() < 0.25 { fire_hold = 1; st.kicks += 1; } if g.ram("kick") >= 16 && down { shot(g, "kick", n); } // lock-up: the ball has not moved let p = (g.ram("ballX"), g.ram("ballY"), floor); if p == last_pos { still += 1; if still > 120 { failures.push(format!("frame {n}: ball stuck at {p:?}")); fail = true; break; } } else { still = 0; } last_pos = p; if n - last_score_change > 60 * 120 { failures.push(format!("frame {n}: no score for two minutes in play")); fail = true; break; } } _ => {} } // pixel probes every 7th frame if n % 7 == 0 && snaps.len() == 3 { for (name, want, got) in probe(g, &snaps[1], &snaps[0], cols) { st.probe_checks += 1; if !probe_ok(&name, &want, &got) { *fail_kinds.entry(name.clone()).or_insert(0usize) += 1; st.probe_fail += 1; if st.probe_fail <= 12 { println!("frame {n} probe {name}: want {want} got {got}"); if let Some(o) = out { g.png(&o.join(format!("probe-fail-{n}-{name}.png"))); } } } } } prev_state = state; prev_floor = floor; if let Some(o) = out { for (due, name) in pending.borrow().iter() { if *due == n { g.png(&o.join(format!("{name}.png"))); println!("frame {n}: shot {name}"); } } } g.step(); snaps.push(g.snapshot()); if snaps.len() > 3 { snaps.remove(0); } if !g.bad_frames.is_empty() { let (f, l) = g.bad_frames[0]; failures.push(format!("frame {f} has {l} lines (state {state}, floor {floor})")); if let Some(o) = out { g.png(&o.join("bad-frame.png")); } fail = true; break; } } let lines: Vec = g.lines.borrow().frames.clone(); let mut hist: BTreeMap = BTreeMap::new(); for &n in lines.iter().skip(2) { *hist.entry(n).or_default() += 1; } println!("seed {seed} game {game}: {st:?}"); let tot: usize = st.floor_frames.iter().sum::().max(1); let pct = |k: usize| 100.0 * st.floor_frames[k] as f64 / tot as f64; println!( "summary: play frames {tot}; floor shares bottom {:.1}% middle {:.1}% top {:.1}%; open floor {:.1}%; \ games {} game overs {} balls lost {} Big Tops {} max level {}; down to bricks {} open falls {} refills {}; \ entries from top {} back up within {BOUNCE_FRAMES} frames {} (clown {}); top drops on purpose {}", pct(0), pct(1), pct(2), 100.0 * st.open_frames as f64 / tot as f64, st.games, st.game_over, st.balls_lost, st.bigtops, st.max_level, st.down_to_bricks, st.open_falls, st.refills, st.entries_from_top, st.bounce_back, st.bounce_clown, st.top_drops ); println!( "per ball: balls ended {} top clears {} drop clears {}; balloon clears per ball {:?}; highest multiplier per ball {:?}", st.balls_ended, st.top_clears, st.drop_clears, st.clears_per_ball, st.mult_per_ball ); println!("game scores {:?}", st.game_scores); println!( "power: punch pops {} plain pops {}; punch events {:?}; speed frames {:?}; runs at or above {} {:?}", st.punch_pops, st.plain_pops, st.punch_events, st.speed_frames, punch_speed(), st.above_runs ); println!("line counts {hist:?}"); let t = g.timing.borrow().clone(); println!("timer margins (cycles left when the logic finished): VBLANK min {} overscan min {} ({} samples)", t.min_vb, t.min_os, t.samples); println!("stack: lowest byte ${:02X}, last RAM variable ${:02X}", t.min_stack, g.ram_top()); if t.min_vb < 0 || t.min_os < 0 { failures.push("logic overran a timer".into()); fail = true; } if t.min_stack <= g.ram_top() { failures.push("the stack reached the variables".into()); fail = true; } for f in &failures { println!("FAIL {f}"); } if st.probe_fail > 0 { println!("FAIL {} of {} probes: {:?}", st.probe_fail, st.probe_checks, fail_kinds); fail = true; } !fail }