//! Can a challenging stage be cleared? A search for the most hits on the //! real board: plays MOVIE (with its DIPs and path mod) to frame FROM, just //! before a challenging stage, then runs a beam search over the rest of the //! stage: from each of the best partial runs it tries several futures of a //! shooter that leads its targets, keeps the best (fewest enemies escaped, //! then most hits), and so on until the stage ends. A run with every enemy hit proves the stage can be //! cleared; the run is written as a movie. Usage: //! galaga-gallery MOVIE.json FROM OUT.json [--beam B] [--tries K] [--seed S] [--rom DIR] //! [--mod FILE [--mod-at F]] //! //! --mod lays a path mod over the board at frame F (default FROM - 100, so //! before the stage is set up), for scoring a design without recording a //! movie with it; no movie is written then. //! //! A hit is an enemy slot entering state 0x04 (exploding), counted only //! for flights that began in the stage; the stage ends when the stage number //! at 0x9821 changes (docs/ram-map.md). The verdict is the game's own: its //! challenge hit counter at 0x9288 (reset about 55 frames into the stage, //! then +1 a hit; what "NUMBER OF HITS" shows; measured 2026-10-01). The //! planner's spawn count misses some of the 40. The counter can over-count: //! two rockets meeting one enemy a frame apart count twice (measured with //! the dual fighter: all 40 destroyed, "NUMBER OF HITS 41", no PERFECT), so //! an over-count ranks like an escape. //! //! How it aims: a challenging stage is a fixed script (measured: enemies fly //! the same whatever the ship does; kills only bring the next wave sooner, //! on a 32-frame beat), so before each segment it plays the board forward //! with the ship idle to forecast every enemy's position, and plans rockets //! against that forecast with the measured ship and rocket physics. //! //! With the dual fighter (0x9827 set at FROM, as in a `galaga-tas --dual` //! movie) it aims the pair: a press fires one double rocket centred between //! the ships, 8 px right of slot 0x31, two lanes 15 px apart (measured //! 2026-10-01), so it reaches 7 px further each side. //! //! Status (2026-10-02): a flight begins when a free slot starts flying (not //! only through state 0x07, which hid 4 of the 40 from the planner). It //! fires as fast as the 51xx allows, a press held two frames and released //! two. With one ship it reaches 38 of 40 on the original first challenging //! stage and 38-40 on the remix's; with the dual fighter the game calls //! every remix stage PERFECT (proofs/). `--seek-double` ranks runs by the //! most double counts instead, to look for them. use std::path::PathBuf; use emu_galaga::galaga::movie::{ram_crc32, Movie}; use emu_galaga::galaga::objects::{objects, slot, state, Object}; use emu_galaga::galaga::roms::load_directory; use emu_galaga::galaga::snapshot::Snapshot; use emu_galaga::galaga::sound::Sound; use emu_galaga::galaga::video::{Video, SCREEN_HEIGHT, SCREEN_WIDTH}; use emu_galaga::galaga::Machine; const SEGMENT: u64 = 30; const RIGHT: u8 = 0x02; const LEFT: u8 = 0x08; const FIRE: u8 = 0x01; struct Rng(u64); impl Rng { fn next(&mut self) -> u64 { self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15); let mut z = self.0; z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); z ^ (z >> 31) } fn below(&mut self, n: u64) -> u64 { self.next() % n } } /// Frames from a fire press to the rocket appearing at the ship, the /// rocket's start Y (the ship's centre) and climb per frame; the ship's /// speed (1 and 2 px on alternate frames) and its 3-frame start delay. All /// measured on the board (2026-09-30). const ROCKET_DELAY: usize = 4; const ROCKET_START_Y: i32 = 265; const ROCKET_CLIMB: i32 = 6; /// How close a rocket must pass to count, assumed conservatively (the board /// judges every planned shot anyway). const HIT_X: i32 = 5; const HIT_Y: i32 = 7; /// How far ahead the forecast looks. const HORIZON: usize = 150; /// Where every enemy slot will be on each coming frame if the ship does /// nothing: the board played forward from a snapshot. Challenge enemies fly /// the same whatever the ship does (measured), so this is exact for every /// enemy not shot down meanwhile. type Forecast = Vec<[Option<(i32, i32)>; 0x30]>; fn forecast(board: &mut Board, snap: &Snapshot) -> Forecast { board .machine .restore(snap, &mut board.video, &mut board.sound) .unwrap(); (0..HORIZON) .map(|_| { board.machine.set_controls([0, 0]); board.machine.run_frame(); let objs = objects(&board.machine.shared.borrow()); std::array::from_fn(|i| { let o = objs[i]; (matches!(o.state, state::ENTERING | state::DIVING | state::SPAWNED) && o.on_screen()) .then(|| o.center()) }) }) .collect() } /// For a rocket fired at forecast frame `t` (pressed then), where must the /// ship be to hit `slot`, if anywhere: the enemy's X when the rocket meets it. fn intercept(future: &Forecast, slot: usize, t: usize) -> Option { for j in 0..45 { let at = t + ROCKET_DELAY + j; let (ex, ey) = future.get(at)?[slot]?; let ry = ROCKET_START_Y - ROCKET_CLIMB * j as i32; if (ey - ry).abs() <= HIT_Y { return Some(ex); } if ry < ey - HIT_Y { return None; } } None } /// The planning shooter: picks a target among the soonest-lost reachable /// ones (at random among the first few, so the search has choices), moves to /// where a rocket fired now would meet it, fires when lined up within the /// hit window and a rocket is free. struct Shooter { rng: Rng, target: Option, until: u64, /// The dual fighter: the rocket's centre is 8 px right of slot 0x31 and /// its reach 7 px wider each side. dual: bool, /// Frames left of the current press and release (4 in all). fire_frames: u8, } impl Shooter { fn controls(&mut self, frame: u64, t: usize, future: &Forecast, now: &[Object; 64]) -> [u8; 2] { // Where a rocket fired now flies up, and how near it must pass. let (gun, reach) = if self.dual { (8, HIT_X + 7) } else { (0, HIT_X) }; let ship_x = now[slot::FIGHTER as usize].center().0 + gun; let rockets_free = (0x32..=0x33) .filter(|&i| { let (x, y) = now[i].center(); !(now[i].state == state::SHOT && (8..270).contains(&y) && x != 247) }) .count(); let reachable = |slot: usize| -> Option<(usize, i32)> { // The first forecast frame from which the ship can get under it. (t..future.len().saturating_sub(ROCKET_DELAY)).find_map(|ft| { let x = intercept(future, slot, ft)?; let travel = ((ft - t) as f32 * 1.5) as i32 - 4; ((x - ship_x).abs() <= travel.max(0) + reach).then_some((ft, x)) }) }; let alive = |slot: usize| future.get(t).and_then(|f| f[slot]).is_some(); if frame >= self.until || self .target .is_none_or(|s| !alive(s) || reachable(s).is_none()) { let mut options: Vec<(usize, usize)> = (0..0x30) .filter(|&s| alive(s)) .filter_map(|s| { // Urgency: how soon it can no longer be reached. let last = (t..future.len().saturating_sub(ROCKET_DELAY)) .rev() .find(|&ft| intercept(future, s, ft).is_some())?; reachable(s).map(|_| (last, s)) }) .collect(); options.sort(); self.target = if options.is_empty() { None } else { let pick = self.rng.below(options.len().min(3) as u64) as usize; Some(options[pick].1) }; self.until = frame + 6 + self.rng.below(16); } let mut stick = 0; let mut fire = 0; if let Some(target) = self.target { if let Some((_, x)) = reachable(target) { if x > ship_x + 1 { stick = RIGHT; } else if x < ship_x - 1 { stick = LEFT; } } } // Fire when a rocket pressed now would hit anything. The 51xx counts // a press only after two frames down and two up (docs/custom-io.md): // hold each press two frames, then release two. if self.fire_frames > 0 { self.fire_frames -= 1; if self.fire_frames >= 2 { fire = FIRE; } } else if rockets_free > 0 { let hits_something = (0..0x30).any(|s| { alive(s) && intercept(future, s, t).is_some_and(|x| (x - ship_x).abs() < reach) }); if hits_something { fire = FIRE; self.fire_frames = 3; } } [stick, fire] } } struct Board { machine: Machine, video: Video, sound: Sound, } #[derive(Clone)] struct Node { snap: Snapshot, inputs: Vec<[u8; 2]>, hits: u32, /// Enemies that left the screen alive: misses for good. The best a run /// can still reach is 40 minus these, so the beam ranks by them first. escaped: u32, /// Each escape: frame, slot and where it was last seen. escapes: Vec<(u64, usize, (i32, i32))>, /// The game's counter beyond the hits seen: double counts (or, before /// the counter's reset early in the stage, its leftover, the same for /// every run). excess: u32, spawned: u32, /// Slots whose current flight began in this stage (a leftover diver /// from the stage before is not part of the challenge). ours: u64, before: [Object; 64], done: bool, } /// One candidate future: SEGMENT frames of a fresh shooter from `node`. fn expand(board: &mut Board, node: &Node, seed: u64, from: usize, stage: u8) -> Node { let future = forecast(board, &node.snap); board .machine .restore(&node.snap, &mut board.video, &mut board.sound) .unwrap(); let mut shooter = Shooter { rng: Rng(seed), target: None, until: 0, dual: board.machine.shared.borrow().ram3[0x27] != 0, fire_frames: 0, }; let mut n = Node { snap: node.snap.clone(), inputs: node.inputs.clone(), hits: node.hits, escaped: node.escaped, escapes: node.escapes.clone(), excess: node.excess, spawned: node.spawned, ours: node.ours, before: node.before, done: false, }; for t in 0..SEGMENT as usize { let frame = (from + n.inputs.len()) as u64; let now = objects(&board.machine.shared.borrow()); // The forecast's frame 0 is the frame about to run. let c = shooter.controls(frame, t, &future, &now); board.machine.set_controls(c); board.machine.run_frame(); n.inputs.push(c); let after = objects(&board.machine.shared.borrow()); for i in 0..0x30 { let bit = 1u64 << i; // A flight begins when a free slot starts flying (most pass // through 0x07, spawned, but not all: measured). if now[i].state == state::FREE && matches!( after[i].state, state::ENTERING | state::DIVING | state::SPAWNED ) { n.spawned += 1; n.ours |= bit; } if n.ours & bit == 0 { continue; } if after[i].state == state::EXPLODING && now[i].state != state::EXPLODING { n.hits += 1; n.ours &= !bit; } if after[i].state == state::FREE && matches!( now[i].state, state::ENTERING | state::DIVING | state::SPAWNED ) { n.escaped += 1; n.escapes.push((frame, i, now[i].center())); n.ours &= !bit; } } n.before = now; let s = board.machine.shared.borrow(); // The counter steps a frame before the explosion shows: allow one // hit in hand. n.excess = u32::from(s.ram2[0x288]).saturating_sub(n.hits + 1); if s.ram3[0x21] != stage || s.ram1[0x62] == state::FIGHTER_EXPLODING { n.done = true; break; } } n.snap = board.machine.snapshot(&board.video, &board.sound); n } fn main() { let args: Vec = std::env::args().skip(1).collect(); if args.len() < 3 { eprintln!( "usage: galaga-gallery MOVIE.json FROM OUT.json [--beam B] [--tries K] [--seed S]" ); std::process::exit(2); } let source = Movie::from_json(&std::fs::read_to_string(&args[0]).unwrap()).unwrap(); let from: usize = args[1].parse().expect("FROM"); let out = PathBuf::from(&args[2]); let (mut beam_width, mut tries, mut seed) = (24usize, 12u64, 1u64); // --seek-double: rank by the most double counts instead (for checking the // game's double count against MAME on the stock ROMs). let mut seek_double = false; let mut rom_dir = PathBuf::from("rom/galaga"); let mut late_mod: Option = None; let mut mod_at: Option = None; let mut rest = args[3..].iter(); while let Some(a) = rest.next() { let mut v = || rest.next().unwrap().clone(); match a.as_str() { "--beam" => beam_width = v().parse().unwrap(), "--tries" => tries = v().parse().unwrap(), "--seed" => seed = v().parse().unwrap(), "--seek-double" => seek_double = true, "--rom" => rom_dir = PathBuf::from(v()), "--mod" => { late_mod = Some( emu_galaga::galaga::paths::PathMod::load(std::path::Path::new(&v())).unwrap(), ) } "--mod-at" => mod_at = Some(v().parse().unwrap()), _ => panic!("unknown argument {a}"), } } let roms = load_directory(&rom_dir).unwrap(); let mut board = Board { machine: Machine::new(&roms), video: Video::new(&roms), sound: Sound::new(&roms), }; source.setup(&mut board.machine).unwrap(); let prefix: Vec<[u8; 2]> = source.inputs().into_iter().take(from).collect(); let mod_at = mod_at.unwrap_or(from.saturating_sub(100)); for (f, &c) in prefix.iter().enumerate() { if f == mod_at { if let Some(m) = &late_mod { m.check(&roms.sub).unwrap(); m.apply_over(&mut board.machine, &roms).unwrap(); } } board.machine.set_controls(c); board.machine.run_frame(); } let stage = board.machine.shared.borrow().ram3[0x21]; let dual = board.machine.shared.borrow().ram3[0x27] != 0; eprintln!( "start: frame {from}, stage {stage}, {}", if dual { "dual fighter" } else { "one ship" } ); let start = Node { snap: board.machine.snapshot(&board.video, &board.sound), inputs: Vec::new(), hits: 0, escaped: 0, escapes: Vec::new(), excess: 0, spawned: 0, ours: 0, before: objects(&board.machine.shared.borrow()), done: false, }; let mut beam = vec![start]; let mut rng = Rng(seed); let mut step = 0; while beam.iter().any(|n| !n.done) && step < 200 { step += 1; let mut next: Vec = beam.iter().filter(|n| n.done).cloned().collect(); // Every (partial run, seed) pair is independent: spread them over // threads, one board each. let jobs: Vec<(usize, u64)> = beam .iter() .enumerate() .filter(|(_, n)| !n.done) .flat_map(|(i, _)| (0..tries).map(move |_| i)) .map(|i| (i, rng.next())) .collect(); let threads = std::thread::available_parallelism().map_or(8, |n| n.get()); let chunk = jobs.len().div_ceil(threads).max(1); let results: Vec> = std::thread::scope(|scope| { jobs.chunks(chunk) .map(|part| { let (roms, beam, source, late_mod) = (&roms, &beam, &source, &late_mod); scope.spawn(move || { let mut board = Board { machine: Machine::new(roms), video: Video::new(roms), sound: Sound::new(roms), }; // Snapshots hold RAM, not program patches: every // worker's board carries the movie's mod too. source.setup(&mut board.machine).unwrap(); if let Some(m) = late_mod { m.apply_over(&mut board.machine, roms).unwrap(); } part.iter() .map(|&(i, seed)| expand(&mut board, &beam[i], seed, from, stage)) .collect::>() }) }) .collect::>() .into_iter() .map(|h| h.join().unwrap()) .collect() }); next.extend(results.into_iter().flatten()); // Best first; a little randomness among equals keeps the beam varied // (drawn once per candidate: the sort needs a consistent order). #[allow(clippy::type_complexity)] let mut keyed: Vec<((std::cmp::Reverse, u32, u32), u32, u64, Node)> = next .into_iter() .map(|n| { let key = if seek_double { (std::cmp::Reverse(n.excess), 0, n.hits) } else { (std::cmp::Reverse(0), n.escaped + n.excess, n.hits) }; (key, n.hits, rng.next(), n) }) .collect(); keyed.sort_by_key(|(key, hits, tie, _)| (key.0, key.1, std::cmp::Reverse(*hits), *tie)); let mut next: Vec = keyed.into_iter().map(|(_, _, _, n)| n).collect(); next.truncate(beam_width); beam = next; let best = &beam[0]; eprintln!( "step {step:3}: best {} hits, {} escaped, of {} spawned so far", best.hits, best.escaped, best.spawned ); } let best = beam .into_iter() .min_by_key(|n| { if seek_double { (std::cmp::Reverse(n.excess), 0, std::cmp::Reverse(n.hits)) } else { ( std::cmp::Reverse(0), n.escaped + n.excess, std::cmp::Reverse(n.hits), ) } }) .unwrap(); if let Some(m) = &late_mod { board .machine .restore(&best.snap, &mut board.video, &mut board.sound) .unwrap(); let game_hits = board.machine.shared.borrow().ram2[0x288]; println!( "galaga-gallery: from frame {from} (stage {stage}, {}) of {} with {}, beam {beam_width} x {tries}: {} hits, the game counts {game_hits}{}", if dual { "dual fighter" } else { "one ship" }, args[0], m.name, best.hits, if game_hits == 40 && best.hits == 40 { " (PERFECT)" } else { "" } ); println!( " {} spawned, {} hits, {} escaped; still marked live at the end: {:?}", best.spawned, best.hits, best.escaped, (0..0x30) .filter(|i| best.ours & (1 << i) != 0) .collect::>() ); for (f, slot, at) in &best.escapes { println!(" escaped: slot {slot:02x} at frame {f}, last seen at {at:?}"); } return; } // Replay from power-on: the movie must reproduce the searched run. let mut inputs = prefix.clone(); inputs.extend_from_slice(&best.inputs); let mut check = Machine::new(&roms); source.setup(&mut check).unwrap(); for &c in &inputs { check.set_controls(c); check.run_frame(); } board .machine .restore(&best.snap, &mut board.video, &mut board.sound) .unwrap(); assert_eq!( ram_crc32(&check), ram_crc32(&board.machine), "replay differs" ); // The game's own count, as its results screen shows it. let game_hits = check.shared.borrow().ram2[0x288]; let note = format!( "galaga-gallery: from frame {from} (stage {stage}, {}) of {}, beam {beam_width} x {tries}: the game counts {game_hits} hits{}", if dual { "dual fighter" } else { "one ship" }, args[0], if game_hits == 40 { " (PERFECT)" } else { "" } ); let mut movie = Movie::from_inputs(source.dsw_a, source.dsw_b, &inputs, &check, ¬e); movie.patches = source.patches.clone(); movie.path_mod = source.path_mod.clone(); std::fs::write(&out, movie.to_json()).unwrap(); // The results screen, a few seconds on, for the record. let mut video = Video::new(&roms); for _ in 0..200 { check.set_controls([0, 0]); check.run_frame(); } video.render(&check.shared.borrow(), check.videolatch_at_vblank_end); let mut rgba = vec![0u8; SCREEN_WIDTH * SCREEN_HEIGHT * 4]; video.screen_rgba(&mut rgba); let mut ppm = format!("P6 {SCREEN_WIDTH} {SCREEN_HEIGHT} 255\n").into_bytes(); for px in rgba.chunks(4) { ppm.extend_from_slice(&px[..3]); } std::fs::write(out.with_extension("results.ppm"), ppm).unwrap(); println!("{note}\n-> {}", out.display()); }