diff --git a/docs/design/macros.md b/docs/design/macros.md index 3e5aff6..9760708 100644 --- a/docs/design/macros.md +++ b/docs/design/macros.md @@ -1775,6 +1775,68 @@ Nothing is ranked, weighted or pressed for the fly: a press waits for the cartri and a menu nobody is reading has no pad. The decoder, the reward catalog, the adapter version, the roles and the compatibility string are untouched. +### 12.28 A ladder underfoot is taken by stepping off it, a ledge is a hop one way, and a way out that goes nowhere is not done (2026-09-28, row 64) + +(12.26 and 12.27 are rows 62 and 63, on their own branches.) Live on v0.6.2/v0.6.4 at rank 12 +(MT. MOON), from 2026-09-26 to 09-28: about 750 macros per ten brain minutes, all `done`, no reward +and no new ground. They were `GO OBJECTIVE` (61%) and `GO WARP`, 27 frames each. Forty-eight flysim +restarts did not clear it. A milestone reset bought a few hours before it came back. + +The pulled checkpoint has the fly on **Mt. Moon B2F (5, 7)**, the ladder up to B1F's exit chamber, +which is the one road on. It reproduces the ring with the ledgers empty; nothing needs rebuilding. + +- **A ladder fires at the end of a step onto it, and at no other time.** `CheckWarpsNoCollision` + runs after a step completes. A bump into the wall beside a warp fires only at a map's edge off the + overworld (`ExtraWarpCheck` uses `IsPlayerFacingEdgeOfMap` for every tileset but the overworld's). + The fly had come down the ladder and was standing on it. `GO OBJECTIVE`, whose first hop is B1F's + exit chamber, and `GO WARP`, whose second tier is the same ladder, both aimed at the tile + underfoot. Both settled there for twenty frames, pressed nothing, and reported `done`. That is + 12.2's trap, with no ledger in it. `GO FRONTIER` was refused `no route` once per restore and marked + the map exhausted (12.14). The mark was **correct**: every reachable tile of B2F's main piece had + been stood on, and the 439 unstood tiles are in its two other pieces. The pad never lacked a way + on. Its two ways on did nothing. +- **A walk that starts on its own step-fired warp steps off and back on.** Taking the warp this way + is what the cartridge requires. The step off goes to free ground, never onto another warp. With + nowhere free it ends `blocked`. +- **Route 4 east of the mountain had no road to Cerulean.** The ledge tile is absent from every + passable list, so the route search read a ledge as a wall in both directions. From B1F's exit the + way down is over ledges (the column at x = 62 and the rows at y = 5 and 9). So `GO OBJECTIVE` + refused `no route`, the east edge rested in the blocked ledger, and `GO FRONTIER` or `GO ITEM` + walked the fly back through the cave mouth (24, 5). It arrived on B1F (27, 3) with a pad of + `GO OBJECTIVE` and `GO OUT`, the same trap one floor up (nobs' "GO OUT / GO OBJECTIVE" of 09-26). + A stray walk over B1F (23, 3) put it back on B2F (5, 7). This is why a milestone reset only + bought hours. +- **A ledge is a hop, one way.** The decoded grid now marks `LedgeTiles` + (`data/tilesets/ledge_tiles.asm`). These count on the OVERWORLD tileset only, read from the + lower-left anchor tiles `HandleLedges` reads. The route search takes a hop from above as one press + that lands two tiles on, if the landing is ground. From below a ledge is still a wall. The flood + that 12.24's pieces are measured with is unchanged. + + `HandleLedges` takes the joypad for the jump, and that reads as a scripted push-back. So the walk + holds while the cartridge carries the fly along the hop's own line. It then plans again from the + landing. Nothing is written to the push-back or blocked ledgers. A wild battle on the landing + still ends the walk. +- **The general half: a way out that does not take the fly anywhere is not `done`.** 12.2's rule is + now held by the executor for every way out instead of by each macro. A `Settle` arrival on an exit + key that leaves the fly on the same map ends `blocked`, and the exit rests in the window. If the + fly never left the tile it pressed from, row 57's refused-from-here ledger (12.21) also keeps the + button off that tile for the window. Without that, the last resort, which ignores the blocked + ledger, would re-deal the dead exit once per hold. This guarantees that **no in-place ring + persists**: at most one no-op per button per tile per window. It cannot supply knowledge the + macros lack. With it alone on base, the live ring broke (1,500 `done` in place dropped to 0 in + 72,000 frames), but the fly still did not reach Cerulean. + +What does *not* guarantee the fly is never stuck, and why it was not built: a repetition budget +that withholds a button after N unrewarded starts. Rows 58, 59 and 61 were rings in which every +macro *moved* the fly across a door, so no effect-based rule sees them. A budget keyed on the fly's +own choice history is a rule about the choice, not knowledge inside a macro (section 12's first +line and the ethos check). In every one of those rows it would have turned a ring into a wait or a +wander, without adding the fact that was missing. The guarantee for those rings stays outside the +fly: the watchdog, the recovery ladder, and the ROM road tests from each trap's checkpoint. + +The decoder, the reward catalog, the adapter version, the roles and the compatibility string are +untouched. Nothing presses for the fly. + ## 13. Shops and Pokémon Centers (the operator, 2026-09-17: "refactor the shop macros. make it a ## priority to visit the shop at least once per area; make shop macros item purchases. same ## for the Pokécenter. heal should be a macro.") diff --git a/infra/docs/macros-traps.md b/infra/docs/macros-traps.md index 67dfed8..d2a2ac8 100644 --- a/infra/docs/macros-traps.md +++ b/infra/docs/macros-traps.md @@ -3207,3 +3207,90 @@ pressing `ITEM` whenever dealt, 12,000 frames in the one battle, `ITEM` 119 and party list left waiting 119 times, the Potion never used, and pressing `BACK` then `MOVE 1` whenever dealt, `MOVE 1` 125 and `BACK` 125, the battle never ends: **fails**. Branch: the Potion used (8 to 28 HP) and the battle over in 555 frames; `MOVE 4` and the battle over in 773: passes. + +## 2026-09-28, row 64: Mt. Moon's far side, a ladder underfoot and three ledges down + +### What was live + +v0.6.2/v0.6.4 binary, adapter `pokered-unique8-v7`, macros mode, rank 12 (MT. MOON), objective +Cerulean City, from 2026-09-26 to 09-28. The watchdog flagged it as `unrewarded`: about 750 macro +decisions per ten brain minutes, all `done`, no reward, places delta 0. The 09-28 event log has +`GO OBJECTIVE` 41,990 starts, `GO WARP` 25,554, `GO FRONTIER refused` 27 (about one per restore), +and nothing else: no battle and no step. Forty-eight hourly flysim restarts did not clear it. The +milestone-12 reset of 09-26 bought hours; nobs had recorded a "GO OUT / GO OBJECTIVE" pad just +before that reset. + +### Reproduction (the pulled checkpoint, hot generation 218910) + +The fly is on Mt. Moon B2F (`$3d`) at (5, 7), which is warp 3, the ladder up to B1F's exit chamber +(23, 3). With the ledgers **empty** the pad is `GO OBJECTIVE`, `GO WARP`, `GO FRONTIER`: + +- `objective_goals` is `Exit(Warp(3))` at (5, 7), and `ways(Passage)` is `[Warp(3)]` (tier 2, + toward the objective). +- `GO FRONTIER` is refused `no route` and the map is marked exhausted. Correctly: all 452 reachable + tiles are stood on, and the 439 unstood ones are in B2F's north and south pieces and the border. +- Per-frame trace: `GO OBJECTIVE` runs 27 frames with mask `0x00` on every one (a `Settle` arrival + on the tile underfoot) and ends `done`. The next hold does the same. Route survey on main, + 20,000 frames: `GO OBJECTIVE` 205 and `GO WARP` 211 `done`, all on (5, 7). + +With the ledgers rebuilt (`EXHAUSTED=1`, `STOOD=1`) the pad is `GO OBJECTIVE`, `GO WARP` from frame +0. **The coordinator's lead (`GO WARP` and `GO FRONTIER` exhausted) is refuted.** The frontier mark +is correct, and `GO WARP` is never withheld: it is dealt the whole time, at the ladder underfoot. +No ledger removes the way on. Both ways on execute as no-ops. + +**Why it came back after the reset.** Off the ladder (a raw right/left step, then the drive), the +fly goes B1F exit chamber, then (27, 3), then Route 4 (24, 6). There `GO OBJECTIVE` is refused +`no route`, because every road from there to Cerulean's west edge crosses a ledge: the column at +x = 62 on rows 10-15, and the rows at y = 5 and 9. The route search read a ledge as a wall both +ways. The east edge rests, and `GO ITEM` or `GO FRONTIER` walk back into the cave mouth (24, 5). +The fly lands on B1F (27, 3), where `GO OBJECTIVE` settles in place (618 times in 30,000 frames), +or on B2F (5, 7) after a walk over (23, 3). The geometry re-creates the ring; nothing persisted. + +### Fix (three commits) + +1. `014d869`: a walk that starts on its own step-fired warp steps onto free ground beside it (never + another warp) and back on (`CheckWarpsNoCollision` runs only after a step). +2. `e10f48e`: `LedgeTiles` hops. The grid marks them (OVERWORLD tileset only, lower-left anchor + tiles). The route search takes a hop from above as one press that lands two tiles on. The walk + holds while `HandleLedges` carries the fly, so the hop is not written as a push-back. +3. `83e842a` (general, separable): a `Settle` on an exit key that leaves the fly on its map ends + `blocked`. From the tile it pressed from, row 57's refused-from-here ledger also holds the + button off for the window. + +Ablations from the checkpoint: + +- 1 alone becomes a B1F/Route 4 ring (`GO OBJECTIVE` done on Route 4 151 times, `GO ROUTE` on B1F + 150). +- 3 alone breaks the in-place ring (1,500 done in place drops to 0 in 72,000 frames), but the fly + does not reach Cerulean. +- 1 + 2 reach Cerulean at frame 1,972. + +### Before and after + +Route survey from the live checkpoint, 72,000 frames per arm, `main` `eecd574` vs the branch: + +| driver | base | branch | +| --- | --- | --- | +| prefer GO OBJECTIVE, GO WARP | rank 12, 3,290 tiles, 1,500 of 1,500 done on B2F | rank 13 CERULEAN, 3,434 tiles, Cerulean f1973 | +| uniform, seed 7 | rank 12, 3,290, 1,499/1,500 | rank 15 NUGGET BRIDGE, 3,551, Cerulean f3331 | +| uniform, seed 12345 | rank 12, 3,290, 1,499/1,500 | rank 13, 3,436, Cerulean f3041 | +| uniform, default seed | rank 12, 3,290, 1,499/1,500 | rank 13, 3,447, Cerulean f1973 | + +ROM test `the_fly_takes_the_ladder_it_stands_on_and_hops_down_to_cerulean_from_mt_moons_far_side` +(`FLY_ROW64_CHECKPOINT`): + +- base: 167 done in place, never leaves B2F, **fails**; +- branch: the first `GO OBJECTIVE` goes to B1F, 80 hop frames under a walk on Route 4, Cerulean at + f1972, pushed ledger empty, passes. + +### Why nothing inside the fly broke it, and the general guarantee + +The in-place ring wrote no ledger. `Done` records nothing, and every ledger with a window was +empty after a restore anyway. The per-macro form of 12.2's rule had no case for a warp underfoot. +Commit 3 makes the rule structural for every way out. + +Rows 58, 59 and 61 were rings in which each macro crossed a door, so no effect-based rule sees +them. A repetition budget keyed on the fly's own starts was considered and not built. It is a rule +about the choice, not knowledge in a macro, and it would turn a ring into a wait or a wander +without adding the missing fact. Those rings stay guarded outside the fly: the watchdog, the +recovery ladder, and the ROM road tests. 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 dcc6b4f..26335b9 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 @@ -25,7 +25,7 @@ use crate::adapter::MemoryReader; use crate::emulator::buttons; use super::cartridge::{ - FACINGS, ListKind, MacroState, TalkTarget, TargetKey, Tile, battle_entry, button, item, + ExitId, FACINGS, ListKind, MacroState, TalkTarget, TargetKey, Tile, battle_entry, button, item, opposite, }; use super::geography::Amenity; @@ -449,6 +449,36 @@ struct Walk { /// without this the same tile is aimed at once per hold for ever, which is what a ledge, a /// tile-pair rule or a person on the far side of it looks like. stalled: bool, + /// The ledge hop the held press is making, as the tile it was pressed from and its direction. + /// + /// Row 64. The route search takes a ledge the one way the cartridge does + /// ([`path::route_avoiding`]), and the cartridge's way is to take the joypad: `HandleLedges` + /// sets `wJoyIgnore` and simulates the two tiles of the jump, so the scene reads + /// [`Scene::Unknown`] for the length of it. Without this the walk ended on that scene change + /// like any other, `scripted` and all, and [`MacroMachine::observe_push`] wrote a hop the walk + /// asked for as a push-back: the tile walled for the session and the target rested for the + /// window. Set when the press begins, cleared when the fly has moved. + hop: Option<(Tile, Facing)>, + /// The warp this walk began standing on, while it has not yet stepped off it. + /// + /// Row 64, Mt. Moon, two days. A ladder, a cave mouth, a staircase -- every warp whose exit + /// has no press -- fires at the end of a *step onto it* (`CheckWarpsNoCollision`, run after a + /// step completes), and nothing else fires it: a press into the wall beside it warps only at + /// a map's edge (`ExtraWarpCheck`, `IsPlayerFacingEdgeOfMap` off the overworld). A fly that + /// arrived on B2F's exit ladder by coming down it is standing on the one way on, and + /// `GO OBJECTIVE` and `GO WARP` both aimed at the tile underfoot, settled on it, and reported + /// `done` without a press -- section 12.2's trap, with no ledger in it for a restart to clear. + /// So a walk that starts on its own step-fired warp takes it the way the cartridge does: one + /// step onto free ground beside it, and the step back. + step_off: Option, + /// Whether the walk settled on a way out and the map did not change: the exit did not take it. + /// + /// The general half of row 64 (section 12.2's rule, held by the executor instead of by each + /// macro): a way out's whole promise is a different map, so a `Settle` arrival on one that + /// leaves the fly on this map has not arrived anywhere. It ends `Blocked` -- the exit rests in + /// the window -- and, when the fly never left the tile it pressed from, + /// [`MacroMachine::unfired_here`] keeps the button off this tile for the window too. + unfired: bool, } /// Progress through one cursor navigation. @@ -881,6 +911,13 @@ impl MacroMachine { // ended every walk north this way, `Done` with nothing recorded, once per hold for eight // hours. let now = class(state.scene()); + // A ledge the walk pressed into is the cartridge carrying the fly where the walk asked it + // to go, not the world moving on under it ([`Walk::hop`]): the walk waits it out and + // re-plans from the landing. + if now != started_in && !spans.contains(&now) && self.hopping(state) { + self.active.as_mut()?.frames += 1; + return Some(buttons::NONE); + } if now != started_in && !spans.contains(&now) { let pushed = state.scripted() || self.moved_away(state); let at = pushed.then(|| state.player()).flatten(); @@ -907,6 +944,9 @@ impl MacroMachine { Decided::End(outcome) => { let pushed = state.scripted(); let at = pushed.then(|| state.player()).flatten(); + if outcome == MacroAbort::Blocked { + self.unfired_here(state); + } return self.finish(outcome, true, pushed, at); } Decided::Pop => { @@ -1019,6 +1059,44 @@ impl MacroMachine { self.pending_push_calm = 0; } + /// A way out that did not fire, pressed from the tile the fly is still standing on: the button + /// is not dealt again from here for the window (row 57's ledger, [`Walk::unfired`]). + /// + /// The blocked entry alone rests the exit for every list but a last resort, and a last resort + /// ignores the blocked ledger by design -- so on a map with nothing else on it the same button + /// would be dealt at the same dead exit once per hold, which is the ring this is here to end. + /// A pad with nothing left that can run is empty and the fly waits, section 13.1's answer. + fn unfired_here(&mut self, state: &mut dyn MacroState) { + let Some(active) = self.active.as_ref() else { return }; + let Some(Step::Walk(walk)) = active.plan.front() else { return }; + if !walk.unfired { + return; + } + let Some(player) = state.player() else { return }; + let here = Tile::new(player.x, player.y); + if player.map == walk.map && active.from == Some(here) { + self.refused_at = Some((player.map, active.kind.slot(), here)); + } + } + + /// Whether the running walk is mid-hop: it pressed into a ledge ([`Walk::hop`]), the + /// cartridge has the joypad with no text up, and the fly is on the hop's own line -- the tile + /// it pressed from, the ledge, or the landing -- on the walk's own map. A wild battle on the + /// landing is a battle, and ends the walk as a scene change always has. + fn hopping(&self, state: &mut dyn MacroState) -> bool { + let Some(active) = self.active.as_ref() else { return false }; + let Some(Step::Walk(walk)) = active.plan.front() else { return false }; + let Some((from, facing)) = walk.hop else { return false }; + if state.scene() != Scene::Unknown || !state.scripted() || state.text_open() { + return false; + } + let Some(player) = state.player() else { return false }; + let at = Tile::new(player.x, player.y); + let over = from.step(facing); + let landing = over.and_then(|tile| tile.step(facing)); + player.map == walk.map && (at == from || Some(at) == over || Some(at) == landing) + } + /// Whether the fly is standing somewhere other than where the running macro began. /// /// The other half of "the game moved the fly": a script can finish its push-back inside the @@ -1560,6 +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`]). + walk.unfired = true; + Progress::Blocked } else { arrived(walk.continues) } @@ -1608,10 +1691,12 @@ fn walk_frame(walk: &mut Walk, state: &mut dyn MacroState) -> Progress { if let Some((facing, from)) = walk.holding { if here != from { // Moved: this tile is done and the failure run is broken. The plan's head is spent, - // and the next one steps from where the player now stands. + // and the next one steps from where the player now stands -- two tiles on, after a + // ledge ([`Walk::hop`]). walk.plan.pop_front(); walk.expect = Some(here); walk.holding = None; + walk.hop = None; walk.held = 0; walk.failures = 0; walk.gap = STEP_GAP; @@ -1631,6 +1716,7 @@ fn walk_frame(walk: &mut Walk, state: &mut dyn MacroState) -> Progress { walk.plan.clear(); walk.expect = None; walk.holding = None; + walk.hop = None; walk.held = 0; walk.gap = STEP_GAP; walk.failures += 1; @@ -1641,8 +1727,15 @@ fn walk_frame(walk: &mut Walk, state: &mut dyn MacroState) -> Progress { }; } + // Off the warp it began on: from here the way back onto it is an ordinary step, and the + // step is what fires it ([`Walk::step_off`]). + if walk.step_off.is_some_and(|tile| tile != here) { + walk.step_off = None; + } // Plan, or re-plan. - if let Some(goal) = walk.goals.iter().find(|goal| goal.tile == here) { + if walk.step_off.is_none() + && let Some(goal) = walk.goals.iter().find(|goal| goal.tile == here) + { walk.arrival = Some(goal.arrival); walk.arrived = Some(here); walk.plan.clear(); @@ -1657,7 +1750,11 @@ fn walk_frame(walk: &mut Walk, state: &mut dyn MacroState) -> Progress { // walkable window that has moved with the player, which is the oscillation [`Walk::plan`] // documents; the plan is only remade when the ground has said something new. if walk.plan.is_empty() || walk.expect != Some(here) { - let tiles: Vec = walk.goals.iter().map(|goal| goal.tile).collect(); + let tiles: Vec = if walk.step_off.is_some() { + beside(state, here) + } else { + walk.goals.iter().map(|goal| goal.tile).collect() + }; let Some(Route { steps, .. }) = path::route_avoiding(state, &tiles, &walk.refused) else { return Progress::Blocked; }; @@ -1672,9 +1769,35 @@ fn walk_frame(walk: &mut Walk, state: &mut dyn MacroState) -> Progress { }; walk.holding = Some((first, here)); walk.held = 1; + walk.hop = state + .map_grid() + .is_some_and(|grid| grid.map() == walk.map && grid.hops(here.x, here.y, first)) + .then_some((here, first)); Progress::Hold(button(first)) } +/// Whether the goal the walk is settling on is a way out: an exit key, whose promise is a map +/// change. A tile the objective names is not one -- standing on it is the point. +fn settled_on_a_way_out(walk: &Walk) -> bool { + walk.arrived.is_some_and(|tile| { + walk.goals + .iter() + .any(|goal| goal.tile == tile && matches!(goal.key, Some(TargetKey::Exit(_)))) + }) +} + +/// The tiles one step from `here` that are not themselves warps: where a walk standing on a warp +/// it has to fire steps to first ([`Walk::step_off`]). Stepping onto another warp would fire that +/// one instead. Which of them is ground is the route search's answer, as it is for every goal. +fn beside(state: &mut dyn MacroState, here: Tile) -> Vec { + let warps: Vec = state.warps().iter().map(|warp| Tile::new(warp.x, warp.y)).collect(); + FACINGS + .iter() + .filter_map(|facing| here.step(*facing)) + .filter(|tile| !warps.contains(tile)) + .collect() +} + /// The extra scene classes a macro is allowed to run through ([`Active::spans`]). /// /// One row, and the empty slice everywhere else. `HEAL` walks in the overworld and finishes in a @@ -2207,6 +2330,18 @@ fn walk_then( .or(nearest); let here = Tile::new(player.x, player.y); 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 + .goal + .and_then(|index| goals.get(index)) + .filter(|goal| { + route.steps.is_empty() + && goal.tile == here + && goal.arrival == Arrival::Settle + && matches!(goal.key, Some(TargetKey::Exit(ExitId::Warp(_)))) + }) + .map(|goal| goal.tile); Some(( Walk { goals, @@ -2226,6 +2361,9 @@ fn walk_then( best_distance: distance, continues, stalled: false, + hop: None, + step_off, + unfired: false, }, target, )) 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 274cc2a..dd26c04 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 @@ -143,11 +143,12 @@ pub enum Way { /// A *directed* wall, which is the only shape that fits what the game encodes. Two of its rules /// are invisible to the collision table [`super::state::walkable`] reads: /// -/// - **ledges.** `HandleLedges` (`home/overworld.asm`) matches a triple of facing, the tile the -/// player stands on and the tile in front against `LedgeTiles`, and hops the player *two* tiles -/// that way. The ledge tile itself is absent from every tileset's passable list, so the -/// predicate already calls it [`Walkable::No`] and the search never plans through one in either -/// direction — a hop is a move the walk declines to use rather than one it gets wrong. +/// - **ledges.** `HandleLedges` (`engine/overworld/ledges.asm`) matches a triple of facing, the +/// tile the player stands on and the tile in front against `LedgeTiles`, and hops the player +/// *two* tiles that way. The ledge tile itself is absent from every tileset's passable list, so +/// the predicate calls it [`Walkable::No`] from both sides. With the decoded grid the search +/// takes the hop the one way the cartridge does (row 64, [`route_avoiding`]); without one, or +/// from the side below, it is a wall the walk declines to plan through. /// - **tile-pair collisions.** `TilePairCollisionsLand` and `...Water` /// (`data/tilesets/tile_pair_collisions.asm`) refuse a step *between* two tiles that are each /// passable on their own — the water/land boundary, a forest's tree line, a gym's floor edge. @@ -254,6 +255,36 @@ pub fn route_avoiding( open.push(Reverse((step_cost + heuristic(next), step_cost, next))); } } + // **A ledge is a step the cartridge takes one way** (row 64). The ledge tile reads + // [`Walkable::No`] and the loop above never plans onto it, which is right from below and + // wrong from above: pressed into from its top side the cartridge hops the fly over it and + // lands it two tiles on. Before this, Route 4 east of Mt. Moon had no road to Cerulean at + // all -- the way down is three ledges -- so `GO OBJECTIVE` refused `no route` on the + // mountain's far side and the fly walked back into the cave. One press, one plan entry; + // the executor holds the walk while the cartridge carries the fly over. + if let Some(grid) = grid { + for facing in super::cartridge::FACINGS { + if !grid.hops(tile.x, tile.y, facing) || refused.contains(&(tile, facing)) { + continue; + } + let Some(landing) = tile.step(facing).and_then(|over| over.step(facing)) else { + continue; + }; + if landing.x >= size.width || landing.y >= size.height { + continue; + } + if state.pushed_tile(landing.x, landing.y) + || !grid.walkable(landing.x, landing.y).is_walkable() + { + continue; + } + let step_cost = cost + 2; + if best.get(&landing).is_none_or(|(known, _, _)| step_cost < *known) { + best.insert(landing, (step_cost, tile, facing)); + open.push(Reverse((step_cost + heuristic(landing), step_cost, landing))); + } + } + } } // Nothing reachable is a goal. Walk to whatever gets closest, so the predicate's window has 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 645813b..ae01242 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 @@ -421,7 +421,13 @@ impl Walkable { /// - **directed walls**: one step out of one tile in one direction that the cartridge refuses /// although both tiles are passable. Pokered has two such rules and the tile-pair lists are the /// one that can be read ahead of time; a ledge is already [`Walkable::No`] in the collision -/// list, and a person in the way is the sprite list's answer, not the ground's. +/// list, and a person in the way is the sprite list's answer, not the ground's; +/// - **ledge hops** (row 64): the one step the collision list calls a wall that the cartridge +/// *does* take, one way, two tiles at a time -- `HandleLedges` matching the facing, the tile +/// stood on and the ledge tile in front against `LedgeTiles` +/// ([`crate::pokemon_red::mapgrid::LEDGE_TILES`]). A hop is a fact about the tables, like a +/// wall, and only [`super::path::route_avoiding`] reads it: [`MapGrid::reachable`] keeps the +/// ground as the collision list draws it, which is what a map's pieces are measured on. /// /// Nothing here is a fact about the run: no ledger, no visit, no target. Those stay where they /// are, session state in the executor layer. @@ -437,6 +443,9 @@ pub struct MapGrid { /// Row-major bitmask of the directions a step out of this tile is refused in /// ([`MapGrid::wall`]). walls: Vec, + /// 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, } impl MapGrid { @@ -450,6 +459,7 @@ impl MapGrid { tiles: vec![Walkable::Unknown; cells], ids: vec![None; cells], walls: vec![0; cells], + hops: vec![0; cells], } } @@ -486,6 +496,18 @@ impl MapGrid { } } + /// Record that a press out of `(x, y)` in `facing` hops the ledge in front, two tiles. + pub fn ledge(&mut self, x: u8, y: u8, facing: Facing) { + if let Some(index) = self.index(x, y) { + self.hops[index] |= wall_bit(facing); + } + } + + /// Whether a press out of `(x, y)` in `facing` is a ledge hop ([`MapGrid::ledge`]). + pub fn hops(&self, x: u8, y: u8, facing: Facing) -> bool { + self.index(x, y).is_some_and(|index| self.hops[index] & 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 5336220..df26ef4 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 @@ -204,6 +204,17 @@ struct World { bought: u32, /// Whether the cartridge is driving the player right now ([`MacroState::scripted`]). scripted: bool, + /// Ledges, as the tile a press hops from and its direction (row 64). Empty everywhere but the + /// tests about them, and with it empty the world has no decoded grid, as before. + ledges: Vec<(Tile, Facing)>, + /// A hop the cartridge is carrying the player through: frames left, the ledge tile, the + /// landing. `HandleLedges` takes the joypad for the length of it, so the scene reads + /// `Unknown` and the world is scripted. + hop: Option<(u32, Tile, Tile)>, + /// Warps a step onto does not fire: the "turns out to need some other press" of + /// [`path::exits`]'s `outward`, for the executor's rule about a way out that did not take the + /// fly anywhere. + duds: BTreeSet, /// A frame at which the cartridge takes the joypad, which is what the Viridian gate does. scripted_at: Option, /// Every completed pulse, in order. @@ -287,6 +298,9 @@ impl World { price_at: None, bought: 0, scripted: false, + ledges: Vec::new(), + hop: None, + duds: BTreeSet::new(), scripted_at: None, pulses: Vec::new(), held: 0, @@ -415,6 +429,23 @@ impl World { fn frame(&mut self, mask: u8) { self.frames += 1; + // A ledge hop in flight: the cartridge's own joypad states, whatever is pressed. + if let Some((left, over, landing)) = self.hop { + let left = left.saturating_sub(1); + if left == 8 { + self.player = over; + } + if left == 0 { + self.player = landing; + self.scene = Scene::Overworld; + self.scripted = false; + self.hop = None; + } else { + self.hop = Some((left, over, landing)); + } + self.previous = mask; + return; + } if let Some((at, next)) = self.pending && self.frames >= at { @@ -588,6 +619,15 @@ impl World { return; } let next = Tile::new(x as u8, y as u8); + // `HandleLedges`: the press over a ledge takes the joypad and hops two tiles. + if self.ledges.contains(&(self.player, facing)) + && let Some(landing) = next.step(facing) + { + self.scene = Scene::Unknown; + self.scripted = true; + self.hop = Some((16, next, landing)); + return; + } if self.walkable(next.x, next.y) != Walkable::Yes { return; } @@ -597,6 +637,9 @@ impl World { else { return; }; + if self.duds.contains(&next) { + return; + } // An interior warp fires on the step onto it; a doormat only when the step onto it is the // same direction the step off the map would be. match outward(next, self.size.height) { @@ -809,6 +852,25 @@ impl MacroState for World { fn objective(&mut self) -> Option { self.objective } + + /// 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() { + return None; + } + let mut grid = super::state::MapGrid::new(self.map, self.size.width, self.size.height); + for y in 0..self.size.height { + for x in 0..self.size.width { + let wall = self.walls.contains(&Tile::new(x, y)); + grid.set(x, y, if wall { 0x60 } else { 0x01 }, if wall { Walkable::No } else { Walkable::Yes }); + } + } + for (tile, facing) in &self.ledges { + grid.ledge(tile.x, tile.y, *facing); + } + Some(std::sync::Arc::new(grid)) + } } fn direction_of(mask: u8) -> Option { @@ -907,6 +969,10 @@ fn settle(machine: &mut MacroMachine, world: &mut World) { assert_eq!(map, world.map); world.pushes.insert(tile); } + // `PokemonPalette::record_talk` drains this after every finish, not only after a refusal. + if let Some((map, slot, tile)) = machine.take_refused() { + world.targets.record_refused(map, slot, tile); + } if let Some((map, target)) = machine.take_talked() { assert_eq!(map, world.map); world.talked.insert(target); @@ -5920,4 +5986,119 @@ fn a_service_does_not_walk_the_fly_out_of_the_rungs_room() { assert!(super::palette::objective_targets(&mut world).is_empty()); assert_eq!(amenity_wanted(&mut world, Amenity::Center), Some(maps::PEWTER_POKECENTER)); assert_eq!(amenity_wanted(&mut world, Amenity::Mart), Some(maps::PEWTER_MART)); + +#[test] +fn a_walk_that_starts_on_the_ladder_it_wants_steps_off_and_back_on_to_take_it() { + // Row 64, Mt. Moon B2F (5, 7): the fly came down the ladder and is standing on it, and the + // ladder is the one way on. The cartridge fires a ladder at the end of a step onto it and at + // no other time, so a walk that "arrives" on the tile it is already standing on and settles + // there presses nothing, reports `done` and changes nothing -- `GO OBJECTIVE` and `GO WARP`, + // 27 frames each, for two days. The walk takes it the way the cartridge does: a step onto + // free ground beside it and the step back. + for kind in [MacroKind::GoWarp, MacroKind::GoObjective] { + let mut world = World::room().at(3, 3); + world.warps = vec![Warp { x: 3, y: 3, destination_warp: 0, destination_map: 0x26 }]; + if kind == MacroKind::GoObjective { + world.objective = Some(Objective { map: 0x26, tile: None, warp: None, edge: None, target: None }); + } + assert_eq!(run(&mut world, kind), Ok(MacroAbort::Done), "{}", kind.name()); + assert_eq!(world.map, 0x26, "{} took the ladder it was standing on", kind.name()); + assert!(!world.pulses.is_empty(), "{} pressed something to take it", kind.name()); + } +} + +#[test] +fn a_walk_off_its_ladder_does_not_step_onto_another_warp() { + // Stepping onto a warp is what fires it, so the step off the one underfoot goes to plain + // ground. With the only free side another ladder there is nowhere to step off to, and the + // walk ends `blocked` -- its exit rests in the window -- rather than taking the other ladder. + let mut world = World::room().at(3, 3).wall(&[(3, 2), (2, 3), (3, 4)]); + world.warps = vec![ + Warp { x: 3, y: 3, destination_warp: 0, destination_map: 0x26 }, + Warp { x: 4, y: 3, destination_warp: 0, destination_map: 0x27 }, + ]; + world.seen_maps = BTreeSet::from([0x27]); + // Only one side is free and it is the other ladder: nowhere to step off to without firing it. + assert_eq!(run(&mut world, MacroKind::GoWarp), Ok(MacroAbort::Blocked)); + assert_eq!(world.map, 0x25, "the other ladder was not taken for this one"); +} + +#[test] +fn a_ledge_the_walk_presses_into_is_hopped_and_is_not_a_push_back() { + // Row 64, Route 4 east of Mt. Moon: Cerulean is three ledges down from the cave's exit, and a + // ledge read as a wall both ways, so `GO OBJECTIVE` refused `no route` there. The route search + // takes a hop the one way the cartridge does, and the walk waits while the cartridge carries + // the fly over -- `HandleLedges` takes the joypad for it, which is the same reading as a + // scripted push-back, and a push-back walls the tile for the session. + let mut world = World::room().at(3, 1); + world.map = 0x0f; + for x in 0..8 { + world.walls.insert(Tile::new(x, 3)); + world.ledges.push((Tile::new(x, 2), Facing::Down)); + } + let goal = Tile::new(3, 6); + world.objective = Some(Objective { map: 0x0f, tile: Some(goal), warp: None, edge: None, target: None }); + let mut machine = MacroMachine::new(0x1234_5678); + assert_eq!(run_with(&mut machine, &mut world, MacroKind::GoObjective), Ok(MacroAbort::Done)); + assert_eq!(world.player, goal, "over the ledge and on to the goal in one walk"); + hand_back(&mut machine, &mut world); + assert!(world.pushes.is_empty(), "the hop the walk asked for walled nothing: {:?}", world.pushes); + assert!(!world.targets.blocked(world.map, TargetKey::Tile(goal)), "nor rested the goal"); + + // From below, the ledge is a wall: nothing plans up it. + let mut below = World::room().at(3, 6); + below.map = 0x0f; + for x in 0..8 { + below.walls.insert(Tile::new(x, 3)); + below.ledges.push((Tile::new(x, 2), Facing::Down)); + } + below.objective = + Some(Objective { map: 0x0f, tile: Some(Tile::new(3, 1)), warp: None, edge: None, target: None }); + assert!(run(&mut below, MacroKind::GoObjective).is_err(), "a ledge is not climbed"); + assert_eq!(below.player, Tile::new(3, 6)); +} + +#[test] +fn a_way_out_that_does_not_take_the_fly_anywhere_is_not_done() { + // The general half of row 64 (section 12.2's rule, held by the executor): a way out's promise + // is another map, so settling on one that leaves the fly on this map is not an arrival. Live, + // `GO OBJECTIVE` and `GO WARP` reported that `done` ~750 times per ten brain minutes on one + // tile for two days. Here the warp does not fire at all, whatever the walk does. + let mut world = World::room().at(1, 1); + world.warps = vec![Warp { x: 5, y: 5, destination_warp: 0, destination_map: 0x26 }]; + world.duds = BTreeSet::from([Tile::new(5, 5)]); + let mut machine = MacroMachine::new(0x1234_5678); + assert_eq!(run_with(&mut machine, &mut world, MacroKind::GoWarp), Ok(MacroAbort::Blocked)); + assert_eq!((world.map, world.player), (0x25, Tile::new(5, 5)), "walked to it; it did not fire"); + let exit = TargetKey::Exit(ExitId::Warp(0)); + assert!(world.targets.blocked(world.map, exit), "the dead exit rests in the window"); + // Walked to from elsewhere, so the button is not held against the tile it now stands on: + // a different tile is a different press. + assert!(!world.targets.refused(world.map, MacroKind::GoWarp.slot(), world.player)); +} + +#[test] +fn a_way_out_pressed_from_where_it_does_not_fire_is_not_dealt_again_from_there() { + // Standing on it: step off, step back on, nothing. The blocked entry rests the exit for every + // list but a last resort, and the last resort ignores the blocked ledger by design, so on a + // map with nothing else on it the same button would be dealt at the same dead exit once per + // hold. Row 57's ledger ends that: not from this tile, for the window. + let mut world = World::room().at(3, 3); + world.warps = vec![Warp { x: 3, y: 3, destination_warp: 0, destination_map: 0x26 }]; + world.duds = BTreeSet::from([Tile::new(3, 3)]); + world.seen_maps = BTreeSet::from([0x26]); + world.stood = (0..8).flat_map(|y| (0..8).map(move |x| Tile::new(x, y))).collect(); + let mut machine = MacroMachine::new(0x1234_5678); + // Nothing else on this map: the last resort is what deals `GO WARP` here. + assert!(pick_opt(&mut world, MacroKind::GoWarp), "the last resort deals the only way out"); + assert_eq!(run_with(&mut machine, &mut world, MacroKind::GoWarp), Ok(MacroAbort::Blocked)); + assert_eq!((world.map, world.player), (0x25, Tile::new(3, 3))); + assert!(world.targets.refused(world.map, MacroKind::GoWarp.slot(), world.player)); + assert!(!pick_opt(&mut world, MacroKind::GoWarp), "not dealt again from the tile it failed on"); +} + +/// Whether `kind` is on the pad the world's scene deals now. +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)) } diff --git a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests/map_aware.rs b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests/map_aware.rs index 1257e99..0226bf1 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests/map_aware.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests/map_aware.rs @@ -36,6 +36,8 @@ struct Ground { npcs: Vec, /// Whether the whole map is decoded, or only the window can answer. decoded: bool, + /// Ledges, as the tile a press hops from and its direction, as the grid records them (row 64). + ledges: Vec<(Tile, Facing)>, } impl Ground { @@ -52,6 +54,7 @@ impl Ground { connections: Connections::default(), npcs: Vec::new(), decoded: true, + ledges: Vec::new(), } } @@ -205,6 +208,9 @@ impl MacroState for Ground { for (tile, facing) in &self.pair_walls { grid.wall(tile.x, tile.y, *facing); } + for (tile, facing) in &self.ledges { + grid.ledge(tile.x, tile.y, *facing); + } Some(Arc::new(grid)) } @@ -342,3 +348,32 @@ fn a_connection_on_the_far_edge_is_a_goal_and_the_walls_along_it_are_not() { .count(); assert_eq!(count, 20); } + +#[test] +fn a_ledge_is_one_press_down_and_a_wall_up() { + // Row 64: Route 4 east of Mt. Moon, where every road to Cerulean is a ledge down. A row of + // ledge tiles across the map, which the collision list calls a wall. + let mut ground = Ground::new(12, 10, (5, 1)); + for x in 0..12 { + ground.walls.insert(Tile::new(x, 4)); + ground.ledges.push((Tile::new(x, 3), Facing::Down)); + } + let below = Tile::new(5, 8); + let route = path::route(&mut ground, &[below]).expect("a route down"); + assert_eq!(route.goal, Some(0), "the goal itself, over the ledge"); + // Two steps to the ledge's edge, one press that hops two tiles, three steps on. + assert_eq!(route.steps, vec![Facing::Down; 6]); + + // Up is a wall: the search gets as close as it can and reaches nothing. + ground.player = below; + let route = path::route(&mut ground, &[Tile::new(5, 1)]); + assert!(route.as_ref().is_none_or(|route| route.goal.is_none()), "a ledge is not climbed: {route:?}"); + + // And without the decoded grid there is nothing to read a ledge from: a wall, as before. + let mut blind = Ground::new(12, 10, (5, 1)); + for x in 0..12 { + blind.walls.insert(Tile::new(x, 4)); + } + let route = path::route(&mut blind, &[below]); + assert!(route.as_ref().is_none_or(|route| route.goal.is_none()), "no hop without a ledge: {route:?}"); +} 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 d13e630..0a76ceb 100644 --- a/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid.rs +++ b/services/flysim/crates/flybrain-gb/src/pokemon_red/mapgrid.rs @@ -29,6 +29,8 @@ //! What it does **not** model is what it did not model before: sprites standing on ground (the //! sprite list answers that, and [`super::macros::path::frontier`] reads it), warps that fire on //! the step onto them, and scripts that push the fly off a tile (a session ledger answers that). +//! Ledges it has modelled since row 64 ([`LEDGE_TILES`]): a wall in the collision list, and a hop +//! the route search may take the one way the cartridge takes it. use std::sync::Arc; @@ -76,6 +78,7 @@ const ANCHOR_ROW: usize = 1; /// Tileset ids the tile-pair lists name (`constants/tileset_constants.asm`, counted in the order /// that file declares them: OVERWORLD 0 … FOREST 3 … CAVERN 17). pub mod tileset { + pub const OVERWORLD: u8 = 0; pub const FOREST: u8 = 3; pub const CAVERN: u8 = 17; } @@ -110,6 +113,31 @@ pub const TILE_PAIRS_LAND: [(u8, u8, u8); 11] = [ (tileset::FOREST, 0x5f, 0x2e), ]; +/// `LedgeTiles` at the pinned pokered commit, as `(facing, the tile stood on, the ledge tile)`. +/// +/// `data/tilesets/ledge_tiles.asm`, read by `HandleLedges` (`engine/overworld/ledges.asm`) on the +/// OVERWORLD tileset only (`wCurMapTileset` is 0 or it returns): when the player faces one of +/// these ledge tiles from one of these tiles with that direction held, the cartridge takes the +/// joypad and hops the player **two** tiles that way. Both tiles are the ones +/// `_GetTileAndCoordsInFrontOfPlayer` reads -- screen `(8, 9)` for the player's own and `(8, 11)`, +/// `(8, 7)`, `(6, 9)` or `(10, 9)` for the one in front -- which is the lower-left corner of each +/// map tile's quadrant, the same corner [`ANCHOR_ROW`] decodes. The input column of the table is +/// the facing again, so it is not repeated. +/// +/// The ledge tile is absent from every passable list, which is why a ledge read as a wall in both +/// directions before row 64 and why nothing east of Mt. Moon could be walked to from its exit: +/// Route 4's road down to Cerulean is three ledges, and every one of them faces away from the cave. +pub const LEDGE_TILES: [(Facing, u8, u8); 8] = [ + (Facing::Down, 0x2c, 0x37), + (Facing::Down, 0x39, 0x36), + (Facing::Down, 0x39, 0x37), + (Facing::Left, 0x2c, 0x27), + (Facing::Left, 0x39, 0x27), + (Facing::Right, 0x2c, 0x0d), + (Facing::Right, 0x2c, 0x1d), + (Facing::Right, 0x39, 0x0d), +]; + /// The tileset's two tables, as the decoder needs them. /// /// Gathered by [`super::state::map_grid`] from WRAM and ROM; separate from the decoding so that @@ -178,9 +206,40 @@ 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); grid } +/// 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 +/// landing two tiles away that is still on the map. Whether the landing is ground is the route +/// search's question, as it is for every step. +fn add_ledge_hops(grid: &mut MapGrid, tileset: u8) { + if tileset != tileset::OVERWORLD { + return; + } + for y in 0..grid.height() { + for x in 0..grid.width() { + let Some(here) = grid.tile_id(x, y) else { continue }; + for (facing, stood, ledge) in LEDGE_TILES { + if here != stood { + continue; + } + let (dx, dy) = facing.delta(); + let (Some(nx), Some(ny)) = (checked_step(x, dx), checked_step(y, dy)) else { continue }; + let (Some(lx), Some(ly)) = (checked_step(nx, dx), checked_step(ny, dy)) else { continue }; + if lx >= grid.width() || ly >= grid.height() { + continue; + } + if grid.tile_id(nx, ny) == Some(ledge) { + grid.ledge(x, y, facing); + } + } + } + } +} + /// Turn every tile-pair collision the loaded tileset has into two directed walls. fn add_pair_walls(grid: &mut MapGrid, tileset: u8) { let pairs: Vec<(u8, u8)> = TILE_PAIRS_LAND 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 4ce210a..0b6c3a8 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 @@ -162,3 +162,37 @@ fn the_cache_holds_one_map_and_drops_it_on_arrival_somewhere_else() { assert_eq!(grids.held(), Some(4)); assert!(grids.get(3, 4, 4).is_none()); } + +#[test] +fn a_ledge_is_a_hop_from_above_on_the_overworld_tileset_only() { + // `LedgeTiles`: facing down from `$2C` onto `$37` hops two tiles down. Row 64, Route 4. + let mut grid = MapGrid::new(0x0f, 2, 5); + for y in 0..5 { + grid.set(0, y, 0x2c, Walkable::Yes); + } + grid.set(1, 0, 0x2c, Walkable::Yes); + grid.set(1, 1, 0x37, Walkable::No); + grid.set(1, 2, 0x2c, Walkable::Yes); + grid.set(1, 3, 0x2c, Walkable::Yes); + grid.set(1, 4, 0x2c, Walkable::Yes); + add_ledge_hops(&mut grid, tileset::OVERWORLD); + assert!(grid.hops(1, 0, Facing::Down), "down over the ledge from above"); + assert!(!grid.hops(1, 2, Facing::Up), "never up it from below"); + assert!(!grid.hops(0, 0, Facing::Down), "plain ground is not a ledge"); + assert!(!grid.hops(1, 0, Facing::Right), "only the direction the table names"); + + // `HandleLedges` returns at once on any other tileset. + let mut plain = MapGrid::new(0x3d, 2, 5); + for y in 0..5 { + plain.set(1, y, grid.tile_id(1, y).unwrap_or(0), grid.walkable(1, y)); + } + add_ledge_hops(&mut plain, tileset::CAVERN); + assert!(!plain.hops(1, 0, Facing::Down), "no ledges in a cave"); + + // A ledge whose landing would be off the map is not a hop the table can promise. + let mut edge = MapGrid::new(0x0f, 1, 2); + edge.set(0, 0, 0x2c, Walkable::Yes); + edge.set(0, 1, 0x37, Walkable::No); + add_ledge_hops(&mut edge, tileset::OVERWORLD); + assert!(!edge.hops(0, 0, Facing::Down)); +} diff --git a/services/flysim/crates/flysim/tests/rom_macros_mode.rs b/services/flysim/crates/flysim/tests/rom_macros_mode.rs index a438f19..b6128f9 100644 --- a/services/flysim/crates/flysim/tests/rom_macros_mode.rs +++ b/services/flysim/crates/flysim/tests/rom_macros_mode.rs @@ -4290,3 +4290,165 @@ fn row62_east_of_mt_moon_go_heal_is_not_dealt_back_into_the_mountain() { assert!(east_frames > 0, "the fly was never hurt on the exit chamber: {:?}", run.route); assert_eq!(go_heal_east, 0, "GO HEAL dealt east of the mountain, first at {first:?}"); } + +fn row64_checkpoint() -> Option { + std::env::var_os("FLY_ROW64_CHECKPOINT").map(|path| { + flysim::store::load(std::path::Path::new(&path)) + .expect("the checkpoint should be a FLYSIM01 envelope") + }) +} + +/// Mt. Moon's far side, from the checkpoint pulled during the two-day ring. +/// +/// **What was live** (2026-09-26 to 09-28, v0.6.2/v0.6.4, rank 12 MT. MOON, the objective Cerulean +/// City): about 750 macros per ten brain minutes, every one `done`, no reward, no new ground -- +/// `GO OBJECTIVE` and `GO WARP`, 27 frames each. Forty-eight hourly flysim restarts did not clear +/// it and a milestone reset bought hours (`infra/docs/macros-traps.md` row 64). The fly stands on +/// B2F (5, 7), the ladder up to B1F's exit chamber, which is the one road on. Two things stacked: +/// +/// - a warp whose exit has no press fires at the end of a **step onto it** +/// (`CheckWarpsNoCollision`), and both buttons aimed at the tile underfoot, settled on it and +/// reported `done` without a press -- section 12.2's trap with no ledger in it, so a restore +/// restores it; +/// - off the ladder, the road reaches Route 4's east side, where Cerulean is three **ledges** down. +/// The route search read a ledge as a wall both ways, so `GO OBJECTIVE` refused `no route`, the +/// edge rested in the blocked ledger, and the other walks took the fly back into the cave -- +/// onto B1F's exit (27, 3), the same trap one floor up. +/// +/// The driver is the real palette with the live brain's measured favourites pressed whenever they +/// are dealt (`GO OBJECTIVE`, then `GO WARP`) and one xorshift choice per hold otherwise: a harness +/// choice, not the fly's. On the base it never leaves (5, 7). The claims: +/// +/// - **the first `GO OBJECTIVE`, started on the ladder, takes it**: the map has changed when it ends; +/// - **the fly hops a ledge on Route 4** under a walk (`wMovementFlags` bit 6 with a macro running), +/// and **no tile enters the pushed ledger on the way down**: a hop the walk asked for is not a push-back; +/// - **the fly reaches Cerulean City** inside the budget. +/// +/// ```sh +/// FLY_ROM=/path/to/pokemon-red.gb \ +/// FLY_ROW64_CHECKPOINT= \ +/// cargo test --release -p flysim --test rom_macros_mode -- --nocapture mt_moons_far_side +/// ``` +#[test] +fn the_fly_takes_the_ladder_it_stands_on_and_hops_down_to_cerulean_from_mt_moons_far_side() { + use flybrain_gb::pokemon_red::macros::PokemonPalette; + use flybrain_gb::pokemon_red::state; + use flybrain_gb::{MacroPalette, MemoryReader, Outcome, Started}; + const MT_MOON_B2F: u8 = 0x3d; + const ROUTE_4: u8 = 0x0f; + const CERULEAN: u8 = 0x03; + const LEDGE_OR_FISHING: u8 = 1 << 6; + let rom = skip_without_rom!(); + let Some(checkpoint) = row64_checkpoint() else { + eprintln!("skipped: no FLY_ROW64_CHECKPOINT"); + return; + }; + let mut run = Run::resume(&rom, MacroMode::Macros, &checkpoint); + let start = state::player(&mut run.gb).expect("a loaded map"); + assert_eq!((start.map, start.x, start.y), (MT_MOON_B2F, 5, 7), "the checkpoint is on B2F's exit ladder"); + + let budget = 8_000u32; + let hold_frames = 48u32; + let mut palette = PokemonPalette::new(SEED); + let mut rng = 20_260_928u32 | 1; + let mut running = false; + let mut since_decision = hold_frames; + let mut ms = run.ms; + let mut arrivals: Vec<(u32, u8)> = Vec::new(); + let mut last = None; + let mut first_objective: Option<(u8, u8)> = None; + let mut first_started_on: Option = None; + let mut hop_frames = 0u32; + let mut done_in_place = 0u32; + // The pushed ledger as it stood when the fly first arrived in Cerulean City: the road from the + // ladder over the ledges. + let mut pushed_on_the_way: Option = None; + let mut walled = false; + for frame in 0..budget { + palette.clock(ms); + let observed = { + let ledger = AdapterLedger(&run.adapter); + palette.observe(&mut run.gb, &ledger) + }; + let before = state::player(&mut run.gb).map(|player| (player.map, player.x, player.y)); + let mut mask = 0u8; + { + let ledger = AdapterLedger(&run.adapter); + if running { + match palette.step(&mut run.gb, &ledger) { + Some(held) => mask = held, + None => running = false, + } + } else if since_decision >= hold_frames && !observed.bindings.is_empty() { + since_decision = 0; + rng ^= rng << 13; + rng ^= rng >> 17; + rng ^= rng << 5; + let binding = ["GO OBJECTIVE", "GO WARP"] + .iter() + .find_map(|want| observed.bindings.iter().find(|binding| binding.name == *want)) + .unwrap_or(&observed.bindings[rng as usize % observed.bindings.len()]); + if let Started::Running(_) = palette.start(binding.slot, &mut run.gb, &ledger) { + if first_started_on.is_none() && binding.name == "GO OBJECTIVE" { + first_started_on = before.map(|(map, _, _)| map); + } + running = true; + match palette.step(&mut run.gb, &ledger) { + Some(held) => mask = held, + None => running = false, + } + } + } + } + since_decision += 1; + run.gb.set_buttons(mask); + run.gb.run_frame().expect("a frame should complete"); + ms += MS_PER_FRAME; + run.adapter.sample(&mut run.gb, ms); + if let Some((name, outcome)) = palette.take_finished() { + let after = state::player(&mut run.gb).map(|player| player.map); + if name == "GO OBJECTIVE" && first_objective.is_none() { + first_objective = first_started_on.zip(after); + } + if matches!(outcome, Outcome::Done) + && matches!(name, "GO OBJECTIVE" | "GO WARP") + && after == Some(MT_MOON_B2F) + && state::player(&mut run.gb).is_some_and(|player| (player.x, player.y) == (5, 7)) + { + done_in_place += 1; + } + } + if running + && state::player(&mut run.gb).is_some_and(|player| player.map == ROUTE_4) + && run.gb.read8(flybrain_gb::pokemon_red::symbols::ram::wMovementFlags) & LEDGE_OR_FISHING != 0 + { + hop_frames += 1; + } + if let Some(player) = state::player(&mut run.gb) + && last != Some(player.map) + { + last = Some(player.map); + arrivals.push((frame, player.map)); + if player.map == CERULEAN && pushed_on_the_way.is_none() { + pushed_on_the_way = Some(format!("{:?}", palette.fences().0)); + walled = !palette.fences().0.is_empty(); + } + } + } + let cerulean = arrivals.iter().find(|(_, map)| *map == CERULEAN).map(|(frame, _)| *frame); + let route_4_pushed = pushed_on_the_way.unwrap_or_else(|| format!("{:?}", palette.fences().0)); + eprintln!( + "{:.1} brain minutes: first GO OBJECTIVE {first_objective:?}, done on the ladder in place \ + {done_in_place}, hop frames under a walk on Route 4 {hop_frames}, Cerulean City at \ + {cerulean:?}, pushed on the way {route_4_pushed}, rank {}, arrivals {arrivals:?}", + (ms - run.ms) / 60_000.0, + run.adapter.progress().rank, + ); + assert_eq!(done_in_place, 0, "a walk reported done on the ladder it had not taken"); + let (from, to) = first_objective.expect("GO OBJECTIVE was never started and finished"); + assert_eq!(from, MT_MOON_B2F, "the first GO OBJECTIVE started on B2F's ladder"); + assert_ne!(to, MT_MOON_B2F, "the first GO OBJECTIVE ended where it began: {arrivals:?}"); + assert!(hop_frames > 0, "no ledge was hopped under a walk on Route 4: {arrivals:?}"); + 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:?}"); +}