From ceaf55ad485be1aeb6828f485f07006ecb70c145 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 04:01:16 +0000 Subject: [PATCH] macros: a yard's one door is taken, and a split map's exits are the fly's own piece's Cerulean's badge house back door leaves the fly on (9, 9), the door tile of a closed yard; the pad was empty for the rest of the survey. - The exit walks fall back on a step-fired warp underfoot once every listed goal has failed the route search (goals_of set it aside while any other exit was listed, reachable or not). - The decoded grid marks warp carpets (warp_carpet_tile_ids.asm) on the maps whose ExtraWarpCheck reads them; a walk whose goal is a warp underfoot bumps toward one (CheckWarpsCollision) instead of row 64's sideways step-off, which fires nothing on a tile that is no door. - The badge house is on the map graph and the yard is a piece of Cerulean, so GO OUT in the house takes the front door. - path::exits keeps the fly's own piece on a split map: refusals from the yard no longer rest the town's exits for the whole map. - The 12.28 guarantee reads where the fly stands: a same-map teleport moved it. ROM test row65_the_fly_leaves_the_cerulean_badge_houses_back_yard (FLY_ROW65_YARD_CHECKPOINT); scene_probe's route survey can save its caught frame (FLY_PROBE_SAVE without FLY_PROBE_SAVE_RANK). --- .../src/pokemon_red/macros/executor.rs | 81 +++++++-- .../src/pokemon_red/macros/geography.rs | 99 +++++++++- .../src/pokemon_red/macros/path.rs | 16 ++ .../src/pokemon_red/macros/state.rs | 26 +++ .../src/pokemon_red/macros/tests.rs | 170 +++++++++++++++++- .../flybrain-gb/src/pokemon_red/mapgrid.rs | 49 +++++ .../src/pokemon_red/mapgrid/tests.rs | 38 ++++ .../flybrain-gb/src/pokemon_red/maps.rs | 4 + .../crates/flysim/examples/scene_probe.rs | 9 + .../crates/flysim/tests/rom_macros_mode.rs | 102 +++++++++++ 10 files changed, 578 insertions(+), 16 deletions(-) diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/executor.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/executor.rs index 26335b9..783c48b 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/executor.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/executor.rs @@ -1638,9 +1638,11 @@ fn walk_frame(walk: &mut Walk, state: &mut dyn MacroState) -> Progress { walk.held += 1; if walk.held <= SETTLE_FRAMES { Progress::Hold(buttons::NONE) - } else if settled_on_a_way_out(walk) { - // Still on this map (the top of this function ends the walk on any other): - // the way out did not take the fly anywhere ([`Walk::unfired`]). + } else if settled_on_a_way_out(walk) && walk.arrived == Some(here) { + // Still on this map (the top of this function ends the walk on any other), + // and still on the tile it settled on: the way out did not take the fly + // anywhere ([`Walk::unfired`]). A warp that moves the fly on its own map -- + // the Saffron Gym's pads, Silph Co.'s -- has taken it somewhere (row 65). walk.unfired = true; Progress::Blocked } else { @@ -1982,18 +1984,31 @@ fn script( MacroKind::GoWarp => Way::Passage, _ => Way::Route, }; - let goals = exit_goals(state, way); + let (goals, mut underfoot) = exit_goals(state, way); unreachable.extend(goal_keys(&goals)); // A last resort that preferred the way toward the objective, and the route search // cannot reach it: the rest of the last resort, nearest reachable first (row 57). - let walked = match walk_to(state, goals) { - Some(walked) => Some(walked), - None => { - let rest = super::palette::last_resort_wide(state, way); - let wide = goals_of(state, rest); - if wide.is_empty() { None } else { walk_to(state, wide) } + let mut walked = walk_to(state, goals); + if walked.is_none() { + let rest = super::palette::last_resort_wide(state, way); + underfoot.extend(underfoot_warps(state, &rest)); + let wide = goals_of(state, rest); + if !wide.is_empty() { + walked = walk_to(state, wide); } - }; + } + // **The door underfoot, when no other way of this kind can be walked to** (row 65). + // [`goals_of`] sets a step-fired warp underfoot aside while any other exit is listed, + // reachable or not, so a fly standing on the one door out of a closed yard -- the + // Cerulean badge house's back door, whose yard has no other exit -- refused + // `no route` at every other exit and never took the one it stood on: the pad emptied + // for as long as the survey ran. Only here, after every listed goal has failed the + // route search: it is the step off and back on that row 64 taught the walk + // ([`Walk::step_off`]), and the executor's own rule still ends it `blocked` if the + // map does not change. + if walked.is_none() && !underfoot.is_empty() { + walked = walk_to(state, underfoot); + } let (walk, target) = walked?; aimed = target; vec![Step::Walk(walk)] @@ -2332,7 +2347,7 @@ fn walk_then( let budget = walk_budget(route.steps.len()); // Standing on the goal already, and the goal is a warp that fires by itself: the arrival // would settle where the warp has plainly not fired ([`Walk::step_off`]). - let step_off = route + let mut step_off = route .goal .and_then(|index| goals.get(index)) .filter(|goal| { @@ -2342,6 +2357,23 @@ fn walk_then( && matches!(goal.key, Some(TargetKey::Exit(ExitId::Warp(_)))) }) .map(|goal| goal.tile); + // ...unless the cartridge takes it by a bump from where the fly stands (row 65): a warp whose + // own tile is no door, with a warp carpet in front one way, fires on a press that way + // (`CheckWarpsCollision`, [`super::state::MapGrid::carpet_press`]) and on no step back onto it + // made any other way. The Cerulean badge house's back door is one: stepped off sideways and + // back on, it did nothing. + let mut goals = goals; + if step_off.is_some() + && let Some(bump) = state + .map_grid() + .filter(|grid| grid.map() == map) + .and_then(|grid| grid.carpet_press(here.x, here.y)) + { + step_off = None; + for goal in goals.iter_mut().filter(|goal| goal.tile == here && goal.arrival == Arrival::Settle) { + goal.arrival = Arrival::Leave(bump); + } + } Some(( Walk { goals, @@ -2397,9 +2429,30 @@ fn one_target(goals: &[Goal]) -> Option { /// by itself has plainly not fired, so it is not an exit to walk to — which is the state the fly /// is in the moment it comes down a staircase and lands on the warp tile. A doormat underfoot is /// different: its press is the point, so it stays. -fn exit_goals(state: &mut dyn MacroState, way: Way) -> Vec { +/// +/// The second list is the step-fired warps underfoot that [`goals_of`] set aside, for the exit +/// script to fall back on when nothing in the first can be walked to (row 65). +fn exit_goals(state: &mut dyn MacroState, way: Way) -> (Vec, Vec) { let exits = ways(state, way); - goals_of(state, exits) + let underfoot = underfoot_warps(state, &exits); + (goals_of(state, exits), underfoot) +} + +/// The step-fired warps of `exits` the fly is standing on, as goals: what [`goals_of`] sets aside +/// while another exit is listed, for the exit script to fall back on when none of those can be +/// walked to (row 65). +/// +/// [`walk_then`] takes it the way the cartridge does from where the fly stands: a bump toward a +/// warp carpet where there is one, row 64's step off and back on otherwise. +fn underfoot_warps(state: &mut dyn MacroState, exits: &[Exit]) -> Vec { + let Some(here) = state.player().map(|player| Tile::new(player.x, player.y)) else { + return Vec::new(); + }; + exits + .iter() + .filter(|exit| exit.tile == here && exit.press.is_none() && matches!(exit.id, ExitId::Warp(_))) + .map(|exit| Goal { tile: exit.tile, arrival: Arrival::Settle, key: Some(TargetKey::Exit(exit.id)) }) + .collect() } /// [`exit_goals`] over a list of exits the caller already has. diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/geography.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/geography.rs index fffb3cc..39c8efc 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/geography.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/geography.rs @@ -167,6 +167,12 @@ const LINKS: &[(u8, u8)] = &[ (maps::CERULEAN_GYM, maps::CERULEAN_CITY), (maps::CERULEAN_MART, maps::CERULEAN_CITY), (maps::CERULEAN_POKECENTER, maps::CERULEAN_CITY), + // The badge house (row 65): no rung place needs a route through it, but its back door at + // (9, 9) is the only way into or out of a closed yard, so without it on the graph Cerulean is + // one piece and the house's two doors are the same door to every `GO OUT` -- the nearest one, + // which from the back door's arrival is the back door. Which piece each door opens onto is + // [`SPLIT`]'s business. + (maps::CERULEAN_BADGE_HOUSE, maps::CERULEAN_CITY), (maps::ROCK_TUNNEL_1F, maps::ROUTE_10), (maps::INDIGO_PLATEAU_LOBBY, maps::INDIGO_PLATEAU), ]; @@ -242,6 +248,11 @@ const B2F_MAIN: u8 = 0; const B2F_NORTH: u8 = 1; const B2F_SOUTH: u8 = 2; +/// Cerulean City's town, and the closed yard behind the badge house. +const CERULEAN_TOWN: u8 = 0; +#[cfg(test)] +const CERULEAN_YARD: u8 = 1; + /// Every map whose ground is in pieces, with each piece's doors and neighbours. /// /// Every row is measured from the disassembly at the pinned commit: the map's blocks, its @@ -262,6 +273,12 @@ const B2F_SOUTH: u8 = 2; /// to dead ends on B2F. /// - **`MT_MOON_B2F`** (row 59): the fossil floor, one large piece with the two ladders the road /// uses, and two small pieces under the dead-end ladders. +/// - **`CERULEAN_CITY`** (row 65): the town, and a closed yard of 33 tiles behind the badge house +/// whose one way out is the house's back door at (9, 9). Row 59's flood found it and left it +/// off because the house was not on the graph; the fly found it in a survey and stood in it with +/// an empty pad for 32,000 frames. The flood's third piece -- a strip of the west edge beside +/// Cerulean Cave's mouth, reached over water -- has no door on the graph and stays unlisted, so +/// the Route 4 edge and the cave are the town's as before. const SPLIT: &[Split] = &[ Split { map: maps::ROUTE_2, @@ -297,7 +314,7 @@ const SPLIT: &[Split] = &[ doors: &[(2, 24, 5)], next: &[ Region::piece(maps::MT_MOON_B1F, B1F_EXIT), - Region::whole(maps::CERULEAN_CITY), + Region::piece(maps::CERULEAN_CITY, CERULEAN_TOWN), ], }, ], @@ -355,12 +372,65 @@ const SPLIT: &[Split] = &[ }, ], }, + Split { + map: maps::CERULEAN_CITY, + pieces: &[ + Piece { + doors: &[ + (0, 27, 11), + (1, 13, 15), + (2, 19, 17), + (3, 30, 19), + (4, 13, 25), + (5, 25, 25), + (7, 27, 9), + (8, 9, 11), + ], + next: &[ + Region::whole(maps::ROUTE_24), + Region::whole(maps::ROUTE_5), + Region::piece(maps::ROUTE_4, EAST_SIDE), + Region::whole(maps::ROUTE_9), + Region::whole(maps::CERULEAN_POKECENTER), + Region::whole(maps::CERULEAN_GYM), + Region::whole(maps::CERULEAN_MART), + Region::whole(maps::CERULEAN_BADGE_HOUSE), + ], + }, + Piece { doors: &[(9, 9, 9)], next: &[Region::whole(maps::CERULEAN_BADGE_HOUSE)] }, + ], + }, ]; fn split_of(map: u8) -> Option<&'static Split> { SPLIT.iter().find(|split| split.map == map) } +/// Whether `map`'s ground is in pieces ([`SPLIT`] has a row for it). +pub fn is_split(map: u8) -> bool { + split_of(map).is_some() +} + +/// Whether warp `index` of `from`'s map stands on the piece `from` (row 65). +/// +/// A warp another piece lists is on ground no walk from here reaches, so it is not a way out of +/// here: from the Cerulean yard the town's eight doors, and from the town the yard's. A warp no +/// piece lists -- a door off the graph -- is not claimed either way and stays a way out. +pub fn warp_on(from: Region, index: u8) -> bool { + let Some(split) = split_of(from.map) else { return true }; + pieces(split) + .find(|(_, piece)| piece.doors.iter().any(|(door, _, _)| *door == index)) + .is_none_or(|(part, _)| part == from.part) +} + +/// Whether the edge of `from`'s map onto `to` is stepped off the piece `from` (row 65): the piece +/// lists `to` among what is one step from it, or no piece does. +pub fn edge_on(from: Region, to: u8) -> bool { + let Some(split) = split_of(from.map) else { return true }; + let mut owners = pieces(split).filter(|(_, piece)| piece.next.iter().any(|next| next.map == to)).peekable(); + owners.peek().is_none() || owners.any(|(part, _)| part == from.part) +} + /// The pieces of a split map with their numbers, which are their [`Region::part`]s. fn pieces(split: &'static Split) -> impl Iterator { split.pieces.iter().enumerate().filter_map(|(part, piece)| Some((u8::try_from(part).ok()?, piece))) @@ -874,6 +944,33 @@ mod tests { } } + #[test] + fn cerulean_is_a_town_and_a_yard_and_the_badge_houses_back_door_is_the_yards() { + // Row 65. The yard behind the badge house is 33 tiles with one way out, the house's back + // door at (9, 9) (Cerulean's warp 9). From the house the road to anywhere is the front + // door, which opens on the town; from the yard it is the house. + let yard = Region::piece(maps::CERULEAN_CITY, CERULEAN_YARD); + let town = Region::piece(maps::CERULEAN_CITY, CERULEAN_TOWN); + assert_eq!(town, Region::whole(maps::CERULEAN_CITY), "the town is the piece every old row names"); + assert_eq!(region_at(maps::CERULEAN_CITY, 9, 9), yard); + assert_eq!(region_at(maps::CERULEAN_CITY, 9, 12), town); + assert_eq!(arrival_by_warp(maps::CERULEAN_CITY, 9), Some(yard), "the back door lands in the yard"); + assert_eq!(arrival_by_warp(maps::CERULEAN_CITY, 8), Some(town), "the front door in the town"); + let house = Region::whole(maps::CERULEAN_BADGE_HOUSE); + assert_eq!(next_step(house, maps::CERULEAN_GYM), Some(town)); + assert_eq!(next_step(yard, maps::CERULEAN_GYM), Some(house)); + assert_eq!(hops(yard, maps::CERULEAN_GYM), Some(3)); + assert_eq!(arrival_by_edge(maps::CERULEAN_CITY, maps::ROUTE_4), Some(town)); + // What is on which piece, for the exit list (`path::exits`). + assert!(warp_on(yard, 9) && !warp_on(yard, 8) && !warp_on(town, 9) && warp_on(town, 8)); + assert!(warp_on(yard, 6) && warp_on(town, 6), "the cave's mouth is no piece's door"); + assert!(!edge_on(yard, maps::ROUTE_24) && edge_on(town, maps::ROUTE_24)); + assert!(warp_on(Region::whole(maps::PEWTER_CITY), 3), "an unsplit map claims nothing"); + // Route 4's sides, which row 59 split, answer the same question. + let west = Region::piece(maps::ROUTE_4, WEST_SIDE); + assert!(warp_on(west, 1) && !warp_on(west, 2) && !edge_on(west, maps::CERULEAN_CITY)); + } + #[test] fn the_road_from_pewter_to_cerulean_is_through_mt_moon_one_chamber_at_a_time() { // Row 59. Every step of the road, as the pieces the fly stands in, measured from the diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/path.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/path.rs index dd26c04..3350784 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/path.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/path.rs @@ -431,9 +431,20 @@ pub fn exits(state: &mut dyn MacroState) -> Vec { let grid = state.map_grid(); let grid = grid.as_deref(); let here_outdoors = outdoors(player.map); + // **On a map in pieces, a way out on another piece is not a way out of here** (row 65, + // section 12.24's pieces). From the Cerulean yard every one of the town's doors and edges was + // a candidate the route search refused, and each refusal rested that exit for the whole map -- + // so a fly that got out of the yard found the town's ways out resting (a survey: an empty pad + // outside the badge house's front door for the rest of the window). A warp no piece lists is + // not claimed either way ([`geography::warp_on`]). + let piece = geography::is_split(player.map) + .then(|| geography::region_on(player.map, player.x, player.y, grid)); let mut out = Vec::new(); for (index, warp) in state.warps().iter().enumerate() { let Ok(id) = u8::try_from(index) else { continue }; + if piece.is_some_and(|piece| !geography::warp_on(piece, id)) { + continue; + } let tile = Tile::new(warp.x, warp.y); // Section 9.1's classification, from the destination map id and nothing else. Outdoors // every warp is a door into somewhere new, which is a route; indoors the destination @@ -470,6 +481,11 @@ pub fn exits(state: &mut dyn MacroState) -> Vec { // the cartridge does not normally do -- it is still a way out of the building. let way = if here_outdoors { Way::Route } else { Way::Exit }; let into = geography::connected(player.map, edge); + if let (Some(piece), Some(to)) = (piece, into) + && !geography::edge_on(piece, to) + { + continue; + } for tile in edge_tiles(facing, size.width, size.height) { // Not `== Yes`: without a grid the walkable predicate's window is the screen, so the // far edge of an outdoor map reads `Unknown` from anywhere but next to it, and diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/state.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/state.rs index ae01242..245fdb2 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/state.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/state.rs @@ -446,6 +446,9 @@ pub struct MapGrid { /// Row-major bitmask of the directions a press out of this tile hops a ledge in /// ([`MapGrid::ledge`]), landing two tiles that way. hops: Vec, + /// Row-major bitmask of the directions whose tile in front is a warp carpet + /// ([`MapGrid::carpet`]): from a warp on this tile, a bump that way warps (row 65). + carpets: Vec, } impl MapGrid { @@ -460,6 +463,7 @@ impl MapGrid { ids: vec![None; cells], walls: vec![0; cells], hops: vec![0; cells], + carpets: vec![0; cells], } } @@ -508,6 +512,28 @@ impl MapGrid { self.index(x, y).is_some_and(|index| self.hops[index] & wall_bit(facing) != 0) } + /// Record that the tile in front of `(x, y)` in `facing` is a warp carpet + /// (`data/tilesets/warp_carpet_tile_ids.asm`), on a map whose `ExtraWarpCheck` reads it. + pub fn carpet(&mut self, x: u8, y: u8, facing: Facing) { + if let Some(index) = self.index(x, y) { + self.carpets[index] |= wall_bit(facing); + } + } + + /// The direction a fly standing on a warp at `(x, y)` presses to take it by bumping, when the + /// cartridge would: the tile in front that way is a warp carpet ([`MapGrid::carpet`]). + /// + /// Row 65. A warp whose own tile is not a door fires only through `ExtraWarpCheck`: at the end + /// of a step onto it with the direction still held, or on a bump while standing on it + /// (`CheckWarpsCollision`), and on the OVERWORLD tileset both ask `IsWarpTileInFrontOfPlayer`. + /// Down first, the order pokered lists the carpets in. + pub fn carpet_press(&self, x: u8, y: u8) -> Option { + let bits = self.index(x, y).map_or(0, |index| self.carpets[index]); + [Facing::Down, Facing::Up, Facing::Left, Facing::Right] + .into_iter() + .find(|facing| bits & wall_bit(*facing) != 0) + } + /// Whether the player could stand on this tile. Off the map is [`Walkable::No`], which is the /// window predicate's own answer for it. pub fn walkable(&self, x: u8, y: u8) -> Walkable { diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs index 4948ab9..98b96e5 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs @@ -215,6 +215,16 @@ struct World { /// [`path::exits`]'s `outward`, for the executor's rule about a way out that did not take the /// fly anywhere. duds: BTreeSet, + /// Warp carpets, as the tile a bump is made from and its direction (row 65): standing on a + /// warp there, a press that way into ground the fly cannot enter fires it + /// (`CheckWarpsCollision`). With it non-empty the world has a decoded grid. + carpets: Vec<(Tile, Facing)>, + /// Same-map teleports, as the pad and where it puts the player (row 65): the Saffron Gym's + /// pads and Silph Co.'s move the fly on its own map a few frames after it stands on one, with + /// no scene change. + teleports: Vec<(Tile, Tile)>, + /// Frames the player has stood on a teleport pad. + on_pad: u32, /// A frame at which the cartridge takes the joypad, which is what the Viridian gate does. scripted_at: Option, /// Every completed pulse, in order. @@ -301,6 +311,9 @@ impl World { ledges: Vec::new(), hop: None, duds: BTreeSet::new(), + carpets: Vec::new(), + teleports: Vec::new(), + on_pad: 0, scripted_at: None, pulses: Vec::new(), held: 0, @@ -485,6 +498,16 @@ impl World { self.pulses.push(self.previous); self.on_pulse(self.previous); } + match self.teleports.iter().find(|(pad, _)| *pad == self.player).copied() { + Some((_, to)) => { + self.on_pad += 1; + if self.on_pad >= 8 { + self.player = to; + self.on_pad = 0; + } + } + None => self.on_pad = 0, + } if self.scene == Scene::Overworld { match direction_of(mask) { Some(facing) => { @@ -629,6 +652,13 @@ impl World { return; } if self.walkable(next.x, next.y) != Walkable::Yes { + // A bump while standing on a warp, toward a carpet: `CheckWarpsCollision` (row 65). + if self.carpets.contains(&(self.player, facing)) + && let Some(warp) = + self.warps.iter().find(|warp| warp.x == self.player.x && warp.y == self.player.y) + { + self.map = warp.destination_map; + } return; } self.player = next; @@ -856,7 +886,7 @@ impl MacroState for World { /// The decoded grid, only for a world with ledges in it (row 64): the same walls the window /// reads, plus the hops. Every other fixture keeps answering from the window, as before. fn map_grid(&mut self) -> Option> { - if self.ledges.is_empty() { + if self.ledges.is_empty() && self.carpets.is_empty() { return None; } let mut grid = super::state::MapGrid::new(self.map, self.size.width, self.size.height); @@ -869,6 +899,9 @@ impl MacroState for World { for (tile, facing) in &self.ledges { grid.ledge(tile.x, tile.y, *facing); } + for (tile, facing) in &self.carpets { + grid.carpet(tile.x, tile.y, *facing); + } Some(std::sync::Arc::new(grid)) } } @@ -6106,3 +6139,138 @@ fn pick_opt(world: &mut World, kind: MacroKind) -> bool { let scene = world.scene(); Palette::for_scene(scene, world).slots.iter().any(|slot| slot.is_some_and(|spec| spec.kind == kind)) } + +#[test] +fn a_door_underfoot_is_taken_when_no_other_way_out_can_be_walked_to() { + // Row 65, the Cerulean badge house's back yard: the fly stands on the one door out of ground + // walled off from every other exit. The exit walks set a step-fired door underfoot aside while + // any other exit is listed, reachable or not, so `GO OUT` refused `no route` at the far door + // for as long as it was dealt and never took the one underfoot. It now falls back on it, the + // way row 64 taught the walk to take a ladder: a step off and the step back on. + let mut world = World::room().at(3, 3).wall(&[(5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (5, 7)]); + world.warps = vec![ + Warp { x: 3, y: 3, destination_warp: 0, destination_map: 0x00 }, + Warp { x: 7, y: 3, destination_warp: 1, destination_map: 0x00 }, + ]; + assert_eq!(run(&mut world, MacroKind::GoOut), Ok(MacroAbort::Done)); + assert_eq!(world.map, 0x00, "the door underfoot was taken"); + assert!(!world.pulses.is_empty(), "by a step off it and back on"); + + // With the other door reachable, it is still the one walked to: the fallback is a fallback. + let mut open = World::room().at(3, 3); + open.warps = world.warps.clone(); + open.warps[1].destination_map = 0x01; + assert_eq!(run(&mut open, MacroKind::GoOut), Ok(MacroAbort::Done)); + assert_eq!(open.map, 0x01, "the reachable door, not the one underfoot"); +} + +#[test] +fn a_door_underfoot_that_fires_on_a_bump_is_bumped_and_not_stepped_off() { + // The same yard, measured on the cartridge: the back door's tile is no door tile, so a step + // back onto it sideways fires nothing (`duds`), and the cartridge takes it on a bump toward + // the house -- a warp carpet in front, `CheckWarpsCollision` for a player standing on a warp. + let wall: Vec<(u8, u8)> = (0..8).map(|y| (5, y)).chain([(3, 4)]).collect(); + let mut world = World::room().at(3, 3).wall(&wall); + world.warps = vec![ + Warp { x: 3, y: 3, destination_warp: 0, destination_map: 0x00 }, + Warp { x: 7, y: 3, destination_warp: 1, destination_map: 0x00 }, + ]; + world.duds = BTreeSet::from([Tile::new(3, 3)]); + world.carpets = vec![(Tile::new(3, 3), Facing::Down)]; + assert_eq!(run(&mut world, MacroKind::GoOut), Ok(MacroAbort::Done)); + assert_eq!(world.map, 0x00, "the bump took the door"); + assert!(world.pulses.iter().all(|mask| *mask == buttons::DOWN), "a press down and nothing else"); + + // The row-64 step off alone is what this tile does not answer: with no carpet it ends + // `blocked`, the executor's rule for a way out that went nowhere. + let mut stepped = World::room().at(3, 3).wall(&wall); + stepped.warps = world.warps.clone(); + stepped.duds = world.duds.clone(); + assert_eq!(run(&mut stepped, MacroKind::GoOut), Ok(MacroAbort::Blocked)); + assert_eq!(stepped.map, 0x25); +} + +#[test] +fn a_floor_whose_way_on_is_a_passage_deals_no_go_out_back_the_way_it_came() { + // Row 65, Mt. Moon 1F: the objective is Cerulean, the road is the ladder at (5, 5) into B1F's + // west chamber, and the cave mouth leads back onto Route 4, where the run has been. `GO OUT`'s + // "a room has to be leavable" fallback dealt the mouth anyway, one step from the tile the fly + // arrives on, and Route 4's `GO ROUTE` walked straight back in. + let mut world = World::room().at(3, 6); + world.map = maps::MT_MOON_1F; + world.size = MapSize { width: 8, height: 8 }; + world.warps = vec![ + Warp { x: 3, y: 7, destination_warp: 1, destination_map: maps::ROUTE_4 }, + Warp { x: 5, y: 2, destination_warp: 0, destination_map: maps::MT_MOON_B1F }, + ]; + // The centre beside the mouth has been visited, so it is no errand: the objective is the rung. + world.seen_maps = BTreeSet::from([maps::ROUTE_4, maps::MT_MOON_B1F, maps::MT_MOON_POKECENTER]); + world.objective = Some(Objective { map: maps::CERULEAN_CITY, tile: None, warp: None, edge: None, target: None }); + assert!(ways(&mut world, Way::Exit).is_empty(), "no way out: the road is the ladder"); + assert!(!on_the_pad(&mut world, MacroKind::GoOut)); + assert!(on_the_pad(&mut world, MacroKind::GoWarp), "the ladder is the way on"); + + // The escape hatch every suppression has: a ladder no walk reaches rests in the window, and + // the mouth is a way out again. + world.targets.record_blocked(maps::MT_MOON_1F, TargetKey::Exit(ExitId::Warp(1))); + assert_eq!(ways(&mut world, Way::Exit).len(), 1); + assert!(on_the_pad(&mut world, MacroKind::GoOut)); + + // And a party that needs the nurse still has its way out, under the button that says why. + let mut hurt = World::room().at(3, 6); + hurt.map = maps::MT_MOON_1F; + hurt.warps = world.warps.clone(); + hurt.seen_maps = world.seen_maps.clone(); + hurt.objective = world.objective; + hurt.mons = vec![mon(0, 5, 20, &[(33, 30)])]; + assert!(!on_the_pad(&mut hurt, MacroKind::GoOut)); + assert!(on_the_pad(&mut hurt, MacroKind::GoHeal), "GO HEAL walks out to the centre"); +} + +#[test] +fn a_way_out_on_another_piece_of_a_split_map_is_not_a_way_out_of_this_one() { + // Row 65, Cerulean City's yard behind the badge house. Every door and edge of the town was a + // way out of the yard for the route search to refuse, and each refusal rested that exit for + // the whole map: out of the yard at last, the fly found the town's exits, the gym's door + // among them, resting. On a split map the exits are the fly's own piece's. + let mut world = World::room().at(9, 9); + world.map = maps::CERULEAN_CITY; + world.size = MapSize { width: 40, height: 36 }; + world.connections = Connections { north: true, south: true, east: true, west: true }; + world.warps = [(27, 11), (13, 15), (19, 17), (30, 19), (13, 25), (25, 25), (4, 11), (27, 9), (9, 11), (9, 9)] + .iter() + .map(|(x, y)| Warp { x: *x, y: *y, destination_warp: 0, destination_map: 0x40 }) + .collect(); + let exits = path::exits(&mut world); + let ids: Vec = exits.iter().map(|exit| exit.id).collect(); + assert!(ids.contains(&ExitId::Warp(9)), "the back door is the yard's"); + assert!(ids.contains(&ExitId::Warp(6)), "the cave's mouth is no piece's, and not claimed"); + assert!(!ids.contains(&ExitId::Warp(8)), "the front door is the town's: {ids:?}"); + assert!(!ids.iter().any(|id| matches!(id, ExitId::Edge(_))), "the town's edges: {ids:?}"); + + // From the town it is the other way round. + world.player = Tile::new(9, 12); + let ids: Vec = path::exits(&mut world).iter().map(|exit| exit.id).collect(); + assert!(ids.contains(&ExitId::Warp(8)) && !ids.contains(&ExitId::Warp(9)), "{ids:?}"); + assert!(ids.iter().any(|id| matches!(id, ExitId::Edge(_))), "{ids:?}"); +} + +#[test] +fn a_same_map_teleport_is_somewhere_the_way_out_took_the_fly() { + // Row 65, the row-64 review's note: the executor's guarantee (a way out that leaves the fly on + // its map is not done) read the tile the walk settled on, so a warp that moves the fly on its + // own map -- the Saffron Gym's pads, Silph Co.'s -- would read as one that did not fire. The + // fly has gone somewhere when it no longer stands where it settled. + let mut world = World::room().at(3, 3); + world.warps = vec![Warp { x: 3, y: 5, destination_warp: 0, destination_map: 0x25 }]; + world.duds = BTreeSet::from([Tile::new(3, 5)]); + world.teleports = vec![(Tile::new(3, 5), Tile::new(6, 1))]; + assert_eq!(run(&mut world, MacroKind::GoWarp), Ok(MacroAbort::Done)); + assert_eq!((world.map, world.player), (0x25, Tile::new(6, 1)), "moved by the pad"); + + // A pad that does nothing is still the guarantee's case. + let mut dead = World::room().at(3, 3); + dead.warps = world.warps.clone(); + dead.duds = world.duds.clone(); + assert_eq!(run(&mut dead, MacroKind::GoWarp), Ok(MacroAbort::Blocked)); +} diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid.rs index 0a76ceb..728d690 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid.rs @@ -80,7 +80,35 @@ const ANCHOR_ROW: usize = 1; pub mod tileset { pub const OVERWORLD: u8 = 0; pub const FOREST: u8 = 3; + pub const SHIP: u8 = 13; + pub const SHIP_PORT: u8 = 14; pub const CAVERN: u8 = 17; + pub const PLATEAU: u8 = 23; +} + +/// `WarpTileListPointers` at the pinned pokered commit (`data/tilesets/warp_carpet_tile_ids.asm`): +/// per facing, the tile ids in front of the player that `IsWarpTileInFrontOfPlayer` answers yes +/// to. +pub const WARP_CARPET_TILES: [(Facing, &[u8]); 4] = [ + (Facing::Down, &[0x01, 0x12, 0x17, 0x3d, 0x04, 0x18, 0x33]), + (Facing::Up, &[0x01, 0x5c]), + (Facing::Left, &[0x1a, 0x4b]), + (Facing::Right, &[0x0f, 0x4e]), +]; + +/// Whether `ExtraWarpCheck` asks `IsWarpTileInFrontOfPlayer` on this map (`home/overworld.asm`): +/// the OVERWORLD, SHIP, SHIP_PORT and PLATEAU tilesets and four maps by id, except the S.S. Anne's +/// 3F, which asks `IsPlayerFacingEdgeOfMap` like every other map. +fn carpets_apply(tileset: u8, map: u8) -> bool { + const SS_ANNE_3F: u8 = 0x61; + const ROCKET_HIDEOUT_B1F: u8 = 0xc7; + const ROCKET_HIDEOUT_B2F: u8 = 0xc8; + const ROCKET_HIDEOUT_B4F: u8 = 0xca; + if map == SS_ANNE_3F { + return false; + } + matches!(map, ROCKET_HIDEOUT_B1F | ROCKET_HIDEOUT_B2F | ROCKET_HIDEOUT_B4F | super::maps::ROCK_TUNNEL_1F) + || matches!(tileset, tileset::OVERWORLD | tileset::SHIP | tileset::SHIP_PORT | tileset::PLATEAU) } /// `TilePairCollisionsLand` at the pinned pokered commit, as `(tileset, one tile, the other)`. @@ -207,9 +235,30 @@ pub fn decode(map: u8, width_blocks: u8, height_blocks: u8, blocks: &[u8], tiles } add_pair_walls(&mut grid, tiles.id); add_ledge_hops(&mut grid, tiles.id); + add_warp_carpets(&mut grid, tiles.id, map); grid } +/// Mark, for every tile, the directions whose tile in front is a warp carpet ([`WARP_CARPET_TILES`]), +/// on a map whose `ExtraWarpCheck` reads them ([`carpets_apply`]). Only a warp's own tile ever +/// asks ([`MapGrid::carpet_press`], row 65). +fn add_warp_carpets(grid: &mut MapGrid, tileset: u8, map: u8) { + if !carpets_apply(tileset, map) { + return; + } + for y in 0..grid.height() { + for x in 0..grid.width() { + for (facing, carpets) in WARP_CARPET_TILES { + let (dx, dy) = facing.delta(); + let (Some(nx), Some(ny)) = (checked_step(x, dx), checked_step(y, dy)) else { continue }; + if grid.tile_id(nx, ny).is_some_and(|tile| carpets.contains(&tile)) { + grid.carpet(x, y, facing); + } + } + } + } +} + /// Mark every ledge the loaded tileset has as a hop out of the tile in front of it ([`LEDGE_TILES`]). /// /// Only where the cartridge would take it: the OVERWORLD tileset, a ledge tile in front, and a diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid/tests.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid/tests.rs index 0b6c3a8..9125155 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid/tests.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid/tests.rs @@ -196,3 +196,41 @@ fn a_ledge_is_a_hop_from_above_on_the_overworld_tileset_only() { add_ledge_hops(&mut edge, tileset::OVERWORLD); assert!(!edge.hops(0, 0, Facing::Down)); } + +#[test] +fn a_warp_carpet_in_front_is_marked_where_extra_warp_check_reads_it() { + // Row 65, the Cerulean badge house's back door: a warp whose own tile is no door, with a + // carpet tile in front of it facing down (`$12`, `warp_carpet_tile_ids.asm`). The bump that + // way is how the cartridge takes it from where the fly stands. + let mut grid = MapGrid::new(0x03, 1, 3); + grid.set(0, 0, 0x2c, Walkable::Yes); + grid.set(0, 1, 0x2c, Walkable::Yes); + grid.set(0, 2, 0x12, Walkable::No); + add_warp_carpets(&mut grid, tileset::OVERWORLD, 0x03); + assert_eq!(grid.carpet_press(0, 1), Some(Facing::Down), "a bump down, into the carpet"); + assert_eq!(grid.carpet_press(0, 0), None, "two tiles off is not in front"); + + // A carpet id is only a carpet in the facing pokered lists it under: `$12` is a down carpet. + let mut up = MapGrid::new(0x03, 1, 2); + up.set(0, 0, 0x12, Walkable::No); + up.set(0, 1, 0x2c, Walkable::Yes); + add_warp_carpets(&mut up, tileset::OVERWORLD, 0x03); + assert_eq!(up.carpet_press(0, 1), None); + + // A cave asks `IsPlayerFacingEdgeOfMap` instead, and so does the S.S. Anne's 3F on SHIP. + let mut cave = MapGrid::new(0x3b, 1, 3); + for y in 0..3 { + cave.set(0, y, grid.tile_id(0, y).unwrap_or(0), grid.walkable(0, y)); + } + add_warp_carpets(&mut cave, tileset::CAVERN, 0x3b); + assert_eq!(cave.carpet_press(0, 1), None, "no carpets in a cave"); + let mut rock_tunnel = cave.clone(); + add_warp_carpets(&mut rock_tunnel, tileset::CAVERN, super::super::maps::ROCK_TUNNEL_1F); + assert_eq!(rock_tunnel.carpet_press(0, 1), Some(Facing::Down), "Rock Tunnel 1F is named"); + let mut ship = MapGrid::new(0x61, 1, 3); + for y in 0..3 { + ship.set(0, y, grid.tile_id(0, y).unwrap_or(0), grid.walkable(0, y)); + } + add_warp_carpets(&mut ship, tileset::SHIP, 0x61); + assert_eq!(ship.carpet_press(0, 1), None, "the S.S. Anne's 3F asks the edge"); +} diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/maps.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/maps.rs index f306cf2..e752ac3 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/maps.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/maps.rs @@ -92,3 +92,7 @@ pub const CERULEAN_MART: u8 = 0x43; pub const MT_MOON_POKECENTER: u8 = 0x44; pub const ROCK_TUNNEL_1F: u8 = 0x52; pub const INDIGO_PLATEAU_LOBBY: u8 = 0xae; +/// The house beside Cerulean's west road whose back door is the one way into the closed yard at +/// (9, 9) (row 65). Confirmed by the cartridge rather than by counting: Cerulean City's warp table +/// names `$e6` at (9, 11) and at (9, 9), read from the yard's own survey checkpoint. +pub const CERULEAN_BADGE_HOUSE: u8 = 0xe6; diff --git a/services/flysim/crates/flysim/examples/scene_probe.rs b/services/flysim/crates/flysim/examples/scene_probe.rs index bb2f317..6950d94 100644 --- a/services/flysim/crates/flysim/examples/scene_probe.rs +++ b/services/flysim/crates/flysim/examples/scene_probe.rs @@ -1608,6 +1608,15 @@ fn route_survey( let (pushed, frontiers) = macros.fences(); println!("- pushed tiles (no window): {pushed:?}"); println!("- frontier marks (no window): {frontiers:?}"); + // `FLY_PROBE_SAVE` without `FLY_PROBE_SAVE_RANK` writes the caught frame itself (row 65: the + // Cerulean yard, reached by the survey and by nothing else). The ledgers stay behind, as they + // do in every checkpoint. + if save_rank.is_none() + && let Some(path) = std::env::var_os("FLY_PROBE_SAVE") + { + let bytes = save_state(checkpoint, gb, adapter, frame, &path); + println!("- saved the caught frame to `{}` ({bytes} bytes)", std::path::Path::new(&path).display()); + } let ledger = AdapterLedger(&*adapter); macros.inspect(gb, &ledger, |state: &mut dyn MacroState| { let player = state.player().expect("a loaded map"); diff --git a/services/flysim/crates/flysim/tests/rom_macros_mode.rs b/services/flysim/crates/flysim/tests/rom_macros_mode.rs index b6128f9..7940255 100644 --- a/services/flysim/crates/flysim/tests/rom_macros_mode.rs +++ b/services/flysim/crates/flysim/tests/rom_macros_mode.rs @@ -4452,3 +4452,105 @@ fn the_fly_takes_the_ladder_it_stands_on_and_hops_down_to_cerulean_from_mt_moons assert!(!walled, "a tile was walled on the way down to Cerulean City: {route_4_pushed}"); assert!(cerulean.is_some(), "the fly never reached Cerulean City: {arrivals:?}"); } + +const CERULEAN_CITY: u32 = 0x03; +const CERULEAN_BADGE_HOUSE: u32 = 0xe6; + +/// A checkpoint in the closed yard behind Cerulean's badge house, standing on its back door, or +/// `None` to skip. +/// +/// Row 65's is the route survey's own (`examples/scene_probe.rs`, `FLY_PROBE_CATCH=route +/// FLY_PROBE_RNG=99` from `FLY_ROW64_CHECKPOINT`, written with `FLY_PROBE_CATCH_FRAME=31170 +/// FLY_PROBE_SAVE`): the first free frame after `GO OUT` in the badge house took its back door. +fn row65_yard_checkpoint() -> Option { + std::env::var_os("FLY_ROW65_YARD_CHECKPOINT").map(|path| { + flysim::store::load(std::path::Path::new(&path)) + .expect("the checkpoint should be a FLYSIM01 envelope") + }) +} + +/// Row 65: out of the Cerulean badge house's back yard, whose one way out is the door underfoot. +/// +/// **What the row-64 review found** (its own survey, seed 7, and the same from seed 99 on the +/// release tree): `GO OUT` in the badge house (`$e6`) took the back door at (2, 0), which leaves +/// the fly on Cerulean (9, 9), the door tile of a yard of 33 tiles whose only exit is that door. +/// From then on the pad was empty for as long as the survey ran (about 32,000 frames), with +/// `GO ROUTE` and `GO ITEM` refused `no route` whenever they came back. Three things stacked: +/// +/// - the exit walks set a step-fired door underfoot aside whenever any other exit was listed, +/// reachable or not, so the one door that could be taken never was; +/// - the door is no door tile: it fires on a bump toward the house (a warp carpet in front), and +/// row 64's step off and back on does nothing on it; +/// - Cerulean was one piece on the map graph, so every door and edge of the town was a way out of +/// the yard for the route search to refuse, and the house's two doors were one door to `GO OUT`. +/// +/// The claims, none of them about which button the fly presses, over the stub rotation: the fly +/// **leaves the yard** for the town, and **no run of overworld frames in the yard deals an empty +/// pad** for as long as ten seconds. +/// +/// ```sh +/// FLY_ROM=/path/to/pokemon-red.gb \ +/// FLY_ROW65_YARD_CHECKPOINT=.local/checkpoints/survey-rank15-row65-yard.checkpoint \ +/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture row65 +/// ``` +#[test] +fn row65_the_fly_leaves_the_cerulean_badge_houses_back_yard() { + let rom = skip_without_rom!(); + let Some(checkpoint) = row65_yard_checkpoint() else { + eprintln!("skipped: no FLY_ROW65_YARD_CHECKPOINT"); + return; + }; + let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint); + assert_eq!(run.map(), CERULEAN_CITY, "the checkpoint is in Cerulean City"); + assert_eq!(run.tile(), (9, 9), "on the badge house's back door"); + // The yard, as the cartridge's own ground says: every tile a walk from the door reaches. Read + // here rather than from the map graph, so the base (which has no piece for it) is measured by + // the same ruler. + let grid = flybrain_gb::pokemon_red::state::map_grid(&mut run.gb).expect("Cerulean's grid decodes"); + let yard = grid.reachable(9, 9); + assert!(!yard.contains(9, 12), "the town outside the front door is not the yard's"); + let in_yard = |run: &mut Run| run.map() == CERULEAN_CITY && { + let (x, y) = run.tile(); + yard.contains(x, y) + }; + + let mut left: Option<(u32, u32)> = None; + let mut empty = 0u32; + let mut worst_empty = 0u32; + let mut into_the_house = 0u32; + let mut previous = run.map(); + for frame in 0..24_000u32 { + run.frame(); + let map = run.map(); + if map == CERULEAN_BADGE_HOUSE && previous == CERULEAN_CITY { + into_the_house += 1; + } + previous = map; + let yard_now = in_yard(&mut run); + // On a frame the pad is dealt for: a warp's tear holds the new map with the old tile. + if left.is_none() + && !yard_now + && map != CERULEAN_BADGE_HOUSE + && map != u32::MAX + && run.layer.scene_name() == "overworld" + { + left = Some((frame, map)); + } + if yard_now && run.layer.scene_name() == "overworld" && run.layer.bound_channels().is_empty() { + empty += 1; + worst_empty = worst_empty.max(empty); + } else { + empty = 0; + } + } + eprintln!( + "{:.1} brain minutes: out of the yard at {left:?}, into the badge house {into_the_house} \ + times, longest empty pad in the yard {worst_empty} frames, rank {}, route {:?}, macros {:?}", + run.ms / 60_000.0, + run.adapter.progress().rank, + run.route, + run.started + ); + assert!(worst_empty < 600, "an empty pad in the yard for {worst_empty} frames: {:?}", run.started); + assert!(left.is_some(), "the fly never left the yard: {:?} {:?}", run.route, run.started); +}