From 117649846eccd7712a4b7c8760d59561c958d0d5 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 10:56:15 -0800 Subject: [PATCH 01/64] FRLG AutoStory 00.28: sim tests for wild battles every few steps in Rock Tunnel Console B, 2026-11-09: B1F row 37 met a wild battle 10 to 14 tiles into every try and the walker gave up after 9 stops. Red: both fail. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_AutoStoryLavender_Tests.cpp | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp index 65ad046355..4c96611513 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -140,6 +141,67 @@ UnitTestResult test_rock_tunnel_wild_battles(){ return row_on_sim("00.28", script, ROCK_TUNNEL_TRAINERS, MapPosition{StoryTable::ROUTE10, {8, 58}}); } +// Wild battles on the tunnel's floor, `gaps` steps apart in turn, from the +// first step: as many as a row walks. +SimScript battles_every(const std::vector& gaps){ + SimScript script; + int step = 0; + for (size_t c = 0; step < 3000; c++){ + step += gaps[c % gaps.size()]; + script.encounters.push_back(SimEncounter{.grass_step = step}); + } + return script; +} + +// 00.28's step `name`: where it is in the row. +size_t step_index(const StoryCheckpoint& row, std::string_view name){ + for (size_t c = 0; c < row.steps.size(); c++){ + if (row.steps[c].name == name){ + return c; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No step {} in {}.", name, row.id)); +} + +// Console B, 2026-11-09: after Winston, the walk west along B1F row 37 to +// (13, 37) met a wild battle 10 to 14 tiles into every try. Each time the +// walker found the player again at the east wall (45, 37), behind where +// the leg started, and walked the whole 32 tiles again, until it gave up +// ("stopped part-way 9 times"). From Winston's tile, with a battle every +// 10 to 14 steps, the steps from below_martha_line on reach Martha's line. +UnitTestResult test_b1f_row37_battles_every_12(){ + const StoryCheckpoint& row = checkpoint("00.28"); + const size_t first = step_index(row, "below_martha_line"); + StoryPose at{StoryTable::ROCK_TUNNEL_B1F, {29, 37}, Direction::NORTH}; + OverworldSim sim(maps_after_route10(), MapPosition{at.map, at.tile}, *at.facing, battles_every({12, 10, 14, 11, 13})); + const std::string failure = row_step_on_sim(sim, at, row.steps[first], row.id); + if (!failure.empty()){ + return std::format("below_martha_line: ended on {}; {}", to_string(sim.state().position), failure); + } + if (!(sim.state().position == MapPosition{StoryTable::ROCK_TUNNEL_B1F, {17, 34}})){ + return std::format("below_martha_line: ended on {}, not (17, 34).", to_string(sim.state().position)); + } + return true; +} + +// 00.28 whole with a wild battle every 7 to 25 steps on the tunnel's floor, +// the gaps drawn from each of these seeds: the row ends where it should. +UnitTestResult test_rock_tunnel_frequent_battles(){ + for (unsigned seed = 1; seed <= 12; seed++){ + std::mt19937 random(seed); + std::uniform_int_distribution gap(7, 25); + std::vector gaps; + for (int c = 0; c < 400; c++){ + gaps.push_back(gap(random)); + } + const UnitTestResult result = row_on_sim("00.28", battles_every(gaps), ROCK_TUNNEL_TRAINERS, MapPosition{StoryTable::ROUTE10, {8, 58}}); + if (result.result != UnitTestResult::PASSED){ + return std::format("Seed {}: {}", seed, result.message); + } + } + return true; +} + // 00.29 on the sim: no trainer met, the ledge hopped, Lavender's nurse. UnitTestResult test_lavender_row(){ return row_on_sim("00.29", SimScript{}, {}, MapPosition{StoryTable::LAVENDER_CENTER, {7, 4}}); @@ -222,6 +284,8 @@ const AutoStoryLavenderCase AUTO_STORY_LAVENDER_CASES[] = { {.input = {"00.28 the tree, Rock Tunnel's nine trainers, out of its south mouth", test_rock_tunnel_row}, .expectation = {}}, {.input = {"00.28 a wild battle mid-leg in the tunnel", test_rock_tunnel_wild_battles}, .expectation = {}}, {.input = {"00.28 a tile off after each open leg", test_rock_tunnel_tile_off}, .expectation = {}}, + {.input = {"00.28 B1F row 37 with a wild battle every 10 to 14 steps", test_b1f_row37_battles_every_12}, .expectation = {}}, + {.input = {"00.28 a wild battle every 7 to 25 steps, 12 seeds", test_rock_tunnel_frequent_battles}, .expectation = {}}, {.input = {"00.29 Route 10 south, the ledge, Lavender Town's Pokemon Center", test_lavender_row}, .expectation = {}}, {.input = {"00.29 a tile off after each open leg", test_lavender_tile_off}, .expectation = {}}, {.input = {"00.28 and 00.29 save on Route 10 and in Lavender Town", test_save_places}, .expectation = {}}, From 4febace20fc474ae53ec0da33ff95c7474227450 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 11:01:45 -0800 Subject: [PATCH 02/64] FRLG walker: after a stop, find the player the way that walks the fewest tiles Rock Tunnel B1F row 37 (console B, 2026-11-09): a wild battle 10 to 14 tiles into every try of "west 16". The only single hold that found the player went east to the wall (45, 37), behind the leg's start, and the way back walked all 32 tiles again, until the route gave up. The reanchor search now also tries each first hold with the fewest holds after it, and plan_reanchor() takes the way whose holds and way back walk the fewest tiles together: there, south to row 38 and west to the wall (1, 38), then 13 tiles back. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_OverworldReanchor.cpp | 61 ++++++++++++++++--- .../Overworld/PokemonFRLG_OverworldReanchor.h | 9 ++- .../PokemonFRLG_OverworldRecovery.cpp | 14 +---- 3 files changed, 61 insertions(+), 23 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp index 588b63c357..cdacd42e30 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp @@ -236,14 +236,46 @@ bool walks_same_everywhere( return true; } -// The ways to find the player from all of `positions`: fewest holds first, -// then fewest tiles held. None needed if they are all on one tile. +int held_tiles(const std::vector& holds){ + int tiles = 0; + for (const RouteStep& hold : holds){ + tiles += hold.tiles; + } + return tiles; +} + +// The ways to find the player from all of `positions`, fewest holds first, +// then fewest tiles held. None needed if they are all on one tile. Not +// only the fewest holds: for each first hold, the fewest after it, so a +// caller can pick a way that keeps what a stopped leg walked. On Rock +// Tunnel B1F row 37 the one single hold went back east to the wall +// behind the leg's start, while a hold south and one west, ahead, were +// found too (console B, 2026-11-09). std::vector find_player( const std::vector>& worlds, const std::vector& positions, bool surfing ){ - return Pokemon::find_wall_anchors( - positions, ReanchorContext{.worlds = worlds, .surfing = surfing}, {.max_holds = MAX_HOLDS} - ); + const ReanchorContext context{.worlds = worlds, .surfing = surfing}; + std::vector found = Pokemon::find_wall_anchors(positions, context, {.max_holds = 0}); + if (!found.empty()){ + return found; + } + for (Direction direction : Pokemon::ALL_DIRECTIONS){ + const auto first = ReanchorPolicy::hold(context, positions, direction); + if (!first || first->positions == positions || first->hold.tiles == 0){ + continue; + } + for (Found& rest : Pokemon::find_wall_anchors(first->positions, context, {.max_holds = MAX_HOLDS - 1})){ + rest.holds.insert(rest.holds.begin(), first->hold); + found.push_back(std::move(rest)); + } + } + std::stable_sort(found.begin(), found.end(), [](const Found& a, const Found& b){ + if (a.holds.size() != b.holds.size()){ + return a.holds.size() < b.holds.size(); + } + return held_tiles(a.holds) < held_tiles(b.holds); + }); + return found; } } // namespace @@ -326,6 +358,10 @@ std::vector stop_candidates( return candidates; } +int reanchor_tiles(const Reanchor& anchor){ + return held_tiles(anchor.holds) + held_tiles(anchor.back); +} + std::optional plan_reanchor( const std::vector& maps, const std::vector& candidates, @@ -351,7 +387,12 @@ std::optional plan_reanchor( add_unique(positions, Hypothesis{world, candidate.player}); } + // Of the ways found, the one that walks fewest tiles, holds and way back + // together: it keeps the most of what the leg walked. A wild battle + // every 10 to 14 tiles stopped every try of a leg whose way back + // started behind it (console B, 2026-11-09, Rock Tunnel B1F row 37). const std::vector clear_of_trainers = with_trainers(maps, trainers); + std::optional best; for (const Found& at : find_player(worlds, positions, step.surfing)){ const Direction facing = at.holds.empty() ? step.direction : at.holds.back().direction; // The way back keeps clear of every trainer who may stand in it if @@ -360,11 +401,15 @@ std::optional plan_reanchor( if (!back && !trainers.empty()){ back = plan_overworld_route(maps, at.at, RouteGoal{step.end, std::nullopt}, costs, facing); } - if (back && (trainers.empty() || walks_same_everywhere(worlds, positions, at.at, *back))){ - return Reanchor{.holds = at.holds, .found = at.at, .back = std::move(*back)}; + if (!back || (!trainers.empty() && !walks_same_everywhere(worlds, positions, at.at, *back))){ + continue; + } + Reanchor anchor{.holds = at.holds, .found = at.at, .back = std::move(*back)}; + if (!best || reanchor_tiles(anchor) < reanchor_tiles(*best)){ + best = std::move(anchor); } } - return std::nullopt; + return best; } std::optional> holds_to_one_tile( diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h index 157917283e..1d1983c608 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h @@ -106,8 +106,13 @@ struct Reanchor{ std::vector back; }; -// After `step` stopped part-way, from `candidates`. Nothing if no holds -// bring them all to one tile, or no way back walks the same from there. +// How many tiles `anchor`'s holds and way back walk, as far as planned. +int reanchor_tiles(const Reanchor& anchor); + +// After `step` stopped part-way, from `candidates`: of the ways that find +// the player, the one that walks the fewest tiles, holds and way back +// together. Nothing if no holds bring them all to one tile, or no way +// back walks the same from there. std::optional plan_reanchor( const std::vector& maps, const std::vector& candidates, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp index 9053f963ea..b5b2c8d0f1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp @@ -86,18 +86,6 @@ bool hold_finds(const std::vector& maps, const std::vector anchor = plan_reanchor(*maps(), candidates, step, m_planning->costs); - if (!anchor || anchor->holds.empty() || anchor_tiles(*anchor) > 2 * step.tiles){ + if (!anchor || anchor->holds.empty() || reanchor_tiles(*anchor) > 2 * step.tiles){ m_calls.log("Route: no holds to walls within " + std::to_string(2 * step.tiles) + " tiles find the player if " + to_string(step) + " ended short; taken as walked."); return; } From 1484c5e6fa286338c93dfed97a3a49a26f1e8c43 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 11:03:00 -0800 Subject: [PATCH 03/64] FRLG AutoStory: watch a warp's fade from the start of the hold onto it The walk waited for a warp's fade only once the hold onto the warp had ended, so a fade that was over by then went unseen and the walk stopped on "no fade in and out after walking onto the warp" though the player had warped (00.27, console B, 2026-11-09 01:41, the warp to CeruleanCity: the watch started about 1.3 s into the hold). The walk and the recovery walk now show the hold's frames to the same BlackScreenOverWatcher (Pokemon::WatchAlong) and wait on with it only if it has not fired. The watcher and its thresholds are unchanged, so a dim textured floor is still no fade. The overworld sim's walker watches for the fade from where the console does (SimWalkerRules::watch_fade_along_hold), and fails on a warp whose fade it missed, as the console does. OverworldWarpFade walks out of Viridian Mart with a 200 ms fade that is over before the hold ends: seen when watched from the start of the hold, missed from its end. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_OverworldRecoveryWalk.cpp | 7 +- .../Overworld/PokemonFRLG_OverworldSim.cpp | 26 +++- .../Overworld/PokemonFRLG_OverworldSim.h | 12 +- .../PokemonFRLG_OverworldSim_Tests.cpp | 1 + .../Overworld/PokemonFRLG_OverworldWalk.cpp | 54 ++++++-- .../Overworld/PokemonFRLG_OverworldWalk.h | 11 +- .../PokemonFRLG_OverworldWarpFade_Tests.cpp | 129 ++++++++++++++++++ SerialPrograms/cmake/SourceFiles.cmake | 1 + 8 files changed, 222 insertions(+), 19 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWarpFade_Tests.cpp diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp index 8aac65097e..e886503d5f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp @@ -16,6 +16,7 @@ #include "CommonTools/Async/InferenceSession.h" #include "CommonTools/VisualDetectors/BlackScreenDetector.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_DialogDetector.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" #include "PokemonFRLG_OverworldLateBattle.h" #include "PokemonFRLG_OverworldRecoveryWalk.h" @@ -72,16 +73,18 @@ StepWalk walk_step( } context.wait_for_all_requests(); out.hold_start = current_time(); + BlackScreenOverWatcher arrival(COLOR_RED); + Pokemon::WatchAlong fade(arrival); const Pokemon::LegResult result = Pokemon::walk_leg( console, context, leg_mover(step, speed), step.wild ? interrupts.wild : interrupts.other, - leg_spec(step, speed), MAX_INTERRUPTIONS_PER_LEG + leg_spec(step, speed), MAX_INTERRUPTIONS_PER_LEG, warp_hold_watchers(step, fade) ); if (result.stopped){ out.stopped = walked_near(step, result.tiles, tile_time(step, speed)); return out; } if (step.warps){ - wait_out_warp(console, context, step); + wait_out_warp(console, context, step, fade); static_assert(AFTER_WARP_BATTLE_WATCH >= AFTER_WARP); if (run_from_battle_after_warp(console, context)){ console.log("Route: a wild battle, not the warp to " + step.end.map + "; the player is on " + to_string(step) + " before the warp.", COLOR_ORANGE); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index 3395eda537..b904273c14 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -650,17 +650,30 @@ std::optional OverworldSimWalker::hold_watching(const RouteStep& step, return m_sim.hold(step.direction, hold, STEP_RELEASE, hold + STEP_RELEASE + m_rules.watch_past_hold, watchers(interrupts)); } +// Whether a warp's fade showed and was over between `from` and now. +bool OverworldSimWalker::fade_over_since(Milliseconds from) const{ + const SimState& state = m_sim.state(); + if (state.screen == SimScreen::FADE){ + return false; + } + return std::any_of( + state.shown.begin(), state.shown.end(), + [&](const SimShown& shown){ return shown.screen == SimScreen::FADE && shown.at >= from; } + ); +} + // wait_out_warp(), then run_from_battle_after_warp(): false if the fade // was a wild battle's, run from. wait_out_warp()'s watcher takes a wild // battle's wipe for the fade (run 7; console B, 2026-11-03, Mt. Moon 1F): -// the battle screen stands in for the wipe. -bool OverworldSimWalker::after_warp(const RouteStep& step, int warps_before){ +// the battle screen stands in for the wipe. The fade is watched for from +// `watched_from`: a fade over by then is missed. +bool OverworldSimWalker::after_warp(const RouteStep& step, int warps_before, Milliseconds watched_from){ if (m_sim.state().warps == warps_before){ if (!m_sim.watch({SimWatcher::BATTLE_SCREEN}, WARP_TIMEOUT)){ fail("walk_overworld_route(): no fade in and out after walking onto the warp to " + step.end.map + "."); } - }else{ - m_sim.watch({SimWatcher::FADE}, WARP_TIMEOUT); + }else if (!fade_over_since(watched_from) && !m_sim.watch({SimWatcher::FADE}, WARP_TIMEOUT)){ + fail("walk_overworld_route(): no fade in and out after walking onto the warp to " + step.end.map + "."); } m_sim.watch({}, AFTER_WARP); if (!m_sim.watch(watchers({m_wild[1]}), AFTER_WARP_BATTLE_WATCH - AFTER_WARP)){ @@ -712,7 +725,8 @@ std::optional OverworldSimWalker::walk_step(const RouteStep& step, if (result.stopped){ return walked_near(step, result.tiles, TILE_TIME); } - if (step.warps && !after_warp(step, warps_before)){ + const Milliseconds fade_watched_from = m_rules.watch_fade_along_hold ? m_leg_start : m_sim.state().time; + if (step.warps && !after_warp(step, warps_before, fade_watched_from)){ if (!m_rules.find_player_after_warp_battle){ fail_off_route(step); } @@ -795,7 +809,7 @@ void OverworldSimWalker::hold_to_warp(const RouteStep& step){ const Milliseconds hold = TILE_TIME * (step.tiles + 2); const std::optional seen = m_sim.hold(step.direction, hold, STEP_RELEASE, hold + STEP_RELEASE, fade_first); if (seen && seen->watcher == 0){ - if (!after_warp(step, warps_before)){ + if (!after_warp(step, warps_before, m_sim.state().time)){ fail_off_route(step); } return; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index 9483c2e289..32751834dc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -328,6 +328,13 @@ struct SimWalkerRules{ // player may be anywhere on the leg: on Route 10, "east 11" was found // again from all 12 of its tiles (console B, 2026-11-09, 00.27 run 2). bool place_late_battle = true; + // The watch for a warp's fade starts with the hold onto the warp + // (Pokemon::WatchAlong), not when it ends. Without it a fade over + // before the hold ended was missed, and the walk stopped on "no fade in + // and out after walking onto the warp" though it had warped (console B, + // 2026-11-09 01:41, 00.27, the warp to CeruleanCity: the watch started + // about 1.3 s into the hold). + bool watch_fade_along_hold = true; }; // The console side of run_route() on an OverworldSim, as @@ -367,7 +374,8 @@ class OverworldSimWalker{ StepOutcome walk(const RouteStep& step, std::optional facing); std::optional late_stop(const RouteStep& step); std::optional walk_step(const RouteStep& step, std::optional facing); - bool after_warp(const RouteStep& step, int warps_before); + bool after_warp(const RouteStep& step, int warps_before, Milliseconds watched_from); + bool fade_over_since(Milliseconds from) const; [[noreturn]] void fail_off_route(const RouteStep& step); std::optional hold_watching(const RouteStep& step, Milliseconds hold, const std::vector& interrupts); size_t clear_late(const std::vector& interrupts, Milliseconds watch, size_t max); @@ -394,6 +402,8 @@ class OverworldSimWalker{ // Register overworld simulation unit tests. void add_tests_OverworldSim(UnitTestDatabase& database); +// Register the tests of a warp's fade over before the hold onto it ends. +void add_tests_OverworldWarpFade(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp index f8a2c4ca80..3179e1829a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp @@ -983,6 +983,7 @@ void add_tests_OverworldSim(UnitTestDatabase& database){ database.add(item); } add_tests_OverworldLateBattle(database); + add_tests_OverworldWarpFade(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp index 8e57b1cc73..f6332251fb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp @@ -213,12 +213,22 @@ std::string speed_note(const RouteStep& step, MoveSpeed speed){ ); } +std::vector warp_hold_watchers(const RouteStep& step, Pokemon::WatchAlong& fade){ + if (!step.warps){ + return {}; + } + return {&fade}; +} + // One watcher for the whole fade: a ladder's black is short enough to be // over before a second watcher, started once the fade is seen, looks. -void wait_out_warp(ConsoleHandle& console, ProControllerContext& context, const RouteStep& step){ - BlackScreenOverWatcher arrival(COLOR_RED); +void wait_out_warp(ConsoleHandle& console, ProControllerContext& context, const RouteStep& step, Pokemon::WatchAlong& fade){ + if (fade.fired()){ + console.log("Route: the fade to " + step.end.map + " was over before the hold ended."); + return; + } context.wait_for_all_requests(); - if (wait_until(console, context, WARP_TIMEOUT, {arrival}) < 0){ + if (wait_until(console, context, WARP_TIMEOUT, {fade.watcher()}) < 0){ OperationFailedExceptionWithScreenshot::fire( ErrorReportMode::SEND_ERROR_REPORT, "walk_overworld_route(): no fade in and out after walking onto the warp to " + step.end.map + ".", @@ -227,6 +237,12 @@ void wait_out_warp(ConsoleHandle& console, ProControllerContext& context, const } } +void wait_out_warp(ConsoleHandle& console, ProControllerContext& context, const RouteStep& step){ + BlackScreenOverWatcher arrival(COLOR_RED); + Pokemon::WatchAlong fade(arrival); + wait_out_warp(console, context, step, fade); +} + // Fails unless the overworld is up. Under the START menu or a message the // D-pad only moves a cursor, and legs to a wall seem to go fine: three // "walked" that way in Viridian Forest without the player moving (console B, @@ -454,6 +470,31 @@ const OverworldInterruptSet& default_overworld_interrupts(){ } +namespace{ + +// A WALK step's leg, and the fade of the warp it walks onto, watched from +// the start of the hold. +void walk_step_leg( + ConsoleHandle& console, ProControllerContext& context, + const RouteStep& step, const OverworldInterruptSet& interrupts, MoveSpeed speed +){ + BlackScreenOverWatcher arrival(COLOR_RED); + Pokemon::WatchAlong fade(arrival); + Pokemon::walk_leg( + console, context, leg_mover(step, speed), step.wild ? interrupts.wild : interrupts.other, + leg_spec(step, speed), MAX_INTERRUPTIONS_PER_LEG, warp_hold_watchers(step, fade) + ); + if (!step.warps){ + return; + } + wait_out_warp(console, context, step, fade); + static_assert(AFTER_WARP_BATTLE_WATCH >= AFTER_WARP); + check_warp_was_no_battle(console, context, step); +} + +} // namespace + + void walk_overworld_route( ConsoleHandle& console, ProControllerContext& context, const std::vector& route, @@ -479,12 +520,7 @@ void walk_overworld_route( if (const std::string note = speed_note(step, speed); !note.empty()){ console.log(note); } - Pokemon::walk_leg(console, context, leg_mover(step, speed), step.wild ? interrupts.wild : interrupts.other, leg_spec(step, speed), MAX_INTERRUPTIONS_PER_LEG); - if (step.warps){ - wait_out_warp(console, context, step); - static_assert(AFTER_WARP_BATTLE_WATCH >= AFTER_WARP); - check_warp_was_no_battle(console, context, step); - } + walk_step_leg(console, context, step, interrupts, speed); break; case RouteAction::SURF: start_surf(console, context, step.direction, facing == step.direction); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h index e166617c2a..c74361044e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h @@ -176,7 +176,16 @@ Milliseconds leg_hold_time(const RouteStep& step, MoveSpeed speed); // the tiles at the assumed pace and the hold. Empty for other steps. std::string speed_note(const RouteStep& step, MoveSpeed speed); -// After a hold onto `step`'s warp: waits out its fade. +// The hold watchers (Pokemon::walk_leg()) of a leg onto `step`: `fade`, +// which watches for the warp's fade from the start of the hold, if the +// step warps. A fade can be over before the hold ends. +std::vector warp_hold_watchers(const RouteStep& step, Pokemon::WatchAlong& fade); + +// After a hold onto `step`'s warp: waits out its fade, unless `fade`, a +// BlackScreenOverWatcher watched along the hold, saw it over already; +// else waits on with that watcher, which may have seen the black. +void wait_out_warp(ConsoleHandle& console, ProControllerContext& context, const RouteStep& step, Pokemon::WatchAlong& fade); +// The same, watching only from now: for a caller that saw the black itself. void wait_out_warp(ConsoleHandle& console, ProControllerContext& context, const RouteStep& step); // Before `step`: fails unless the overworld is up. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWarpFade_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWarpFade_Tests.cpp new file mode 100644 index 0000000000..de344c2dc1 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWarpFade_Tests.cpp @@ -0,0 +1,129 @@ +/* Overworld Warp Fade Tests + * + * From: https://github.com/PokemonAutomation/ + * + * A warp whose fade is over before the hold onto it ends, on the sim: the + * walker must watch for the fade from the start of the hold. + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_OverworldMaps.h" +#include "PokemonFRLG_OverworldSim.h" +#include "PokemonFRLG_OverworldWalk.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +using namespace std::chrono_literals; + +struct WarpFadeInput{ + std::string name; + // How long the fade shows, from the end of the step onto the warp. + Milliseconds fade{0}; + // SimWalkerRules::watch_fade_along_hold. + bool watch_along_hold = true; +}; + +struct WarpFadeExpectation{ + // The failure the walk stops on; empty: the route is walked. + std::string failure; +}; + +struct WarpFadeCase{ + WarpFadeInput input; + WarpFadeExpectation expectation; +}; + +const std::vector& maps(){ + static const std::vector MAPS = overworld_maps(); + return MAPS; +} + +const MapPosition MART{"ViridianCity_Mart", {4, 3}}; +// Where the Mart's exit mat, (4, 7), puts the player. +const MapPosition OUTSIDE{"ViridianCity", {36, 20}}; + +// 00.27 (console B, 2026-11-09 01:41), the warp to CeruleanCity: "no fade +// in and out after walking onto the warp", the watch for the fade having +// started about 1.3 s into the hold, after the fade was over. Here the +// walk out of Viridian Mart, south 5 onto its mat, is held as to a wall, +// two tiles past the mat; a 200 ms fade is over before the hold ends. +class Test_OverworldWarpFade : public UnitTest{ +public: + explicit Test_OverworldWarpFade(WarpFadeCase test_case) + : UnitTest("PokemonFRLG::OverworldWarpFade - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + RouteStep out; + out.direction = Direction::SOUTH; + out.tiles = 5; + out.warps = true; + out.to_wall = true; + out.facing_after = Direction::SOUTH; + out.end = OUTSIDE; + SimScript script; + script.timing.fade = m_case.input.fade; + SimWalkerRules rules; + rules.watch_fade_along_hold = m_case.input.watch_along_hold; + OverworldSim sim(maps(), MART, Direction::SOUTH, script); + OverworldSimWalker walker(sim, rules); + const RoutePlanning planning{.maps = &maps(), .costs = default_route_costs(), .start = MART, .label = "Sim"}; + const std::string failure = walker.run({out}, planning); + const std::string& expected = m_case.expectation.failure; + const bool as_expected = expected.empty() ? failure.empty() : failure.find(expected) != std::string::npos; + if (as_expected && sim.state().warps == 1){ + return true; + } + std::string log; + for (const std::string& line : walker.log()){ + log += "\n " + line; + } + return std::format( + "Expected failure \"{}\" after 1 warp; got \"{}\" after {}:{}", + expected, failure, sim.state().warps, log + ); + } + +private: + WarpFadeCase m_case; +}; + +} // namespace + + +const WarpFadeCase WARP_FADE_CASES[] = { + { + .input = {.name = "a fade over before the hold ends, watched from its start", .fade = 200ms}, + .expectation = {.failure = ""}, + }, + { + .input = {.name = "a fade over before the hold ends, watched from its end", .fade = 200ms, .watch_along_hold = false}, + .expectation = {.failure = "no fade in and out after walking onto the warp to ViridianCity"}, + }, + { + .input = {.name = "a fade still on when the hold ends, watched from its end", .fade = 1000ms, .watch_along_hold = false}, + .expectation = {.failure = ""}, + }, +}; + +void add_tests_OverworldWarpFade(UnitTestDatabase& database){ + for (const WarpFadeCase& item : WARP_FADE_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index f3d79ac4b8..0b44daf242 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1871,6 +1871,7 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWarpFade_Tests.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_PlayerFacingReader.h Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp From ec9cf9fc6840340c9df71c535fc6877cdaf27af9 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 11:19:42 -0800 Subject: [PATCH 04/64] FRLG walker: walk on after a wild battle when the next holds find the player Rock Tunnel 00.28 with a wild battle every 7 to 25 steps (sim) still lost the open legs' progress after the first fix: - Walk on: after an open leg stops, if the route's next holds bring every tile the player may be on to one tile (and none of those ways crosses a trainer's sight off the planned way), the walker walks on the rest of the leg from the middle candidate instead of finding the player at walls first. The player still faces the leg's way, so no turn tap. A stop on the walked-on leg counts from every tile it may start on. - A leg onto a warp stopped by a wild battle, where no trainer may see the player, holds on to the warp as off the grass: below Rock Tunnel 1F's ladder (20, 13) the holds that found the player went down a column Hiker Lucas looks over. - plan_reanchor() weighs open-leg tiles 4x over held ones, and puts ways whose holds cross a trainer's sight last. - The sim looks for trainers before rolling for a wild battle, as the game does (pokefirered ProcessPlayerFieldInput()). OverworldReanchor rules and two OverworldSim rule tests follow the new choices. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_OverworldReanchor.cpp | 218 ++++++++++++++++-- .../Overworld/PokemonFRLG_OverworldReanchor.h | 32 ++- .../PokemonFRLG_OverworldReanchor_Tests.cpp | 19 +- .../PokemonFRLG_OverworldRecovery.cpp | 72 +++++- .../PokemonFRLG_OverworldRecoveryWalk.cpp | 15 +- .../Overworld/PokemonFRLG_OverworldSim.cpp | 13 +- .../PokemonFRLG_OverworldSim_Tests.cpp | 18 +- .../PokemonFRLG_AutoStoryLavender_Tests.cpp | 30 ++- 8 files changed, 363 insertions(+), 54 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp index cdacd42e30..8917415cfb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp @@ -175,6 +175,11 @@ std::optional, RouteStep>> hold_all( return std::make_pair(std::move(ends), hold); } +// Whether `step` is a hold to a wall. +bool is_hold(const RouteStep& step){ + return step.action == RouteAction::WALK && step.to_wall && !step.warps; +} + using Found = Pokemon::WallAnchor; // Runtime world alternatives and movement mode, separate from the policy type. @@ -362,37 +367,104 @@ int reanchor_tiles(const Reanchor& anchor){ return held_tiles(anchor.holds) + held_tiles(anchor.back); } -std::optional plan_reanchor( - const std::vector& maps, - const std::vector& candidates, - const RouteStep& step, - const RouteCosts& costs +namespace{ + +// How much more a tile of an open leg costs than one held to a wall: a +// wild battle on a hold costs only the battle, as the hold goes on to its +// wall, while one on an open leg stops it and needs finding the player +// again. Not measured: weighted so that on Rock Tunnel B1F row 38 the way +// west to the wall (1, 38) and 13 tiles back beats 10 held east to the +// wall (30, 38) and 17 back. +constexpr int OPEN_TILE_WEIGHT = 4; + +// How costly `anchor` is to walk: its tiles, with open legs' weighted. +int reanchor_cost(const Reanchor& anchor){ + int open = 0; + for (const RouteStep& step : anchor.back){ + if (step.action == RouteAction::WALK && !step.to_wall && !step.warps){ + open += step.tiles; + } + } + return reanchor_tiles(anchor) + (OPEN_TILE_WEIGHT - 1) * open; +} + +// Whether `holds`, from any of `positions`, pass a tile a trainer may see. +// A trainer the route keeps clear of would stop the player and fight +// (the sim, 2026-11-09: Hiker Lucas, on a hold down Rock Tunnel 1F's +// column 16 after a wild battle below the ladder (20, 13)). +bool holds_in_sight( + const std::vector>& worlds, const std::vector& positions, const std::vector& holds ){ - if (candidates.empty() || step.action != RouteAction::WALK){ - return std::nullopt; + for (const Hypothesis& position : positions){ + const std::vector& world = worlds[position.world]; + MapPosition at = position.at; + for (const RouteStep& hold : holds){ + const std::optional wall = hold_to_wall(world, at, hold.surfing, hold.direction); + if (!wall){ + break; + } + RouteStep held = hold; + held.tiles = wall->tiles; + for (const MapPosition& tile : leg_tiles(world, at, held)){ + if (!trainers_seeing(world, tile).empty()){ + return true; + } + } + at = wall->end; + } } + return false; +} - // The maps as they may stand: as they are, and with each trainer who - // may have walked up. - std::vector> worlds{maps}; +// Ways whose holds pass a trainer's sight come after every other way. +constexpr int IN_SIGHT_COST = 1000; + +// The maps as they may stand after a stop on one of `candidates`: as they +// are, and with each trainer who may have walked up; where those trainers +// stand, and where the player may be on which of the maps. +struct StopWorlds{ + std::vector> worlds; std::vector trainers; std::vector positions; +}; +StopWorlds stop_worlds(const std::vector& maps, const std::vector& candidates){ + StopWorlds out{.worlds = {maps}, .trainers = {}, .positions = {}}; for (const StopCandidate& candidate : candidates){ size_t world = 0; if (candidate.trainer){ - worlds.push_back(with_trainers(maps, {candidate.trainer->at})); - world = worlds.size() - 1; - add_unique(trainers, candidate.trainer->at); + out.worlds.push_back(with_trainers(maps, {candidate.trainer->at})); + world = out.worlds.size() - 1; + add_unique(out.trainers, candidate.trainer->at); } - add_unique(positions, Hypothesis{world, candidate.player}); + add_unique(out.positions, Hypothesis{world, candidate.player}); } + return out; +} - // Of the ways found, the one that walks fewest tiles, holds and way back - // together: it keeps the most of what the leg walked. A wild battle - // every 10 to 14 tiles stopped every try of a leg whose way back - // started behind it (console B, 2026-11-09, Rock Tunnel B1F row 37). +} // namespace + +std::optional plan_reanchor( + const std::vector& maps, + const std::vector& candidates, + const RouteStep& step, + const RouteCosts& costs +){ + if (candidates.empty() || step.action != RouteAction::WALK){ + return std::nullopt; + } + + const StopWorlds stop = stop_worlds(maps, candidates); + const std::vector>& worlds = stop.worlds; + const std::vector& trainers = stop.trainers; + const std::vector& positions = stop.positions; + + // Of the ways found, the cheapest (reanchor_cost()): it keeps the most + // of what the leg walked. A wild battle every 10 to 14 tiles stopped + // every try of a leg whose way back started behind it (console B, + // 2026-11-09, Rock Tunnel B1F row 37). const std::vector clear_of_trainers = with_trainers(maps, trainers); std::optional best; + int best_cost = 0; for (const Found& at : find_player(worlds, positions, step.surfing)){ const Direction facing = at.holds.empty() ? step.direction : at.holds.back().direction; // The way back keeps clear of every trainer who may stand in it if @@ -405,13 +477,121 @@ std::optional plan_reanchor( continue; } Reanchor anchor{.holds = at.holds, .found = at.at, .back = std::move(*back)}; - if (!best || reanchor_tiles(anchor) < reanchor_tiles(*best)){ + const int cost = reanchor_cost(anchor) + (holds_in_sight(worlds, positions, anchor.holds) ? IN_SIGHT_COST : 0); + if (!best || cost < best_cost){ best = std::move(anchor); + best_cost = cost; } } return best; } +namespace{ + +// How many tiles `from` is before `to`, walking `direction` on one map; +// nothing if `to` isn't ahead on that line within `max_tiles`. +std::optional tiles_ahead(const MapPosition& from, const MapPosition& to, Direction direction, int max_tiles){ + if (from.map != to.map){ + return std::nullopt; + } + TilePos at = from.point; + for (int c = 0; c <= max_tiles; c++){ + if (at == to.point){ + return c; + } + at = at.next(direction); + } + return std::nullopt; +} + +// One candidate's way on: the tiles it walks, and where it stands. +struct WayOn{ + std::vector tiles; + MapPosition at; +}; + +// `hold` from where each of `ways` stands. False if any isn't stopped by a +// wall, or may be stopped short by a person. +bool hold_ways(const std::vector& maps, const RouteStep& hold, std::vector& ways){ + for (WayOn& way : ways){ + const std::optional wall = hold_to_wall(maps, way.at, hold.surfing, hold.direction); + if (!wall || person_on_the_way(maps, way.at, hold.surfing, hold.direction, *wall)){ + return false; + } + RouteStep held = hold; + held.tiles = wall->tiles; + const std::vector tiles = leg_tiles(maps, way.at, held); + way.tiles.insert(way.tiles.end(), tiles.begin() + 1, tiles.end()); + way.at = wall->end; + } + return true; +} + +// Whether any of `ways` walks onto a tile off `planned` that a trainer may +// see: walking on a few tiles off the planned way may cross a trainer's +// line the route keeps clear of. +bool off_way_in_sight(const std::vector& maps, const std::vector& ways, const std::vector& planned){ + for (const WayOn& way : ways){ + for (const MapPosition& tile : way.tiles){ + const bool off_way = std::find(planned.begin(), planned.end(), tile) == planned.end(); + if (off_way && !trainers_seeing(maps, tile).empty()){ + return true; + } + } + } + return false; +} + +// Each of `candidates` walking `rest`; nothing if any is stopped short. +std::optional> walk_rest( + const std::vector& maps, const std::vector& candidates, const RouteStep& rest +){ + std::vector ways; + for (const StopCandidate& candidate : candidates){ + std::vector tiles = leg_tiles(maps, candidate.player, rest); + if (tiles.size() != (size_t)rest.tiles + 1){ + return std::nullopt; + } + const MapPosition at = tiles.back(); + ways.push_back(WayOn{std::move(tiles), at}); + } + return ways; +} + +} // namespace + +std::optional plan_resume( + const std::vector& maps, + const std::vector& candidates, + const RouteStep& step, + const std::vector& after +){ + const bool open_leg = step.action == RouteAction::WALK && !step.to_wall && !step.warps && step.connection_steps.empty(); + const bool by_trainer = std::any_of(candidates.begin(), candidates.end(), [](const StopCandidate& c){ return c.trainer.has_value(); }); + if (candidates.size() < 2 || !open_leg || by_trainer){ + return std::nullopt; + } + const std::optional remaining = tiles_ahead(candidates[candidates.size() / 2].player, step.end, step.direction, step.tiles); + if (!remaining){ + return std::nullopt; + } + RouteStep rest = step; + rest.tiles = *remaining; + std::optional> ways = walk_rest(maps, candidates, rest); + // The way as planned, from the leg's end. + std::vector planned{WayOn{{step.end}, step.end}}; + for (size_t c = 0; ways && c < after.size() && c < MAX_HOLDS; c++){ + if (!is_hold(after[c]) || !hold_ways(maps, after[c], *ways) || !hold_ways(maps, after[c], planned)){ + return std::nullopt; + } + const bool found = std::all_of(ways->begin(), ways->end(), [&](const WayOn& way){ return way.at == after[c].end; }); + if (found){ + return off_way_in_sight(maps, *ways, planned[0].tiles) ? std::nullopt : std::optional(Resume{rest, c + 1}); + } + } + return std::nullopt; +} + std::optional> holds_to_one_tile( const std::vector& maps, const std::vector& tiles ){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h index 1d1983c608..7d0c2e2e69 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h @@ -111,8 +111,9 @@ int reanchor_tiles(const Reanchor& anchor); // After `step` stopped part-way, from `candidates`: of the ways that find // the player, the one that walks the fewest tiles, holds and way back -// together. Nothing if no holds bring them all to one tile, or no way -// back walks the same from there. +// together, with tiles of open legs weighted over held ones. Nothing if +// no holds bring them all to one tile, or no way back walks the same from +// there. std::optional plan_reanchor( const std::vector& maps, const std::vector& candidates, @@ -120,6 +121,33 @@ std::optional plan_reanchor( const RouteCosts& costs = default_route_costs() ); +// Walking on along a stopped open leg instead of finding the player at +// walls first: the rest of the leg from the middle of the tiles they may +// be on, after which the route's next holds, as planned, bring them to +// one tile from every one of them. Walking on from how far a leg got, +// trusting the timing, went wrong on the console; here the holds find the +// player whichever tile they were on. +struct Resume{ + // From the middle candidate to the stopped leg's end; no tiles if the + // middle candidate is its end. + RouteStep rest; + // How many of the steps after the stopped leg, all holds to walls, + // bring every candidate to one tile. + size_t holds = 0; +}; + +// After `step`, an open leg, stopped part-way on one of `candidates` +// (none stopped by a trainer), with `after` the route's steps after it: +// the way to walk on. Nothing if the holds that start `after` don't bring +// every candidate to one tile, or if any would walk onto a tile off the +// planned way that a trainer may see. +std::optional plan_resume( + const std::vector& maps, + const std::vector& candidates, + const RouteStep& step, + const std::vector& after +); + // Holds to walls that bring the player to one tile from every one of // `tiles`, found as plan_reanchor() finds them, with no trainer about: for // a player known to be on one of a few tiles without a stop (a wild diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor_Tests.cpp index 8e91a54445..650317683e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor_Tests.cpp @@ -152,20 +152,29 @@ const char* const TEST_FIELD_JSON = R"({ })"; // Stopped part-way east, the player holds back west to the wall, the -// shorter way, and walks back. Stopped part-way south above the ledges, -// which would be hopped, they hold back north. +// shorter way, and walks back. Stopped a tile further from that wall, they +// hold on east to the far wall: two more tiles held, one fewer to walk +// back on an open leg, which a wild battle would stop again. Stopped +// part-way south above the ledges, which would be hopped, they hold back +// north. UnitTestResult test_rules(){ const std::vector maps{parse_map(TEST_FIELD_JSON, "Field")}; RouteStep east; east.direction = Direction::EAST; - east.tiles = 3; - east.end = {"Field", {4, 1}}; + east.tiles = 2; + east.end = {"Field", {3, 1}}; std::optional anchor = plan_reanchor(maps, stop_candidates(maps, MapPosition{"Field", {1, 1}}, east, whole_leg(east)), east); if (!anchor || anchor->holds.size() != 1 || anchor->holds[0].direction != Direction::WEST || !(anchor->found.point == TilePos{1, 1})){ return "Expected a hold west to (1, 1), got " + describe(anchor); } if (anchor->back.size() != 1 || !(anchor->back[0].end == east.end)){ - return "Expected one leg back east to (4, 1), got " + describe(anchor); + return "Expected one leg back east to (3, 1), got " + describe(anchor); + } + east.tiles = 3; + east.end = {"Field", {4, 1}}; + anchor = plan_reanchor(maps, stop_candidates(maps, MapPosition{"Field", {1, 1}}, east, whole_leg(east)), east); + if (!anchor || anchor->holds.size() != 1 || anchor->holds[0].direction != Direction::EAST || !(anchor->found.point == TilePos{6, 1})){ + return "Expected a hold east to (6, 1), got " + describe(anchor); } RouteStep south; south.direction = Direction::SOUTH; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp index b5b2c8d0f1..ca9e278392 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp @@ -299,7 +299,7 @@ class RouteRun{ if (step.to_wall){ return after_wall_stop(step, outcome, start, crossing); } - if (outcome.end == StepEnd::STOPPED && step.warps && !step.wild){ + if (outcome.end == StepEnd::STOPPED && step.warps && (!step.wild || by_wild_battle(step, start, outcome))){ m_calls.hold_to_warp(step); m_at = step.end; m_facing = step.facing_after; @@ -313,7 +313,40 @@ class RouteRun{ return false; } const WalkedTiles walked = outcome.walked.value_or(whole_leg(step)); - return rejoin(step, stop_candidates(*maps(), start, step, walked), walked); + return rejoin(step, candidates_on(step, start, walked), walked); + } + + // Whether `step`, a leg with wild battles stopped part-way, was stopped + // by one: no trainer may see the player on it. A wild battle leaves the + // player on the leg's line, so holding on reaches its warp; found again + // at walls instead, below Rock Tunnel 1F's ladder (20, 13), the holds + // went down a column Hiker Lucas looks over (the sim, 2026-11-09). + bool by_wild_battle(const RouteStep& step, const std::optional& start, const StepOutcome& outcome) const{ + if (maps() == nullptr){ + return false; + } + const std::vector candidates = candidates_on(step, start, outcome.walked.value_or(whole_leg(step))); + return !candidates.empty() && std::none_of(candidates.begin(), candidates.end(), [](const StopCandidate& candidate){ + return candidate.trainer.has_value(); + }); + } + + // Where `step`, m_plan[m_next] from `start`, may have stopped. The rest + // of a leg walked on after a stop (walk_on()) starts on any of the + // tiles that stop left the player on. + std::vector candidates_on(const RouteStep& step, const std::optional& start, WalkedTiles walked) const{ + if (m_next != 0 || m_walk_on_starts.empty()){ + return stop_candidates(*maps(), start, step, walked); + } + std::vector candidates; + for (const MapPosition& from : m_walk_on_starts){ + for (const StopCandidate& candidate : stop_candidates(*maps(), from, step, walked)){ + if (std::find(candidates.begin(), candidates.end(), candidate) == candidates.end()){ + candidates.push_back(candidate); + } + } + } + return candidates; } // A leg to a wall seen interrupted after its hold is walked again: the @@ -386,11 +419,36 @@ class RouteRun{ plan.insert(plan.end(), m_plan.begin() + rest, m_plan.end()); m_plan = std::move(plan); m_walked.reset(); + m_walk_on_starts.clear(); m_holds = anchor.holds.size(); m_unchecked = m_holds + anchor.back.size(); m_next = 0; } + // The plan from here: the rest of `step`, the stopped leg m_plan[m_next], + // from the middle of `candidates`, then the old plan after it, whose + // first `resume.holds` steps find the player. The player still faces + // the leg's way: a turn tap first would step a tile. + void walk_on(const RouteStep& step, const Resume& resume, const std::vector& candidates){ + std::vector plan; + m_walk_on_starts.clear(); + if (resume.rest.tiles > 0){ + plan.push_back(resume.rest); + for (const StopCandidate& candidate : candidates){ + m_walk_on_starts.push_back(candidate.player); + } + } + plan.insert(plan.end(), m_plan.begin() + m_next + 1, m_plan.end()); + m_plan = std::move(plan); + m_walked.reset(); + m_holds = (resume.rest.tiles > 0 ? 1 : 0) + resume.holds; + m_unchecked = m_holds; + m_next = 0; + m_at = std::nullopt; + m_facing = step.direction; + m_lines.plan(std::nullopt, m_plan); + } + // Finds the player on one of `candidates`, plans the way back to the // end of `step` (m_plan[m_next]), and the rest of the route after it. bool rejoin(const RouteStep& step, const std::vector& candidates, WalkedTiles walked){ @@ -402,6 +460,15 @@ class RouteRun{ "Route: {} stopped {} to {} tiles in; the player is on one of: {}.", to_string(step), walked.min, walked.max, where.empty() ? "nothing (no start to work from)" : where )); + const std::vector after(m_plan.begin() + m_next + 1, m_plan.end()); + if (const std::optional resume = plan_resume(*maps(), candidates, step, after)){ + m_calls.log(std::format( + "Route: walking on {} tiles along {}; the next {} hold(s) find the player from every one of those tiles.", + resume->rest.tiles, to_string(step), resume->holds + )); + walk_on(step, *resume, candidates); + return true; + } const std::optional anchor = candidates.empty() ? std::nullopt : plan_reanchor(*maps(), candidates, step, m_planning->costs); @@ -444,6 +511,7 @@ class RouteRun{ size_t m_holds = 0; // of the plan, holds to walls that find the player size_t m_unchecked = 0; // of the plan, the holds and the way back after them std::optional m_walked; // the step walked last, if it may have stopped part-way + std::vector m_walk_on_starts; // where the plan's first step, a leg walked on, may start }; } // namespace diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp index 8aac65097e..a5dced5853 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp @@ -186,12 +186,13 @@ StepOutcome walk_and_watch( return StepOutcome{.end = StepEnd::LATE, .walked = recorder.place(console, step, tile_time(step, speed), walked.hold_start)}; } -// Holds on along `step`, stopped part-way off the grass, until its warp's -// fade. Off the grass only a message stops a leg (a trainer who saw the -// player, a Repel wearing off), and the player then stands on the leg's -// line, so holding on reaches the warp however far they got (console B, -// 2026-11-01: Camper Liam stopped "south 9 (warp)" out of Pewter Gym). -// After a trainer the player faces them, so this turns first. +// Holds on along `step`, stopped part-way off the grass or by a wild +// battle where no trainer may see the player, until its warp's fade. Off +// the grass only a message stops a leg (a trainer who saw the player, a +// Repel wearing off), and the player then stands on the leg's line, as +// after a wild battle, so holding on reaches the warp however far they +// got (console B, 2026-11-01: Camper Liam stopped "south 9 (warp)" out of +// Pewter Gym). After a trainer the player faces them, so this turns first. void hold_to_warp( ConsoleHandle& console, ProControllerContext& context, const RouteStep& step, const OverworldInterrupts& interrupts, MoveSpeed speed @@ -303,7 +304,7 @@ void walk_overworld_route_with_recovery( return walk_and_watch(console, context, step, from_facing, interrupts, speed); }; calls.hold_to_warp = [&](const RouteStep& step){ - hold_to_warp(console, context, step, interrupts.other, speed); + hold_to_warp(console, context, step, step.wild ? interrupts.wild : interrupts.other, speed); }; calls.log = [&](const std::string& message){ console.log(message, COLOR_ORANGE); }; calls.fail = [&](const std::string& message){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index 3395eda537..f39bf0f5ed 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -345,7 +345,7 @@ bool OverworldSim::trainer_sees(Milliseconds pressed){ } // The player has taken `step`, pressed at `pressed`. Returns whether the -// game stopped them there: a warp, a wild battle, a trainer. +// game stopped them there: a warp, a trainer, a wild battle. bool OverworldSim::after_step(const Step& step, Milliseconds pressed){ const SimTiming& timing = m_script.timing; m_map = step.map; @@ -364,7 +364,11 @@ bool OverworldSim::after_step(const Step& step, Milliseconds pressed){ note("warped to " + to_string(m_state.position) + "."); return true; } - return wild_battle(pressed) || trainer_sees(pressed); + // The game looks for trainers who see the player before it rolls for a + // wild battle, and doesn't roll once one does (pokefirered + // ProcessPlayerFieldInput(): CheckForTrainersWantingBattle() first, + // CheckStandardWildEncounter() last). + return trainer_sees(pressed) || wild_battle(pressed); } // A wild battle the script starts on this step onto tall grass, or onto a @@ -785,8 +789,9 @@ size_t OverworldSimWalker::clear_unseen_battle(const RouteStep& step){ } void OverworldSimWalker::hold_to_warp(const RouteStep& step){ + const std::vector& ints = interrupts(step); std::vector fade_first{SimWatcher::FADE}; - for (const SimWatcher watcher : watchers(m_other)){ + for (const SimWatcher watcher : watchers(ints)){ fade_first.push_back(watcher); } const int warps_before = m_sim.state().warps; @@ -803,7 +808,7 @@ void OverworldSimWalker::hold_to_warp(const RouteStep& step){ if (!seen){ break; } - clear(m_other[seen->watcher - 1]); + clear(ints[seen->watcher - 1]); } fail("walk_overworld_route(): no fade holding on toward the warp to " + step.end.map + "."); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp index f8a2c4ca80..d289fb2b1d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp @@ -296,10 +296,10 @@ UnitTestResult test_forest_north_gate(){ // on the leg a tile short of the ladder. Here on the leg through the // forest's grass onto its north gate: a battle on the leg's first or // second step is run from, the player found again on the leg, and the -// gate reached through its warp. If the walk back onto the warp then -// ends short of it (hold 4: the leg, the hold that finds the player and -// its re-hold after the Bug Catcher), the route still stops on no fade. -// Without the rule it stops as off the route, as on the console. +// gate reached through its warp: the player is on the leg's line, and +// holds on to it. If that hold then ends well short of the warp (hold 2: +// the leg, then the hold on), the route still stops on no fade. Without the +// rule it stops as off the route, as on the console. UnitTestResult test_battle_on_warp_leg(){ const SimCase c{.start = at("ViridianForest", 5, 20), .facing = Direction::NORTH, .goal = at("Route2_ViridianForest_NorthEntrance", 7, 9)}; for (size_t tile : {1, 2}){ @@ -312,9 +312,9 @@ UnitTestResult test_battle_on_warp_leg(){ } } SimCase no_warp = c; - no_warp.script.short_holds[4] = 2; + no_warp.script.short_holds[2] = 6; const std::optional short_back = run_with_battle_on_warp_leg(no_warp, 1); - if (!short_back || !stopped_with(*short_back, "no fade in and out") || short_back->state.warps != 0){ + if (!short_back || !stopped_with(*short_back, "no fade holding on toward the warp") || short_back->state.warps != 0){ return "Expected a stop on no fade when the walk back ends short of the warp:" + (short_back ? describe(*short_back) : ""); } SimCase off = c; @@ -658,7 +658,9 @@ UnitTestResult test_mt_moon_battle_on_ladder_leg(){ // timing. The text box after the watch is now watched on for, the leg // walked again to its wall, and the route reaches B2F's ladder. Without // the rule the leg is taken as walked, and the run stops on no fade onto -// the ladder down to B2F, as it did. +// the ladder down to B2F, as it did (the console's walker stopped on the +// leg; this one, which holds on toward a warp after a wild battle, stops +// holding on). UnitTestResult test_mt_moon_battle_seen_after_wall_leg(){ SimCase c{.start = at("MtMoon_B1F", 3, 3), .facing = Direction::SOUTH, .goal = at("MtMoon_B2F", 26, 21)}; c.script.encounters = {{.grass_step = 13, .seen_late = true}}; @@ -679,7 +681,7 @@ UnitTestResult test_mt_moon_battle_seen_after_wall_leg(){ const bool taken_as_walked = std::any_of(old.log.begin(), old.log.end(), [](const std::string& line){ return line.find("south 15 (to wall): ended at MtMoon_B1F (3, 18) (walked)") != std::string::npos; }); - if (!taken_as_walked || !stopped_with(old, "no fade in and out after walking onto the warp to MtMoon_B2F.")){ + if (!taken_as_walked || !stopped_with(old, "no fade holding on toward the warp to MtMoon_B2F.")){ return "Expected the leg taken as walked and the run stopped on no fade, as on the console, without the rule:" + describe(old); } return true; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp index 4c96611513..faff538e47 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp @@ -98,14 +98,18 @@ std::string row_rest(OverworldSim& sim, StoryPose at, const StoryCheckpoint& row return ""; } -UnitTestResult row_on_sim(std::string_view id, const SimScript& script, const std::vector& trainers, const MapPosition& end){ +// Row `id` on the sim with `script`: it ends on `end`, with no violation +// on the way, having fought the trainers of one of `fought`, in order. +UnitTestResult row_on_sim( + std::string_view id, const SimScript& script, const std::vector>& fought, const MapPosition& end +){ const StoryCheckpoint& row = checkpoint(id); const StoryPose at = *story_pose(*row.start); OverworldSim sim(maps_after_route10(), MapPosition{at.map, at.tile}, *at.facing, script); if (const std::string failure = row_rest(sim, at, row, 0); !failure.empty()){ return std::string(id) + ": " + failure; } - if (sim.state().trainers_beaten != trainers){ + if (std::find(fought.begin(), fought.end(), sim.state().trainers_beaten) == fought.end()){ std::string fought; for (const std::string& name : sim.state().trainers_beaten){ fought += " " + name; @@ -124,12 +128,18 @@ UnitTestResult row_on_sim(std::string_view id, const SimScript& script, const st const std::vector ROCK_TUNNEL_TRAINERS{ "poke_maniac", "poke_maniac", "picnicker", "hiker", "hiker", "picnicker", "hiker", "poke_maniac", "picnicker", }; +// Cooper unfought: a wild battle on the step into his sight, on the leg +// past him, starts first, and the sim's trainers look only after a step. +// The leg goes on past him to its wall either way. +const std::vector ROCK_TUNNEL_TRAINERS_BUT_COOPER{ + "poke_maniac", "poke_maniac", "picnicker", "hiker", "hiker", "picnicker", "hiker", "picnicker", +}; // 00.28 on the sim: the tree cut, the nine trainers fought where the // table steps into their lines (Cooper by the walker, on the leg past // him), no one else met, and the walk out of the south mouth. UnitTestResult test_rock_tunnel_row(){ - return row_on_sim("00.28", SimScript{}, ROCK_TUNNEL_TRAINERS, MapPosition{StoryTable::ROUTE10, {8, 58}}); + return row_on_sim("00.28", SimScript{}, {ROCK_TUNNEL_TRAINERS}, MapPosition{StoryTable::ROUTE10, {8, 58}}); } // 00.28 with a wild battle on the 3rd step on the tunnel's floor, mid-way @@ -138,7 +148,7 @@ UnitTestResult test_rock_tunnel_row(){ UnitTestResult test_rock_tunnel_wild_battles(){ SimScript script; script.encounters.push_back(SimEncounter{.grass_step = 3}); - return row_on_sim("00.28", script, ROCK_TUNNEL_TRAINERS, MapPosition{StoryTable::ROUTE10, {8, 58}}); + return row_on_sim("00.28", script, {ROCK_TUNNEL_TRAINERS}, MapPosition{StoryTable::ROUTE10, {8, 58}}); } // Wild battles on the tunnel's floor, `gaps` steps apart in turn, from the @@ -187,6 +197,7 @@ UnitTestResult test_b1f_row37_battles_every_12(){ // 00.28 whole with a wild battle every 7 to 25 steps on the tunnel's floor, // the gaps drawn from each of these seeds: the row ends where it should. UnitTestResult test_rock_tunnel_frequent_battles(){ + std::string failures; for (unsigned seed = 1; seed <= 12; seed++){ std::mt19937 random(seed); std::uniform_int_distribution gap(7, 25); @@ -194,17 +205,22 @@ UnitTestResult test_rock_tunnel_frequent_battles(){ for (int c = 0; c < 400; c++){ gaps.push_back(gap(random)); } - const UnitTestResult result = row_on_sim("00.28", battles_every(gaps), ROCK_TUNNEL_TRAINERS, MapPosition{StoryTable::ROUTE10, {8, 58}}); + const UnitTestResult result = row_on_sim( + "00.28", battles_every(gaps), {ROCK_TUNNEL_TRAINERS, ROCK_TUNNEL_TRAINERS_BUT_COOPER}, MapPosition{StoryTable::ROUTE10, {8, 58}} + ); if (result.result != UnitTestResult::PASSED){ - return std::format("Seed {}: {}", seed, result.message); + failures += std::format("{}Seed {}: {}", failures.empty() ? "" : " | ", seed, result.message); } } + if (!failures.empty()){ + return failures; + } return true; } // 00.29 on the sim: no trainer met, the ledge hopped, Lavender's nurse. UnitTestResult test_lavender_row(){ - return row_on_sim("00.29", SimScript{}, {}, MapPosition{StoryTable::LAVENDER_CENTER, {7, 4}}); + return row_on_sim("00.29", SimScript{}, {{}}, MapPosition{StoryTable::LAVENDER_CENTER, {7, 4}}); } // Where an open leg of two tiles or more ends a tile short or long, the From 291f72d5c9a4c2bff7b6b04fd3c2db9cfc40b8cf Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 11:26:58 -0800 Subject: [PATCH 05/64] FRLG AutoStory: run from wild battles on steps into a trainer's line; walk on through open legs The 00.28 sim with a wild battle every 7 to 25 steps now passes at all 12 seeds (before these changes: 0 of 12). - A step into a trainer's line that sets off a wild battle took its battle screen for the trainer's, and the battle step after it found no message. The step now watches 5 s for a wild battle, runs from one seen with no message before it, and steps on (program and sim). The game looks for trainers before it rolls for a wild battle, so the trainer didn't see the player on that step. - Walking on after a stop may go through open legs of the plan before the hold that finds the player (Rock Tunnel 1F row 31: west, then south 1, then the hold west to (12, 32)); a stop on any of them counts from every tile it may start on. - A hold to a wall where wild battles start, stopped right away after another interrupt (Cooper, then a wild battle), is walked again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_OverworldReanchor.cpp | 55 ++++++++++++------- .../Overworld/PokemonFRLG_OverworldReanchor.h | 23 ++++---- .../PokemonFRLG_OverworldRecovery.cpp | 38 ++++++++----- .../PokemonFRLG_AutoStoryActions.cpp | 9 ++- .../AutoStory/PokemonFRLG_AutoStoryActions.h | 11 +++- .../AutoStory/PokemonFRLG_AutoStoryRowSim.cpp | 11 +++- 6 files changed, 99 insertions(+), 48 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp index 8917415cfb..f5328d5980 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp @@ -17,6 +17,9 @@ namespace PokemonFRLG{ namespace{ constexpr size_t MAX_HOLDS = 3; +// How many of the route's steps after a leg walked on may go by before +// they find the player. +constexpr size_t MAX_WALK_ON_STEPS = 4; Direction opposite(Direction direction){ return (Direction)(((int)direction + 2) % 4); @@ -175,11 +178,6 @@ std::optional, RouteStep>> hold_all( return std::make_pair(std::move(ends), hold); } -// Whether `step` is a hold to a wall. -bool is_hold(const RouteStep& step){ - return step.action == RouteAction::WALK && step.to_wall && !step.warps; -} - using Found = Pokemon::WallAnchor; // Runtime world alternatives and movement mode, separate from the policy type. @@ -510,19 +508,28 @@ struct WayOn{ MapPosition at; }; -// `hold` from where each of `ways` stands. False if any isn't stopped by a -// wall, or may be stopped short by a person. -bool hold_ways(const std::vector& maps, const RouteStep& hold, std::vector& ways){ +// `step`, a hold to a wall or an open leg onto no warp, from where each of +// `ways` stands. False if a hold isn't stopped by a wall, an open leg is +// stopped short, or either may be stopped short by a person. +bool walk_ways(const std::vector& maps, const RouteStep& step, std::vector& ways){ + if (step.action != RouteAction::WALK || step.warps || !step.connection_steps.empty()){ + return false; + } for (WayOn& way : ways){ - const std::optional wall = hold_to_wall(maps, way.at, hold.surfing, hold.direction); - if (!wall || person_on_the_way(maps, way.at, hold.surfing, hold.direction, *wall)){ + std::optional walked = step.to_wall + ? hold_to_wall(maps, way.at, step.surfing, step.direction) + : std::optional(WallHold{.end = way.at, .tiles = step.tiles}); + if (!walked || person_on_the_way(maps, way.at, step.surfing, step.direction, *walked)){ return false; } - RouteStep held = hold; - held.tiles = wall->tiles; + RouteStep held = step; + held.tiles = walked->tiles; const std::vector tiles = leg_tiles(maps, way.at, held); + if (tiles.size() != (size_t)held.tiles + 1){ + return false; + } way.tiles.insert(way.tiles.end(), tiles.begin() + 1, tiles.end()); - way.at = wall->end; + way.at = tiles.back(); } return true; } @@ -575,18 +582,26 @@ std::optional plan_resume( if (!remaining){ return std::nullopt; } - RouteStep rest = step; - rest.tiles = *remaining; - std::optional> ways = walk_rest(maps, candidates, rest); + Resume resume{.rest = step, .steps = 0, .starts = {{}}}; + resume.rest.tiles = *remaining; + for (const StopCandidate& candidate : candidates){ + resume.starts[0].push_back(candidate.player); + } + std::optional> ways = walk_rest(maps, candidates, resume.rest); // The way as planned, from the leg's end. std::vector planned{WayOn{{step.end}, step.end}}; - for (size_t c = 0; ways && c < after.size() && c < MAX_HOLDS; c++){ - if (!is_hold(after[c]) || !hold_ways(maps, after[c], *ways) || !hold_ways(maps, after[c], planned)){ + for (size_t c = 0; ways && c < after.size() && c < MAX_WALK_ON_STEPS; c++){ + resume.starts.emplace_back(); + for (const WayOn& way : *ways){ + resume.starts.back().push_back(way.at); + } + if (!walk_ways(maps, after[c], *ways) || !walk_ways(maps, after[c], planned)){ return std::nullopt; } - const bool found = std::all_of(ways->begin(), ways->end(), [&](const WayOn& way){ return way.at == after[c].end; }); + const bool found = after[c].to_wall && std::all_of(ways->begin(), ways->end(), [&](const WayOn& way){ return way.at == after[c].end; }); if (found){ - return off_way_in_sight(maps, *ways, planned[0].tiles) ? std::nullopt : std::optional(Resume{rest, c + 1}); + resume.steps = c + 1; + return off_way_in_sight(maps, *ways, planned[0].tiles) ? std::nullopt : std::optional(std::move(resume)); } } return std::nullopt; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h index 7d0c2e2e69..28530d8c11 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h @@ -123,24 +123,27 @@ std::optional plan_reanchor( // Walking on along a stopped open leg instead of finding the player at // walls first: the rest of the leg from the middle of the tiles they may -// be on, after which the route's next holds, as planned, bring them to -// one tile from every one of them. Walking on from how far a leg got, -// trusting the timing, went wrong on the console; here the holds find the -// player whichever tile they were on. +// be on, after which the route's next steps, as planned, end with a hold +// that brings them to one tile from every one of them. Walking on from +// how far a leg got, trusting the timing, went wrong on the console; here +// a hold finds the player whichever tile they were on. struct Resume{ // From the middle candidate to the stopped leg's end; no tiles if the // middle candidate is its end. RouteStep rest; - // How many of the steps after the stopped leg, all holds to walls, - // bring every candidate to one tile. - size_t holds = 0; + // How many of the steps after the stopped leg go by until one, a hold + // to a wall, brings every candidate to one tile. + size_t steps = 0; + // Where each of those steps may start, `rest` first. + std::vector> starts; }; // After `step`, an open leg, stopped part-way on one of `candidates` // (none stopped by a trainer), with `after` the route's steps after it: -// the way to walk on. Nothing if the holds that start `after` don't bring -// every candidate to one tile, or if any would walk onto a tile off the -// planned way that a trainer may see. +// the way to walk on. Nothing if, from some candidate, a step of `after` +// before a hold that brings them all to one tile would walk otherwise +// than planned, or a way would cross a tile off the planned way that a +// trainer may see. std::optional plan_resume( const std::vector& maps, const std::vector& candidates, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp index ca9e278392..cddb0e2026 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp @@ -335,11 +335,11 @@ class RouteRun{ // of a leg walked on after a stop (walk_on()) starts on any of the // tiles that stop left the player on. std::vector candidates_on(const RouteStep& step, const std::optional& start, WalkedTiles walked) const{ - if (m_next != 0 || m_walk_on_starts.empty()){ + if (m_next >= m_walk_on_starts.size()){ return stop_candidates(*maps(), start, step, walked); } std::vector candidates; - for (const MapPosition& from : m_walk_on_starts){ + for (const MapPosition& from : m_walk_on_starts[m_next]){ for (const StopCandidate& candidate : stop_candidates(*maps(), from, step, walked)){ if (std::find(candidates.begin(), candidates.end(), candidate) == candidates.end()){ candidates.push_back(candidate); @@ -358,6 +358,15 @@ class RouteRun{ const RouteStep& step, const StepOutcome& outcome, const std::optional& start, const std::optional& crossing ){ + if (outcome.end == StepEnd::STOPPED && step.wild){ + // Where wild battles start, one on the first step held again + // after another interrupt stops the hold the same way: Cooper's + // battle, then a wild one, on Rock Tunnel B1F's column 1 (the + // sim, 2026-11-09). Walked again, as after any stop; a sign + // that interrupts every hold ends the route at MAX_ROUTE_STOPS. + m_lines.end(step, std::nullopt, EndBasis::UNKNOWN, "interrupted again right away where wild battles start; walking it again"); + return true; + } if (outcome.end == StepEnd::STOPPED){ // Interrupted at once, hold after hold: by something on the // way that speaks, a sign, which the plan didn't have there. @@ -426,22 +435,21 @@ class RouteRun{ } // The plan from here: the rest of `step`, the stopped leg m_plan[m_next], - // from the middle of `candidates`, then the old plan after it, whose - // first `resume.holds` steps find the player. The player still faces - // the leg's way: a turn tap first would step a tile. - void walk_on(const RouteStep& step, const Resume& resume, const std::vector& candidates){ + // then the old plan after it, whose first `resume.steps` steps find the + // player. The player still faces the leg's way: a turn tap first would + // step a tile. + void walk_on(const RouteStep& step, const Resume& resume){ std::vector plan; - m_walk_on_starts.clear(); + m_walk_on_starts = resume.starts; if (resume.rest.tiles > 0){ plan.push_back(resume.rest); - for (const StopCandidate& candidate : candidates){ - m_walk_on_starts.push_back(candidate.player); - } + }else{ + m_walk_on_starts.erase(m_walk_on_starts.begin()); } plan.insert(plan.end(), m_plan.begin() + m_next + 1, m_plan.end()); m_plan = std::move(plan); m_walked.reset(); - m_holds = (resume.rest.tiles > 0 ? 1 : 0) + resume.holds; + m_holds = (resume.rest.tiles > 0 ? 1 : 0) + resume.steps; m_unchecked = m_holds; m_next = 0; m_at = std::nullopt; @@ -463,10 +471,10 @@ class RouteRun{ const std::vector after(m_plan.begin() + m_next + 1, m_plan.end()); if (const std::optional resume = plan_resume(*maps(), candidates, step, after)){ m_calls.log(std::format( - "Route: walking on {} tiles along {}; the next {} hold(s) find the player from every one of those tiles.", - resume->rest.tiles, to_string(step), resume->holds + "Route: walking on {} tiles along {}; the next {} step(s) find the player from every one of those tiles.", + resume->rest.tiles, to_string(step), resume->steps )); - walk_on(step, *resume, candidates); + walk_on(step, *resume); return true; } const std::optional anchor = candidates.empty() @@ -511,7 +519,7 @@ class RouteRun{ size_t m_holds = 0; // of the plan, holds to walls that find the player size_t m_unchecked = 0; // of the plan, the holds and the way back after them std::optional m_walked; // the step walked last, if it may have stopped part-way - std::vector m_walk_on_starts; // where the plan's first step, a leg walked on, may start + std::vector> m_walk_on_starts; // after walking on: where each of the plan's first steps may start }; } // namespace diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp index 0f4ef4de91..cc73c34012 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp @@ -27,6 +27,7 @@ #include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_StartMenuDetector.h" #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleScreenDetector.h" #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_SelectionArrowDetector.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" #include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h" #include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_StartMenuNavigation.h" @@ -611,7 +612,13 @@ std::optional step_into_line( [&]{ WhiteDialogWatcher message(COLOR_RED); BattleScreenWatcher battle(COLOR_RED); - return wait_until(console, context, watch, {message, battle}) >= 0; + const int seen = wait_until(console, context, std::max(watch, WILD_BATTLE_IN_LINE_WATCH), {message, battle}); + if (seen == 1){ + console.log("Story: a wild battle on the step into a trainer's line; running from it, then stepping on.", COLOR_ORANGE); + flee_battle(console, context); + return false; + } + return seen == 0; } ); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h index e08122242b..2940c2fab4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h @@ -136,6 +136,14 @@ std::optional step_until_seen(int max_tiles, const std::function& s // "!", then their words, as the route walker watches for a trainer // with no tiles to walk up (PokemonFRLG_OverworldRecoveryWalk.cpp). inline constexpr Milliseconds TRAINER_LINE_WATCH(2500); +// How long a step into a trainer's line is watched for a wild battle it +// set off: its HP boxes, with no message before them, came over 5 s after +// the step in Mt. Moon (UNSEEN_BATTLE_WATCH). The trainer didn't see the +// player on that step (the game looks for trainers before it rolls for a +// wild battle), so it is run from and the stepping goes on: in Rock +// Tunnel the battle step after it found no trainer's message (the sim, +// 2026-11-09). +inline constexpr Milliseconds WILD_BATTLE_IN_LINE_WATCH(5000); // How long a step into the line of a trainer who looks around waits for // them to turn to the player (TRAINER_WAIT_VARIANT). @@ -143,7 +151,8 @@ inline constexpr Milliseconds TRAINER_WAIT_WATCH(30000); // From the overworld: step_until_seen() `direction`, turning first // unless `facing` is `direction`, each step watched `watch` for a -// trainer's message or battle. +// trainer's message, and at least WILD_BATTLE_IN_LINE_WATCH for a wild +// battle, which is run from. std::optional step_into_line( ConsoleHandle& console, ProControllerContext& context, Pokemon::Direction direction, std::optional facing, int max_tiles, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp index 791fe18e85..d9ba3fcd69 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp @@ -405,8 +405,17 @@ std::string OverworldStepSim::step_ahead(const StoryStep& step){ } m_sim.tap(step.direction); }; + // A wild battle, with no message before it, is run from, and the + // stepping goes on, as step_into_line() does. const auto seen = [this]{ - return m_sim.watch({SimWatcher::MESSAGE, SimWatcher::BATTLE_SCREEN}, TRAINER_LINE_WATCH).has_value(); + const std::optional shown = m_sim.watch( + {SimWatcher::MESSAGE, SimWatcher::BATTLE_SCREEN}, std::max(TRAINER_LINE_WATCH, WILD_BATTLE_IN_LINE_WATCH) + ); + if (shown && shown->watcher == 1){ + m_sim.handle_battle(SimBattleChoice::RUN); + return false; + } + return shown.has_value(); }; const int tiles = step.variant == TRAINER_LINE_VARIANT ? TRAINER_LINE_TILES : 1; return step_until_seen(tiles, tap, seen) ? "" : "no trainer saw the player."; From 62aa1d4e4289520a3a69cb254c8fe7c629d59a75 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 11:35:52 -0800 Subject: [PATCH 06/64] FRLG sim: wild battles at the game's own odds; 00.28 Monte Carlo numbers SimScript::encounter_rates rolls each step onto a wild tile as pokefirered TryStandardWildEncounter() does (8 - rate / 10 cooldown steps at 5%, then rate * 16 / 1600 plus a buff that grows with each roll lost; a battle clears both), seeded per run. Rock Tunnel 1F/B1F use rate 7, Route 10 21 (wild_encounters.json). SimState counts wild battles and their time. New test: 00.28 at those odds from 30 seeds must all pass, and logs the runs' numbers. At the same seeds, before this PR's walker fixes 13/30 passed; now 30/30. Over passing runs, before -> after: time 1037 -> 912 s mean (p90 1190 -> 1004), tiles 535 -> 406 (p90 679 -> 437), tiles walked again 158 -> 3 (p90 302 -> 34), wild battles 22.6 -> 17.7, time lost per battle 4.5 -> 0.3 s (p90 6.6 -> 2.0). With trainers checked before wild battles in the sim, Cooper is always fought: the 7-to-25-step test no longer allows him unfought. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Overworld/PokemonFRLG_OverworldSim.cpp | 57 ++++++- .../Overworld/PokemonFRLG_OverworldSim.h | 16 ++ .../PokemonFRLG_AutoStoryLavender_Tests.cpp | 153 +++++++++++++++--- 3 files changed, 202 insertions(+), 24 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index 59bfea0c60..e8631f50f0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -144,6 +144,7 @@ OverworldSim::OverworldSim(std::vector maps, MapPosition start, Directi : m_maps(std::move(maps)) , m_script(std::move(script)) , m_map(find_map(m_maps, start.map)) + , m_encounter_rng(m_script.encounter_seed) { if (m_map < 0){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Sim: start on a map that isn't loaded: " + start.map); @@ -378,13 +379,12 @@ bool OverworldSim::wild_battle(Milliseconds pressed){ return false; } m_grass_steps++; - for (const SimEncounter& encounter : m_script.encounters){ - if (encounter.grass_step != m_grass_steps){ - continue; - } + if (const std::optional encounter = next_encounter()){ m_frozen = true; + m_state.wild_battles++; + m_wild_battle_from = pressed; m_battle_pending = true; - if (!encounter.seen_late){ + if (!encounter->seen_late){ schedule(pressed + m_script.timing.flash, SimScreen::BATTLE_FLASH, false); } if (m_script.timing.battle_wipe){ @@ -394,12 +394,54 @@ bool OverworldSim::wild_battle(Milliseconds pressed){ schedule(pressed + *m_script.timing.battle_opening, SimScreen::BATTLE_OPENING, false); } schedule(pressed + m_script.timing.battle_screen, SimScreen::BATTLE, false); - note(std::format("a wild battle on {}{}.", to_string(m_state.position), encounter.seen_late ? " (flashes missed)" : "")); + note(std::format("a wild battle on {}{}.", to_string(m_state.position), encounter->seen_late ? " (flashes missed)" : "")); return true; } return false; } +// The encounter this step onto a wild tile starts, if any: the script's, +// or the game's roll on a map with an encounter rate. +std::optional OverworldSim::next_encounter(){ + const auto rate = m_script.encounter_rates.find(map().name); + if (rate != m_script.encounter_rates.end()){ + return rolls_encounter(rate->second) ? std::optional(SimEncounter{.grass_step = m_grass_steps}) : std::nullopt; + } + for (const SimEncounter& encounter : m_script.encounters){ + if (encounter.grass_step == m_grass_steps){ + return encounter; + } + } + return std::nullopt; +} + +// pokefirered TryStandardWildEncounter() on land, for a land encounter +// `rate`, with no Repel, flute, Cleanse Tag, lead ability or bike: +// - HandleWildEncounterCooldown(): until `min_steps` steps since the last +// battle (8 - rate / 10, 8 below rate 10, 0 from 80), a step goes on to +// the roll only 5 times in 100; +// - DoWildEncounterRateTest(): a battle if rand % 1600 < rate * 16 plus +// a buff, which grows by `rate` with each roll lost and is cleared by a +// battle, as the step count is. +// StandardWildEncounter()'s 60% roll on a step onto a tile of another +// behavior is left out: a cave's floor is one behavior. +bool OverworldSim::rolls_encounter(int rate){ + const int min_steps = rate >= 80 ? 0 : rate < 10 ? 8 : 8 - rate / 10; + if (m_steps_since_encounter < min_steps){ + m_steps_since_encounter++; + if (m_encounter_rng() % 100 >= 5){ + return false; + } + } + if ((int)(m_encounter_rng() % 1600) >= rate * 16 + m_encounter_rate_buff * 16 / 200){ + m_encounter_rate_buff += rate; + return false; + } + m_encounter_rate_buff = 0; + m_steps_since_encounter = 0; + return true; +} + // Blocked holding `direction` at `pressed`: a sign walked into moving north // or south shows its message. void OverworldSim::bump(Direction direction, Milliseconds pressed){ @@ -511,6 +553,9 @@ SimBattleEnd OverworldSim::handle_battle(SimBattleChoice choice){ show(SimScreen::OVERWORLD, m_now); m_frozen = false; m_battle_pending = false; + if (!m_trainer){ + m_state.in_wild_battles += m_now - m_wild_battle_from; + } if (m_trainer){ MapObject& trainer = m_maps[m_map].objects[*m_trainer]; trainer.trainer.reset(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index 32751834dc..fc90e5ba2b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -30,6 +30,7 @@ #include #include +#include #include #include #include @@ -115,6 +116,11 @@ struct SimScript{ // 2026-11-03, rows 00.16 and 00.20), not south from Route 6 into // Vermilion City (row 00.24). bool connections_stall = true; + // Wild battles at the game's own odds instead of `encounters`, on the + // maps named here, with their land encounter rate (pokefirered + // src/data/wild_encounters.json), rolled from `encounter_seed`. + std::map encounter_rates; + uint32_t encounter_seed = 0; SimTiming timing; }; @@ -138,6 +144,9 @@ struct SimState{ bool black_below = false; int steps = 0; int warps = 0; + int wild_battles = 0; + // From each wild battle's step to the overworld after it, together. + Milliseconds in_wild_battles{0}; int signs_read = 0; std::vector trainers_beaten; // Things the walker did that the game wouldn't let pass: D-pad holds @@ -243,6 +252,8 @@ class OverworldSim{ std::optional cross_edge(Direction direction) const; bool after_step(const Step& step, Milliseconds pressed); bool wild_battle(Milliseconds pressed); + std::optional next_encounter(); + bool rolls_encounter(int rate); bool trainer_sees(Milliseconds pressed); void update_view(); void note(const std::string& line); @@ -267,6 +278,11 @@ class OverworldSim{ // The trees cut since the last warp, and their maps. std::vector> m_cut_trees; int m_grass_steps = 0; + // The game's wild encounter state (SimScript::encounter_rates). + std::mt19937 m_encounter_rng; + int m_steps_since_encounter = 0; + int m_encounter_rate_buff = 0; + Milliseconds m_wild_battle_from{0}; int m_holds = 0; SimState m_state; }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp index faff538e47..7e123f4fcf 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp @@ -13,6 +13,8 @@ #include #include #include +#include +#include #include #include #include @@ -37,7 +39,7 @@ namespace{ struct AutoStoryLavenderInput{ std::string name; - std::function body; + std::function body; }; struct AutoStoryLavenderExpectation{ @@ -54,9 +56,9 @@ class Test_AutoStoryLavender : public UnitTest{ : UnitTest("PokemonFRLG::AutoStory - Simulation: " + test_case.input.name) , m_case(std::move(test_case)) {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ try{ - return m_case.input.body(); + return m_case.input.body(logger); }catch (Exception& e){ return std::string(e.name()) + ": " + e.message(); } @@ -98,6 +100,10 @@ std::string row_rest(OverworldSim& sim, StoryPose at, const StoryCheckpoint& row return ""; } +UnitTestResult row_checked( + OverworldSim& sim, std::string_view id, const std::vector>& fought, const MapPosition& end +); + // Row `id` on the sim with `script`: it ends on `end`, with no violation // on the way, having fought the trainers of one of `fought`, in order. UnitTestResult row_on_sim( @@ -106,6 +112,15 @@ UnitTestResult row_on_sim( const StoryCheckpoint& row = checkpoint(id); const StoryPose at = *story_pose(*row.start); OverworldSim sim(maps_after_route10(), MapPosition{at.map, at.tile}, *at.facing, script); + return row_checked(sim, id, fought, end); +} + +// Row `id` on `sim`, from its start, checked as row_on_sim() does. +UnitTestResult row_checked( + OverworldSim& sim, std::string_view id, const std::vector>& fought, const MapPosition& end +){ + const StoryCheckpoint& row = checkpoint(id); + const StoryPose at = *story_pose(*row.start); if (const std::string failure = row_rest(sim, at, row, 0); !failure.empty()){ return std::string(id) + ": " + failure; } @@ -128,24 +143,18 @@ UnitTestResult row_on_sim( const std::vector ROCK_TUNNEL_TRAINERS{ "poke_maniac", "poke_maniac", "picnicker", "hiker", "hiker", "picnicker", "hiker", "poke_maniac", "picnicker", }; -// Cooper unfought: a wild battle on the step into his sight, on the leg -// past him, starts first, and the sim's trainers look only after a step. -// The leg goes on past him to its wall either way. -const std::vector ROCK_TUNNEL_TRAINERS_BUT_COOPER{ - "poke_maniac", "poke_maniac", "picnicker", "hiker", "hiker", "picnicker", "hiker", "picnicker", -}; // 00.28 on the sim: the tree cut, the nine trainers fought where the // table steps into their lines (Cooper by the walker, on the leg past // him), no one else met, and the walk out of the south mouth. -UnitTestResult test_rock_tunnel_row(){ +UnitTestResult test_rock_tunnel_row(Logger&){ return row_on_sim("00.28", SimScript{}, {ROCK_TUNNEL_TRAINERS}, MapPosition{StoryTable::ROUTE10, {8, 58}}); } // 00.28 with a wild battle on the 3rd step on the tunnel's floor, mid-way // down the leg to the wall (17, 8): the walker runs, holds the leg to its // wall again, and nothing else changes. -UnitTestResult test_rock_tunnel_wild_battles(){ +UnitTestResult test_rock_tunnel_wild_battles(Logger&){ SimScript script; script.encounters.push_back(SimEncounter{.grass_step = 3}); return row_on_sim("00.28", script, {ROCK_TUNNEL_TRAINERS}, MapPosition{StoryTable::ROUTE10, {8, 58}}); @@ -179,7 +188,7 @@ size_t step_index(const StoryCheckpoint& row, std::string_view name){ // the leg started, and walked the whole 32 tiles again, until it gave up // ("stopped part-way 9 times"). From Winston's tile, with a battle every // 10 to 14 steps, the steps from below_martha_line on reach Martha's line. -UnitTestResult test_b1f_row37_battles_every_12(){ +UnitTestResult test_b1f_row37_battles_every_12(Logger&){ const StoryCheckpoint& row = checkpoint("00.28"); const size_t first = step_index(row, "below_martha_line"); StoryPose at{StoryTable::ROCK_TUNNEL_B1F, {29, 37}, Direction::NORTH}; @@ -196,7 +205,7 @@ UnitTestResult test_b1f_row37_battles_every_12(){ // 00.28 whole with a wild battle every 7 to 25 steps on the tunnel's floor, // the gaps drawn from each of these seeds: the row ends where it should. -UnitTestResult test_rock_tunnel_frequent_battles(){ +UnitTestResult test_rock_tunnel_frequent_battles(Logger&){ std::string failures; for (unsigned seed = 1; seed <= 12; seed++){ std::mt19937 random(seed); @@ -206,7 +215,7 @@ UnitTestResult test_rock_tunnel_frequent_battles(){ gaps.push_back(gap(random)); } const UnitTestResult result = row_on_sim( - "00.28", battles_every(gaps), {ROCK_TUNNEL_TRAINERS, ROCK_TUNNEL_TRAINERS_BUT_COOPER}, MapPosition{StoryTable::ROUTE10, {8, 58}} + "00.28", battles_every(gaps), {ROCK_TUNNEL_TRAINERS}, MapPosition{StoryTable::ROUTE10, {8, 58}} ); if (result.result != UnitTestResult::PASSED){ failures += std::format("{}Seed {}: {}", failures.empty() ? "" : " | ", seed, result.message); @@ -218,8 +227,115 @@ UnitTestResult test_rock_tunnel_frequent_battles(){ return true; } +// The sim at row `id`'s start, with `script`. +OverworldSim row_start_sim(std::string_view id, SimScript script){ + const StoryPose at = *story_pose(*checkpoint(id).start); + return OverworldSim(maps_after_route10(), MapPosition{at.map, at.tile}, *at.facing, std::move(script)); +} + +// One run of a row on the sim, against the same row with no wild battle. +struct RowRunNumbers{ + bool passed = false; + double seconds = 0; + int tiles = 0; + // Tiles walked beyond the run with no wild battle: walked again after + // a battle, finding the player and the way back. + int tiles_again = 0; + int battles = 0; + // Per wild battle, the time beyond the run with no wild battle, less + // the battles' own: from each battle's end until the walk is back + // where it was cut off. + double seconds_lost_per_battle = 0; +}; + +RowRunNumbers row_numbers(const SimState& run, bool passed, const SimState& clean){ + RowRunNumbers out; + out.passed = passed; + out.seconds = run.time.count() / 1000.; + out.tiles = run.steps; + out.tiles_again = run.steps - clean.steps; + out.battles = run.wild_battles; + const Milliseconds lost = run.time - clean.time - run.in_wild_battles; + out.seconds_lost_per_battle = run.wild_battles > 0 ? lost.count() / 1000. / run.wild_battles : 0; + return out; +} + +// The mean and 90th percentile of `values`. +std::string mean_p90(std::vector values){ + if (values.empty()){ + return "-"; + } + std::sort(values.begin(), values.end()); + const double mean = std::accumulate(values.begin(), values.end(), 0.) / values.size(); + const double p90 = values[std::min(values.size() - 1, (size_t)(0.9 * values.size()))]; + return std::format("mean {:.1f}, p90 {:.1f}", mean, p90); +} + +// How many of `runs` passed, and over those, the mean and 90th percentile +// of each number. +std::string numbers_summary(const std::vector& runs){ + std::vector seconds, tiles, again, battles, lost; + size_t passed = 0; + for (const RowRunNumbers& run : runs){ + passed += run.passed ? 1 : 0; + if (!run.passed){ + continue; + } + seconds.push_back(run.seconds); + tiles.push_back(run.tiles); + again.push_back(run.tiles_again); + battles.push_back(run.battles); + if (run.battles > 0){ + lost.push_back(run.seconds_lost_per_battle); + } + } + return std::format( + "passed {}/{}; of those passed: time (s) {}; tiles {}; tiles walked again {}; wild battles {}; s lost per battle {}", + passed, runs.size(), mean_p90(seconds), mean_p90(tiles), mean_p90(again), mean_p90(battles), mean_p90(lost) + ); +} + +// The land encounter rates of the maps 00.28 and 00.29 walk (pokefirered +// src/data/wild_encounters.json, FireRed). +const std::map ROCK_TUNNEL_ENCOUNTER_RATES{ + {StoryTable::ROCK_TUNNEL_1F, 7}, + {StoryTable::ROCK_TUNNEL_B1F, 7}, + {StoryTable::ROUTE10, 21}, +}; + +constexpr unsigned GAME_ODDS_SEEDS = 30; + +// 00.28 whole, its wild battles at the game's own odds (OverworldSim:: +// rolls_encounter()), from each of these seeds: every run ends where it +// should. Logs the runs' numbers. +UnitTestResult test_rock_tunnel_game_odds(Logger& logger){ + OverworldSim clean_sim = row_start_sim("00.28", SimScript{}); + if (const UnitTestResult clean = row_checked(clean_sim, "00.28", {ROCK_TUNNEL_TRAINERS}, MapPosition{StoryTable::ROUTE10, {8, 58}}); clean.result != UnitTestResult::PASSED){ + return clean; + } + std::vector runs; + std::string failures; + for (unsigned seed = 1; seed <= GAME_ODDS_SEEDS; seed++){ + SimScript script; + script.encounter_rates = ROCK_TUNNEL_ENCOUNTER_RATES; + script.encounter_seed = seed; + OverworldSim sim = row_start_sim("00.28", script); + const UnitTestResult result = row_checked(sim, "00.28", {ROCK_TUNNEL_TRAINERS}, MapPosition{StoryTable::ROUTE10, {8, 58}}); + const bool passed = result.result == UnitTestResult::PASSED; + runs.push_back(row_numbers(sim.state(), passed, clean_sim.state())); + if (!passed){ + failures += std::format("{}Seed {}: {}", failures.empty() ? "" : " | ", seed, result.message); + } + } + logger.log("00.28 at the game's encounter odds: " + numbers_summary(runs)); + if (!failures.empty()){ + return failures; + } + return true; +} + // 00.29 on the sim: no trainer met, the ledge hopped, Lavender's nurse. -UnitTestResult test_lavender_row(){ +UnitTestResult test_lavender_row(Logger&){ return row_on_sim("00.29", SimScript{}, {{}}, MapPosition{StoryTable::LAVENDER_CENTER, {7, 4}}); } @@ -276,17 +392,17 @@ UnitTestResult tile_off_after_open_legs(std::string_view id){ return true; } -UnitTestResult test_rock_tunnel_tile_off(){ +UnitTestResult test_rock_tunnel_tile_off(Logger&){ return tile_off_after_open_legs("00.28"); } -UnitTestResult test_lavender_tile_off(){ +UnitTestResult test_lavender_tile_off(Logger&){ return tile_off_after_open_legs("00.29"); } // 00.29 saves in Lavender Town's Pokemon Center, LAVENDER TOWN on the // save card; 00.28 on Route 10. -UnitTestResult test_save_places(){ +UnitTestResult test_save_places(Logger&){ if (save_card_place(StoryTable::LAVENDER_CENTER) != "lavender-town" || save_card_place(StoryTable::ROUTE10) != "route-10"){ return "Wrong save card places for Lavender Town's Center or Route 10."; } @@ -302,6 +418,7 @@ const AutoStoryLavenderCase AUTO_STORY_LAVENDER_CASES[] = { {.input = {"00.28 a tile off after each open leg", test_rock_tunnel_tile_off}, .expectation = {}}, {.input = {"00.28 B1F row 37 with a wild battle every 10 to 14 steps", test_b1f_row37_battles_every_12}, .expectation = {}}, {.input = {"00.28 a wild battle every 7 to 25 steps, 12 seeds", test_rock_tunnel_frequent_battles}, .expectation = {}}, + {.input = {"00.28 wild battles at the game's odds, 30 seeds", test_rock_tunnel_game_odds}, .expectation = {}}, {.input = {"00.29 Route 10 south, the ledge, Lavender Town's Pokemon Center", test_lavender_row}, .expectation = {}}, {.input = {"00.29 a tile off after each open leg", test_lavender_tile_off}, .expectation = {}}, {.input = {"00.28 and 00.29 save on Route 10 and in Lavender Town", test_save_places}, .expectation = {}}, From d5910eb861327b10d4ebcca4a0fca87d74640ae7 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 12:10:16 -0800 Subject: [PATCH 07/64] FRLG AutoStory: reach Martha's line up column 16, no one-tile step Console B run 2 of 00.28 lost the one-tile step north onto B1F row 34 after a wild battle on row 38; the walk east "to the wall (17, 34)" then ran along row 35 to the rock (20, 35) and martha_line found no trainer. below_martha_line now ends at (16, 35) and martha_line walks up column 16 (or 17, a tile short) into her line; below_allen_line starts with the walk east to the wall (17, 33). Sim test replays the console's battle and the short step. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_AutoStoryLavender_Tests.cpp | 42 ++++++++++++++++++- .../PokemonFRLG_AutoStoryTableLavender.cpp | 8 ++-- 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp index 7e123f4fcf..d4c9a95e63 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp @@ -197,8 +197,45 @@ UnitTestResult test_b1f_row37_battles_every_12(Logger&){ if (!failure.empty()){ return std::format("below_martha_line: ended on {}; {}", to_string(sim.state().position), failure); } - if (!(sim.state().position == MapPosition{StoryTable::ROCK_TUNNEL_B1F, {17, 34}})){ - return std::format("below_martha_line: ended on {}, not (17, 34).", to_string(sim.state().position)); + if (!(sim.state().position == MapPosition{StoryTable::ROCK_TUNNEL_B1F, {16, 35}})){ + return std::format("below_martha_line: ended on {}, not (16, 35).", to_string(sim.state().position)); + } + return true; +} + +// From Winston's tile, below_martha_line, martha_line and Martha's battle +// on `sim`: the failure, or empty once Martha alone is fought. +std::string winston_to_martha(OverworldSim& sim){ + const StoryCheckpoint& row = checkpoint("00.28"); + StoryPose at{StoryTable::ROCK_TUNNEL_B1F, {29, 37}, Direction::NORTH}; + for (size_t c = step_index(row, "below_martha_line"); c <= step_index(row, "picnicker_martha"); c++){ + if (const std::string failure = row_step_on_sim(sim, at, row.steps[c], row.id); !failure.empty()){ + return std::format("ended on {}; {}", to_string(sim.state().position), failure); + } + } + if (sim.state().trainers_beaten != std::vector{"picnicker"}){ + return std::format("ended on {}, Martha not fought.", to_string(sim.state().position)); + } + return ""; +} + +// Console B, 2026-11-09 (run 2): after Winston, the walk west along row +// 37 was found again at the wall (1, 38); a wild battle 0 to 2 tiles into +// the walk east along row 38 left the player on one of (1..3, 38), and +// the walk went on from there to the wall (19, 35). The one-tile step +// north onto row 34 then ended short with nothing seen, the walk east +// "to the wall (17, 34)" ran along row 35 to the rock (20, 35) instead +// (the end frame shows the wall (19, 34) north, the rock east), and +// martha_line found no trainer. Here the same battle, and the 10th hold +// (that step, before the route went up column 16 into her line) a tile +// short: Martha still sees the player. +UnitTestResult test_b1f_martha_after_row38_battle(Logger&){ + SimScript script; + script.encounters = {SimEncounter{.grass_step = 31}}; + script.short_holds = {{1, 2}, {10, 1}}; + OverworldSim sim(maps_after_route10(), MapPosition{StoryTable::ROCK_TUNNEL_B1F, {29, 37}}, Direction::NORTH, script); + if (const std::string failure = winston_to_martha(sim); !failure.empty()){ + return failure; } return true; } @@ -419,6 +456,7 @@ const AutoStoryLavenderCase AUTO_STORY_LAVENDER_CASES[] = { {.input = {"00.28 B1F row 37 with a wild battle every 10 to 14 steps", test_b1f_row37_battles_every_12}, .expectation = {}}, {.input = {"00.28 a wild battle every 7 to 25 steps, 12 seeds", test_rock_tunnel_frequent_battles}, .expectation = {}}, {.input = {"00.28 wild battles at the game's odds, 30 seeds", test_rock_tunnel_game_odds}, .expectation = {}}, + {.input = {"00.28 B1F a wild battle into row 38, then a step short: Martha still sees the player", test_b1f_martha_after_row38_battle}, .expectation = {}}, {.input = {"00.29 Route 10 south, the ledge, Lavender Town's Pokemon Center", test_lavender_row}, .expectation = {}}, {.input = {"00.29 a tile off after each open leg", test_lavender_tile_off}, .expectation = {}}, {.input = {"00.28 and 00.29 save on Route 10 and in Lavender Town", test_save_places}, .expectation = {}}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableLavender.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableLavender.cpp index 73ae6ffbf4..9613070677 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableLavender.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableLavender.cpp @@ -72,10 +72,10 @@ StoryCheckpoint rock_tunnel(){ running(legs("winston_line_end", {{WEST, 5}, {SOUTH, 10}, {NORTH, 1}, {WEST, 1}}, "west to the wall (33, 28), down column 33 to the wall (33, 38), up to (33, 37) and west to (32, 37)")), into_line("winston_line", WEST, "along row 37 onto (29, 37), the end of Winston's line: he walks down to (29, 36)"), battle("pokemaniac_winston", at(ROCK_TUNNEL_B1F, 29, 37, NORTH), false, "Slowpoke and Slowpoke"), - running(legs("below_martha_line", {{WEST, 16}, {NORTH, 2}, {EAST, 6}, {WEST, 3}, {NORTH, 1}, {EAST, 1}}, "west along row 37 to (13, 37), up to the wall (13, 35), east to the wall (19, 35), west to (16, 35), up to row 34 and east to the wall (17, 34)")), - into_line("martha_line", NORTH, "onto (17, 33), the end of Martha's line: she walks up to (16, 33)"), - battle("picnicker_martha", at(ROCK_TUNNEL_B1F, 17, 33, WEST), false, "Oddish and Bulbasaur"), - running(legs("below_allen_line", {{NORTH, 5}, {EAST, 12}, {NORTH, 9}, {EAST, 11}, {NORTH, 2}, {WEST, 2}, {NORTH, 5}}, "up column 17 to the wall (17, 28), east to the wall (29, 28), up column 29 past Steve's line to the wall (29, 19), east to (40, 19), up to row 17, west to the wall (38, 17) and up to the wall (38, 12)")), + running(legs("below_martha_line", {{WEST, 16}, {NORTH, 2}, {EAST, 6}, {WEST, 3}}, "west along row 37 to (13, 37), up to the wall (13, 35), east to the wall (19, 35), west to (16, 35)")), + into_line("martha_line", NORTH, "up column 16 onto (16, 33), beside Martha; from (17, 35), a tile short, up column 17 onto (17, 33), the end of her line"), + battle("picnicker_martha", at(ROCK_TUNNEL_B1F, 16, 33, WEST), false, "Oddish and Bulbasaur"), + running(legs("below_allen_line", {{EAST, 1}, {NORTH, 5}, {EAST, 12}, {NORTH, 9}, {EAST, 11}, {NORTH, 2}, {WEST, 2}, {NORTH, 5}}, "east to the wall (17, 33), up column 17 to the wall (17, 28), east to the wall (29, 28), up column 29 past Steve's line to the wall (29, 19), east to (40, 19), up to row 17, west to the wall (38, 17) and up to the wall (38, 12)")), into_line("allen_line", WEST, "along row 12 onto (36, 12), below Allen"), battle("hiker_allen", at(ROCK_TUNNEL_B1F, 36, 12, NORTH), false, "Geodude, Geodude and Graveler"), running(legs("west_of_b1f_ladder", {{WEST, 4}, {NORTH, 10}}, "west along row 12 to the wall (32, 12), up column 32 to the wall (32, 2)")), From d9dae0120b16d0b32b7eb6419bb6e217852f0860 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 12:17:41 -0800 Subject: [PATCH 08/64] FRLG walker: check each turn tap by the facing on screen, tap again if missed Console B lost the one-tile step north onto Rock Tunnel B1F row 34 in 00.28 run 2: the game missed the 40 ms turn tap, the leg's short hold then only turned the player (pokefirered PlayerTurnInPlace(), 8 frames), and the leg was taken as walked. OverworldWalkSteps::turn_to() taps, reads the facing (read_player_facing()) and taps again while it shows another way, up to 3 taps; an unreadable facing is taken as turned. Both walkers, step_once() and face_wall() turn with it. Sim: SimScript drops turn taps by number or at a rate; sim_turn_to() mirrors turn_to(), switched by SimWalkerRules::confirm_turn. New tests: a dropped tap before a one-tile leg (red without the rule), and 00.28 at the game's odds with 1 in 10 turn taps dropped, 30 seeds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_OverworldRecoveryWalk.cpp | 2 +- .../Overworld/PokemonFRLG_OverworldSim.cpp | 38 ++++++++++++++++++- .../Overworld/PokemonFRLG_OverworldSim.h | 28 +++++++++++++- .../PokemonFRLG_OverworldSim_Tests.cpp | 22 +++++++++++ .../Overworld/PokemonFRLG_OverworldWalk.cpp | 18 ++++++++- .../Overworld/PokemonFRLG_OverworldWalk.h | 13 +++++++ .../PokemonFRLG_AutoStoryActions.cpp | 15 +++----- .../AutoStory/PokemonFRLG_AutoStoryActions.h | 11 ++++-- .../PokemonFRLG_AutoStoryCapture.cpp | 2 +- .../AutoStory/PokemonFRLG_AutoStoryEvents.cpp | 8 ++-- .../PokemonFRLG_AutoStoryLavender_Tests.cpp | 29 ++++++++++++-- .../PokemonFRLG_AutoStoryPaceSim.cpp | 2 +- .../AutoStory/PokemonFRLG_AutoStoryRowSim.cpp | 6 +-- 13 files changed, 163 insertions(+), 31 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp index bff34929c3..8bf845563a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp @@ -66,7 +66,7 @@ StepWalk walk_step( // facing the right way: holding through a turn lost a tile on the // console, while holds from a standstill were exact over 15 tiles. if (facing != step.direction){ - pbf_press_dpad(context, dpad(step.direction), TURN_TAP, TURN_SETTLE); + turn_to(console, context, step.direction); } if (const std::string note = speed_note(step, speed); !note.empty()){ console.log(note); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index e8631f50f0..c3bb6346e6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -145,6 +145,7 @@ OverworldSim::OverworldSim(std::vector maps, MapPosition start, Directi , m_script(std::move(script)) , m_map(find_map(m_maps, start.map)) , m_encounter_rng(m_script.encounter_seed) + , m_tap_rng(m_script.turn_tap_seed) { if (m_map < 0){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Sim: start on a map that isn't loaded: " + start.map); @@ -524,13 +525,36 @@ void OverworldSim::tap(Direction direction){ if (m_state.screen != SimScreen::OVERWORLD || m_frozen){ stuck_hold(direction); }else if (m_state.facing != direction){ - m_state.facing = direction; + if (drops_turn_tap()){ + m_state.turn_taps_dropped++; + note(std::string("the turn tap ") + direction_name(direction) + " is dropped."); + }else{ + m_state.facing = direction; + } }else{ walk_hold(direction, m_script.timing.tile / 2, 0); } advance_to(m_now + TAP_TIME); } +std::optional OverworldSim::facing_on_screen() const{ + if (m_state.screen != SimScreen::OVERWORLD){ + return std::nullopt; + } + return m_state.facing; +} + +bool OverworldSim::drops_turn_tap(){ + m_turn_taps++; + if (m_script.dropped_turn_taps.contains(m_turn_taps)){ + return true; + } + if (m_script.turn_tap_drop_rate <= 0){ + return false; + } + return std::uniform_real_distribution(0, 1)(m_tap_rng) < m_script.turn_tap_drop_rate; +} + std::optional OverworldSim::watch(const std::vector& watchers, Milliseconds duration){ return watch_until(watchers, m_now, m_now + duration); } @@ -745,7 +769,7 @@ std::optional OverworldSimWalker::walk_step(const RouteStep& step, fail("Sim: Surf isn't modelled."); } if (facing != step.direction){ - m_sim.tap(step.direction); + sim_turn_to(m_sim, step.direction, m_rules.confirm_turn); } const int warps_before = m_sim.state().warps; const std::vector& ints = interrupts(step); @@ -894,6 +918,16 @@ RouteCalls OverworldSimWalker::calls(){ return calls; } +void sim_turn_to(OverworldSim& sim, Direction direction, bool confirm){ + for (size_t tap = 1; tap <= MAX_TURN_TAPS; tap++){ + sim.tap(direction); + const std::optional facing = sim.facing_on_screen(); + if (!confirm || !facing || *facing == direction){ + return; + } + } +} + std::string OverworldSimWalker::run(const std::vector& route, const RoutePlanning& planning){ try{ run_route(route, m_sim.state().facing, &planning, calls()); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index fc90e5ba2b..f2db259d5f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -121,6 +121,14 @@ struct SimScript{ // src/data/wild_encounters.json), rolled from `encounter_seed`. std::map encounter_rates; uint32_t encounter_seed = 0; + // Turn taps (taps while the player faces another way) the game misses: + // the player goes on facing the old way. By number, from 1, and each + // with probability `turn_tap_drop_rate`, rolled from `turn_tap_seed`. + // After one, a hold of a tile only turns the player (console B, + // 2026-11-09, 00.28 run 2). + std::set dropped_turn_taps; + double turn_tap_drop_rate = 0; + uint32_t turn_tap_seed = 0; SimTiming timing; }; @@ -148,6 +156,7 @@ struct SimState{ // From each wild battle's step to the overworld after it, together. Milliseconds in_wild_battles{0}; int signs_read = 0; + int turn_taps_dropped = 0; std::vector trainers_beaten; // Things the walker did that the game wouldn't let pass: D-pad holds // under a battle, a trainer's battle fled, a battle fought that wasn't @@ -202,9 +211,13 @@ class OverworldSim{ ); // A short press of `direction`: turns the player, or steps if they - // already face that way. + // already face that way. A turn may be dropped (SimScript::dropped_turn_taps). void tap(Direction direction); + // The way the player faces, as read_player_facing() reads it: on the + // overworld only. + std::optional facing_on_screen() const; + // Watches `watchers` for `duration`, as wait_until(). std::optional watch(const std::vector& watchers, Milliseconds duration); @@ -254,6 +267,7 @@ class OverworldSim{ bool wild_battle(Milliseconds pressed); std::optional next_encounter(); bool rolls_encounter(int rate); + bool drops_turn_tap(); bool trainer_sees(Milliseconds pressed); void update_view(); void note(const std::string& line); @@ -282,6 +296,9 @@ class OverworldSim{ std::mt19937 m_encounter_rng; int m_steps_since_encounter = 0; int m_encounter_rate_buff = 0; + // The turn taps so far, and what rolls their drops. + int m_turn_taps = 0; + std::mt19937 m_tap_rng; Milliseconds m_wild_battle_from{0}; int m_holds = 0; SimState m_state; @@ -351,8 +368,17 @@ struct SimWalkerRules{ // 2026-11-09 01:41, 00.27, the warp to CeruleanCity: the watch started // about 1.3 s into the hold). bool watch_fade_along_hold = true; + // A turn tap is checked by the facing on screen, and tapped again + // while the player faces another way (OverworldWalkSteps::turn_to()). + // Without it a dropped tap left a one-tile leg turning the player + // only, taken as walked (console B, 2026-11-09, 00.28 run 2). + bool confirm_turn = true; }; +// OverworldWalkSteps::turn_to() on `sim`; with `confirm` false, the one +// tap before it. +void sim_turn_to(OverworldSim& sim, Direction direction, bool confirm = SimWalkerRules{}.confirm_turn); + // The console side of run_route() on an OverworldSim, as // walk_overworld_route_with_recovery() does it, with the story's // interrupts: a wild battle (flashes, or seen late) is fought or run from, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp index 7b7fb39c46..43d3a16ad6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp @@ -486,6 +486,27 @@ UnitTestResult test_short_leg_unseen(){ return true; } +// Console B, 2026-11-09 (00.28 run 2): the game missed the turn tap before +// a one-tile open leg, the leg's hold only turned the player, and the leg +// was taken as walked. The walker now reads the facing after the tap and +// taps again; without that the player stays where they started. +UnitTestResult test_dropped_turn_tap(){ + SimCase c{.start = at("ViridianForest", 13, 28), .facing = Direction::NORTH, .goal = at("ViridianForest", 12, 28)}; + c.route = std::vector{leg(Direction::WEST, 1, c.goal, false)}; + c.script.dropped_turn_taps = {1}; + const SimRun now = run_case(c); + if (!arrived(now, c.goal) || now.state.turn_taps_dropped != 1){ + return "Expected the turn tapped again and the step walked:" + describe(now); + } + SimCase unchecked = c; + unchecked.rules.confirm_turn = false; + const SimRun old = run_case(unchecked); + if (!old.failure.empty() || !(old.state.position == c.start)){ + return "Expected the leg taken as walked from the start without the check:" + describe(old); + } + return true; +} + // r18 (console B, 2026-11-01), Pewter Gym: after Brock, Camper Liam sees // the player on the walk south to the door, walks up and battles. The // route holds on south to the door's mat; finding the player again at @@ -961,6 +982,7 @@ const OverworldSimCase OVERWORLD_SIM_CASES[] = { {.input = {"no hold over a ledge", test_no_hold_over_ledge}, .expectation = {},}, {.input = {"a short leg, then a sign", test_short_leg_then_sign}, .expectation = {},}, {.input = {"a short leg, nothing seen", test_short_leg_unseen}, .expectation = {},}, + {.input = {"a dropped turn tap before a one-tile leg", test_dropped_turn_tap}, .expectation = {},}, {.input = {"a trainer on the way out of Pewter Gym", test_trainer_on_way_out}, .expectation = {},}, {.input = {"out of Viridian Mart from the clerk's scene", test_mart_exit}, .expectation = {},}, {.input = {"Mt. Moon: down the ladders to B2F", test_mt_moon_ladders}, .expectation = {},}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp index f6332251fb..008e7089cc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp @@ -377,6 +377,22 @@ std::optional read_facing(ConsoleHandle& console, ProControllerContex return facing; } +void turn_to(ConsoleHandle& console, ProControllerContext& context, Direction direction){ + for (size_t tap = 1; tap <= MAX_TURN_TAPS; tap++){ + pbf_press_dpad(context, dpad(direction), TURN_TAP, TURN_SETTLE); + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + const std::optional facing = screen ? read_player_facing(screen) : std::nullopt; + if (!facing || *facing == direction){ + return; + } + console.log(std::format( + "Route: after turn tap {} {}, the player faces {}.", + tap, Pokemon::direction_name(direction), Pokemon::direction_name(*facing) + ), COLOR_ORANGE); + } +} + void start_surf(ConsoleHandle& console, ProControllerContext& context, Direction direction, bool facing_water){ // "The water is a deep blue... Would you like to SURF?", with YES selected. // An A pressed while the player is still turning is lost. @@ -515,7 +531,7 @@ void walk_overworld_route( // facing the right way: holding through a turn lost a tile on the // console, while holds from a standstill were exact over 15 tiles. if (facing != step.direction){ - pbf_press_dpad(context, dpad(step.direction), TURN_TAP, TURN_SETTLE); + turn_to(console, context, step.direction); } if (const std::string note = speed_note(step, speed); !note.empty()){ console.log(note); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h index c74361044e..8325dac772 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h @@ -110,6 +110,8 @@ inline constexpr Milliseconds RUN_TILE_TIME(133); inline constexpr Milliseconds TURN_TAP(40); // duration to wait after turning to allow state to settle. inline constexpr Milliseconds TURN_SETTLE(300); +// How many taps turn_to() tries before it takes the player as turned. +inline constexpr size_t MAX_TURN_TAPS = 3; // short enough to turn without stepping. inline constexpr Milliseconds FACE_HOLD(40); // duration of button release between movement steps. @@ -235,6 +237,17 @@ void check_warp_was_no_battle(ConsoleHandle& console, ProControllerContext& cont // The way the player faces, read from the screen; nothing if it can't be read. std::optional read_facing(ConsoleHandle& console, ProControllerContext& context); +// Turns the player to `direction` with a tap (TURN_TAP), then reads the +// facing from the screen and taps again while it shows another way, up to +// MAX_TURN_TAPS taps. A tap the game misses leaves the player facing the +// old way, and a leg's hold then spends its first 8 frames turning +// (pokefirered PlayerTurnInPlace(), a fast walk in place): a one-tile +// hold only turns the player, with nothing to show it (console B, +// 2026-11-09, 00.28 run 2: the step north onto Rock Tunnel B1F row 34). +// A facing that can't be read is taken as turned: a tap while facing the +// way already would take a step. +void turn_to(ConsoleHandle& console, ProControllerContext& context, Direction direction); + // Facing `direction` (turning first unless `facing_water`), starts Surf. void start_surf(ConsoleHandle& console, ProControllerContext& context, Direction direction, bool facing_water); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp index cc73c34012..e009d01701 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp @@ -27,6 +27,7 @@ #include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_StartMenuDetector.h" #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleScreenDetector.h" #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_SelectionArrowDetector.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" #include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h" @@ -57,9 +58,6 @@ constexpr Milliseconds INTRO_TIMEOUT = 600000ms; // "Wait about 8 s" after YES at the nurse (console B, 2026-11-01): 1.5 s // between presses did not heal. constexpr Milliseconds HEAL_TIME = 8000ms; -// FRLG takes a tap this short as a turn, without a step. -constexpr Milliseconds TURN_TAP = 40ms; -constexpr Milliseconds TURN_SETTLE = 300ms; DpadPosition dpad(Direction direction){ switch (direction){ @@ -580,9 +578,9 @@ std::optional talk_and_count_pages(ConsoleHandle& console, ProController return pages; } -void step_once(ProControllerContext& context, Direction direction, std::optional facing){ +void step_once(ConsoleHandle& console, ProControllerContext& context, Direction direction, std::optional facing){ if (facing != direction){ - pbf_press_dpad(context, dpad(direction), TURN_TAP, TURN_SETTLE); + OverworldWalkSteps::turn_to(console, context, direction); } // A step, once started, finishes on its own. pbf_press_dpad(context, dpad(direction), 120ms, 500ms); @@ -606,7 +604,7 @@ std::optional step_into_line( return step_until_seen( max_tiles, [&]{ - step_once(context, direction, facing); + step_once(console, context, direction, facing); facing = direction; }, [&]{ @@ -623,9 +621,8 @@ std::optional step_into_line( ); } -void face_wall(ProControllerContext& context, Direction direction){ - pbf_press_dpad(context, dpad(direction), TURN_TAP, TURN_SETTLE); - context.wait_for_all_requests(); +void face_wall(ConsoleHandle& console, ProControllerContext& context, Direction direction){ + OverworldWalkSteps::turn_to(console, context, direction); } SaveAction SaveDialog::next(SaveScreen screen){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h index 2940c2fab4..efbd5b8679 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h @@ -121,8 +121,11 @@ std::optional talk_and_count_pages(ConsoleHandle& console, ProController // From the overworld: one step `direction`, onto a trigger or into a door. // `facing` is the way the player faces, if known; a player facing another -// way is turned first. -void step_once(ProControllerContext& context, Pokemon::Direction direction, std::optional facing); +// way is turned first (OverworldWalkSteps::turn_to()). +void step_once( + ConsoleHandle& console, ProControllerContext& context, + Pokemon::Direction direction, std::optional facing +); // Steps with `step` a tile at a time, at most `max_tiles`, until `seen` // says a trainer saw the player. Returns the tiles stepped, or nothing @@ -160,8 +163,8 @@ std::optional step_into_line( ); // From the overworld, turns to face `direction` without stepping: the -// player must have a wall that way. -void face_wall(ProControllerContext& context, Pokemon::Direction direction); +// player must have a wall that way (OverworldWalkSteps::turn_to()). +void face_wall(ConsoleHandle& console, ProControllerContext& context, Pokemon::Direction direction); // The save dialog after SAVE, as pokefirered's start_menu.c runs it: // "Would you like to save the game?" YES/NO (YES first). Then, over a save diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.cpp index 860a78a259..c99038983f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.cpp @@ -487,7 +487,7 @@ bool ConsolePatchSteps::step(){ const int ret = run_until( m_console, m_context, [&](ProControllerContext& context){ - step_once(context, way, m_spot.facing); + step_once(m_console, context, way, m_spot.facing); }, {battle} ); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index 00fdd207dd..13a39e6cae 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -77,7 +77,7 @@ std::optional face_a_wall(StoryEnv& env, const MapPosition& position) const std::optional wall = wall_beside(*map, position.point); if (wall){ env.console.log(std::string("Story: facing unknown, turning to the wall ") + direction_name(*wall) + "."); - face_wall(env.context, *wall); + face_wall(env.console, env.context, *wall); } return wall; } @@ -192,7 +192,7 @@ Outcome take_step(StoryEnv& env, RunState& state, const StoryStep& step){ return Pokemon::outcome_failed("no_trainer", std::format("{} s on the tile {}", TRAINER_WAIT_WATCH.count() / 1000, direction_name(step.direction))); } }else{ - step_once(env.context, step.direction, facing_of(state.pose)); + step_once(env.console, env.context, step.direction, facing_of(state.pose)); } const std::vector tiles = Pokemon::tiles_of(state.pose); if (tiles.size() != 1){ @@ -618,12 +618,12 @@ Outcome cut_tree(StoryEnv& env, RunState& state, const StoryStep& step){ } if (here->facing != step.direction){ // The tree is in the way: a tap only turns the player to it. - face_wall(env.context, step.direction); + face_wall(env.console, env.context, step.direction); } pbf_press_button(env.context, BUTTON_A, 160ms, 800ms); answer_yes_no(env.console, env.context, true, BUTTON_B, YES_NO_TIMEOUT); mash_until_overworld(env.console, env.context, SCENE_TIMEOUT); - step_once(env.context, step.direction, step.direction); + step_once(env.console, env.context, step.direction, step.direction); return Pokemon::outcome_ok(to_pose(StoryPose{here->map, here->tile.next(step.direction), step.direction})); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp index d4c9a95e63..4de9243862 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp @@ -341,36 +341,56 @@ const std::map ROCK_TUNNEL_ENCOUNTER_RATES{ }; constexpr unsigned GAME_ODDS_SEEDS = 30; +// The share of turn taps the sim drops (SimScript::turn_tap_drop_rate): +// a guess well above what the console showed, one in 00.28 run 2. +constexpr double TURN_TAP_DROP_RATE = 0.1; // 00.28 whole, its wild battles at the game's own odds (OverworldSim:: -// rolls_encounter()), from each of these seeds: every run ends where it -// should. Logs the runs' numbers. -UnitTestResult test_rock_tunnel_game_odds(Logger& logger){ +// rolls_encounter()) and `turn_tap_drop_rate` of its turn taps dropped, +// from each of these seeds: every run ends where it should. Logs the +// runs' numbers. +UnitTestResult rock_tunnel_game_odds(Logger& logger, double turn_tap_drop_rate){ OverworldSim clean_sim = row_start_sim("00.28", SimScript{}); if (const UnitTestResult clean = row_checked(clean_sim, "00.28", {ROCK_TUNNEL_TRAINERS}, MapPosition{StoryTable::ROUTE10, {8, 58}}); clean.result != UnitTestResult::PASSED){ return clean; } std::vector runs; std::string failures; + int dropped = 0; for (unsigned seed = 1; seed <= GAME_ODDS_SEEDS; seed++){ SimScript script; script.encounter_rates = ROCK_TUNNEL_ENCOUNTER_RATES; script.encounter_seed = seed; + script.turn_tap_drop_rate = turn_tap_drop_rate; + script.turn_tap_seed = seed; OverworldSim sim = row_start_sim("00.28", script); const UnitTestResult result = row_checked(sim, "00.28", {ROCK_TUNNEL_TRAINERS}, MapPosition{StoryTable::ROUTE10, {8, 58}}); const bool passed = result.result == UnitTestResult::PASSED; runs.push_back(row_numbers(sim.state(), passed, clean_sim.state())); + dropped += sim.state().turn_taps_dropped; if (!passed){ failures += std::format("{}Seed {}: {}", failures.empty() ? "" : " | ", seed, result.message); } } - logger.log("00.28 at the game's encounter odds: " + numbers_summary(runs)); + logger.log(std::format( + "00.28 at the game's encounter odds, {} turn taps dropped: {}", dropped, numbers_summary(runs) + )); if (!failures.empty()){ return failures; } return true; } +UnitTestResult test_rock_tunnel_game_odds(Logger& logger){ + return rock_tunnel_game_odds(logger, 0); +} + +// The same with one turn tap in TURN_TAP_DROP_RATE dropped by the game +// (console B, 2026-11-09, 00.28 run 2). +UnitTestResult test_rock_tunnel_dropped_turn_taps(Logger& logger){ + return rock_tunnel_game_odds(logger, TURN_TAP_DROP_RATE); +} + // 00.29 on the sim: no trainer met, the ledge hopped, Lavender's nurse. UnitTestResult test_lavender_row(Logger&){ return row_on_sim("00.29", SimScript{}, {{}}, MapPosition{StoryTable::LAVENDER_CENTER, {7, 4}}); @@ -456,6 +476,7 @@ const AutoStoryLavenderCase AUTO_STORY_LAVENDER_CASES[] = { {.input = {"00.28 B1F row 37 with a wild battle every 10 to 14 steps", test_b1f_row37_battles_every_12}, .expectation = {}}, {.input = {"00.28 a wild battle every 7 to 25 steps, 12 seeds", test_rock_tunnel_frequent_battles}, .expectation = {}}, {.input = {"00.28 wild battles at the game's odds, 30 seeds", test_rock_tunnel_game_odds}, .expectation = {}}, + {.input = {"00.28 wild battles at the game's odds and 1 in 10 turn taps dropped, 30 seeds", test_rock_tunnel_dropped_turn_taps}, .expectation = {}}, {.input = {"00.28 B1F a wild battle into row 38, then a step short: Martha still sees the player", test_b1f_martha_after_row38_battle}, .expectation = {}}, {.input = {"00.29 Route 10 south, the ledge, Lavender Town's Pokemon Center", test_lavender_row}, .expectation = {}}, {.input = {"00.29 a tile off after each open leg", test_lavender_tile_off}, .expectation = {}}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPaceSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPaceSim.cpp index 19cb975a72..46a8fe1ea7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPaceSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPaceSim.cpp @@ -25,7 +25,7 @@ SimPatch::SimPatch(OverworldSim& sim, Direction pace, Direction back, std::funct bool SimPatch::step(){ const Direction way = m_displaced ? m_back : m_pace; if (m_sim.state().facing != way){ - m_sim.tap(way); + sim_turn_to(m_sim, way); } m_sim.tap(way); m_displaced = !m_displaced; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp index d9ba3fcd69..e54680468e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp @@ -401,7 +401,7 @@ std::string OverworldStepSim::step_ahead(const StoryStep& step){ } const auto tap = [this, &step]{ if (m_sim.state().facing != step.direction){ - m_sim.tap(step.direction); + sim_turn_to(m_sim, step.direction); } m_sim.tap(step.direction); }; @@ -424,7 +424,7 @@ std::string OverworldStepSim::step_ahead(const StoryStep& step){ // A hop() or step_onto(): one step, ending where the table says. std::string OverworldStepSim::step_onto(const StoryStep& step){ if (m_sim.state().facing != step.direction){ - m_sim.tap(step.direction); + sim_turn_to(m_sim, step.direction); } m_sim.tap(step.direction); m_at = *story_pose(*step.pose_after); @@ -435,7 +435,7 @@ std::string OverworldStepSim::step_onto(const StoryStep& step){ // tile. std::string OverworldStepSim::cut(const StoryStep& step){ if (m_sim.state().facing != step.direction){ - m_sim.tap(step.direction); + sim_turn_to(m_sim, step.direction); } if (!m_sim.cut_tree()){ return "no tree to cut."; From 680662b0a4772c09cac638f7597b347504675de0 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 12:18:01 -0800 Subject: [PATCH 09/64] StoryInterrupts: a battle's opening before a battle step is the step's An UNSETTLED look (a fade with no battle yet) failed any step as interrupt_unsettled after three looks, including a BATTLE step whose battle was already opening (BDSP 00.02's Starly battle right after the starter pick, lab-B run 3). A step that starts on WILD_ENCOUNTER or TRAINER_SIGHT now starts on UNSETTLED too, and gets it on the first look. Walk steps keep the check. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryInterrupts.cpp | 17 +++++++++++++---- .../AutoStory/Pokemon_StoryInterrupts.h | 11 ++++++++--- .../Pokemon_StoryInterrupts_Tests.cpp | 19 +++++++++++++++++++ 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp index 258d334ba2..0f64cbb35e 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp @@ -37,7 +37,13 @@ void InterruptHandlerTable::starts_on(StoryStepKind step, InterruptKind kind){ } bool InterruptHandlerTable::step_starts_on(StoryStepKind step, InterruptKind kind) const{ - return m_starts_on.contains({step, kind}); + if (m_starts_on.contains({step, kind})){ + return true; + } + return kind == InterruptKind::UNSETTLED && ( + m_starts_on.contains({step, InterruptKind::WILD_ENCOUNTER}) || + m_starts_on.contains({step, InterruptKind::TRAINER_SIGHT}) + ); } @@ -49,9 +55,12 @@ InterruptVerdict judge(const StoryInterrupts& interrupts, bool fresh){ } // The look's verdict, looked at again while it is unsettled, up to -// max_looks looks in all. -InterruptVerdict settled_verdict(const StoryInterrupts& interrupts){ +// max_looks looks in all; not again before a step that starts on it. +InterruptVerdict settled_verdict(const StoryInterrupts& interrupts, StoryStepKind step){ InterruptVerdict verdict = judge(interrupts, true); + if (interrupts.handlers.step_starts_on(step, InterruptKind::UNSETTLED)){ + return verdict; + } for (size_t looks = 1; verdict.kind == InterruptKind::UNSETTLED && looks < interrupts.max_looks; looks++){ verdict = judge(interrupts, false); } @@ -63,7 +72,7 @@ InterruptVerdict settled_verdict(const StoryInterrupts& interrupts){ InterruptCheck clear_story_interrupt(const StoryInterrupts& interrupts, RunState& state, const StoryStep& step){ InterruptCheck out; - out.verdict = settled_verdict(interrupts); + out.verdict = settled_verdict(interrupts, step.kind); const InterruptKind kind = out.verdict.kind; if (kind == InterruptKind::NONE){ return out; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h index 048aa8538f..76df68eb3e 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h @@ -17,7 +17,10 @@ * * A step that starts on what the look found (a MASH on its scene's box, * a BATTLE on its trainer's lines) is not interrupted by it: the table - * says which (InterruptHandlerTable::starts_on()). + * says which (InterruptHandlerTable::starts_on()). A step that starts on + * a battle also starts on an UNSETTLED screen, a fade with no battle yet: + * that is its battle's opening, still playing (BDSP's Starly battle right + * after the starter is picked), and the step waits for it itself. * */ @@ -72,7 +75,8 @@ class InterruptHandlerTable{ const InterruptHandler* find(InterruptKind kind) const; // Steps of `step` start on `kind` showing: before one, it is the - // step's to clear, not an interrupt. + // step's to clear, not an interrupt. A step that starts on + // WILD_ENCOUNTER or TRAINER_SIGHT starts on UNSETTLED too. void starts_on(StoryStepKind step, InterruptKind kind); bool step_starts_on(StoryStepKind step, InterruptKind kind) const; @@ -89,7 +93,8 @@ struct StoryInterrupts{ InterruptKnobs knobs = {}; InterruptHandlerTable handlers = {}; // Looks at a screen that stays UNSETTLED (a fade with no battle yet) - // before it fails the step as "interrupt_unsettled". + // before it fails the step as "interrupt_unsettled". A step that + // starts on it gets it on the first look. size_t max_looks = 3; // Interrupts cleared for one step before it fails as // "too_many_interrupts". diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp index 2dedf86142..8f4d0644c5 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -309,6 +309,21 @@ UnitTestResult test_unsettled_is_bounded(){ return expect_trace(game, {"look", "look again", "look again", "told unsettled interrupt_unsettled: walk"}); } +// A battle's opening still playing when a step that starts on a battle +// begins (BDSP's Starly battle, right after the starter is picked): the +// step's, on the first look, not interrupt_unsettled. +UnitTestResult test_unsettled_before_a_battle(){ + FakeGame game; + game.screens = {white_unsettled()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers.starts_on(StoryStepKind::BATTLE, InterruptKind::WILD_ENCOUNTER); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::BATTLE, "starly")); + if (!run.outcome.succeeded()){ + return "Expected the battle step to run, got " + to_string(run.outcome); + } + return expect_trace(game, {"look", "run starly"}); +} + UnitTestResult test_failure_explained(bool throws){ FakeGame game; // Before the step, after its failure, before its second run. @@ -443,6 +458,10 @@ const StoryInterruptsCase STORY_INTERRUPTS_CASES[] = { .input = {.name = "unsettled: at most max_looks looks", .test = test_unsettled_is_bounded}, .expectation = {.description = "interrupt_unsettled after three looks"}, }, + { + .input = {.name = "unsettled: a battle's opening before a battle step", .test = test_unsettled_before_a_battle}, + .expectation = {.description = "the step's, after one look"}, + }, { .input = {.name = "a failed step an interrupt explains runs again", .test = test_failed_outcome_explained}, .expectation = {.description = "cleared after the failure, then the step again"}, From d40ae84694f2660248fec28403d4bc4e41dd469b Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 12:25:20 -0800 Subject: [PATCH 10/64] FRLG walker: turn tap tests in the walk tests; no extra public sim method Code health: OverworldSim kept at 7 public methods (sim_turn_to() reads the state) and OverworldSim_Tests under 1000 lines (the turn tap cases moved to OverworldWalk_Tests, as a table). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Overworld/PokemonFRLG_OverworldSim.cpp | 11 +-- .../Overworld/PokemonFRLG_OverworldSim.h | 8 +-- .../PokemonFRLG_OverworldSim_Tests.cpp | 22 ------ .../PokemonFRLG_OverworldWalk_Tests.cpp | 72 +++++++++++++++++++ 4 files changed, 76 insertions(+), 37 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index c3bb6346e6..3b92f27ef2 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -537,13 +537,6 @@ void OverworldSim::tap(Direction direction){ advance_to(m_now + TAP_TIME); } -std::optional OverworldSim::facing_on_screen() const{ - if (m_state.screen != SimScreen::OVERWORLD){ - return std::nullopt; - } - return m_state.facing; -} - bool OverworldSim::drops_turn_tap(){ m_turn_taps++; if (m_script.dropped_turn_taps.contains(m_turn_taps)){ @@ -921,8 +914,8 @@ RouteCalls OverworldSimWalker::calls(){ void sim_turn_to(OverworldSim& sim, Direction direction, bool confirm){ for (size_t tap = 1; tap <= MAX_TURN_TAPS; tap++){ sim.tap(direction); - const std::optional facing = sim.facing_on_screen(); - if (!confirm || !facing || *facing == direction){ + const SimState& state = sim.state(); + if (!confirm || state.screen != SimScreen::OVERWORLD || state.facing == direction){ return; } } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index f2db259d5f..a349edbd64 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -214,10 +214,6 @@ class OverworldSim{ // already face that way. A turn may be dropped (SimScript::dropped_turn_taps). void tap(Direction direction); - // The way the player faces, as read_player_facing() reads it: on the - // overworld only. - std::optional facing_on_screen() const; - // Watches `watchers` for `duration`, as wait_until(). std::optional watch(const std::vector& watchers, Milliseconds duration); @@ -375,8 +371,8 @@ struct SimWalkerRules{ bool confirm_turn = true; }; -// OverworldWalkSteps::turn_to() on `sim`; with `confirm` false, the one -// tap before it. +// OverworldWalkSteps::turn_to() on `sim`, which reads the facing on the +// overworld only; with `confirm` false, the one tap before it. void sim_turn_to(OverworldSim& sim, Direction direction, bool confirm = SimWalkerRules{}.confirm_turn); // The console side of run_route() on an OverworldSim, as diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp index 43d3a16ad6..7b7fb39c46 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp @@ -486,27 +486,6 @@ UnitTestResult test_short_leg_unseen(){ return true; } -// Console B, 2026-11-09 (00.28 run 2): the game missed the turn tap before -// a one-tile open leg, the leg's hold only turned the player, and the leg -// was taken as walked. The walker now reads the facing after the tap and -// taps again; without that the player stays where they started. -UnitTestResult test_dropped_turn_tap(){ - SimCase c{.start = at("ViridianForest", 13, 28), .facing = Direction::NORTH, .goal = at("ViridianForest", 12, 28)}; - c.route = std::vector{leg(Direction::WEST, 1, c.goal, false)}; - c.script.dropped_turn_taps = {1}; - const SimRun now = run_case(c); - if (!arrived(now, c.goal) || now.state.turn_taps_dropped != 1){ - return "Expected the turn tapped again and the step walked:" + describe(now); - } - SimCase unchecked = c; - unchecked.rules.confirm_turn = false; - const SimRun old = run_case(unchecked); - if (!old.failure.empty() || !(old.state.position == c.start)){ - return "Expected the leg taken as walked from the start without the check:" + describe(old); - } - return true; -} - // r18 (console B, 2026-11-01), Pewter Gym: after Brock, Camper Liam sees // the player on the walk south to the door, walks up and battles. The // route holds on south to the door's mat; finding the player again at @@ -982,7 +961,6 @@ const OverworldSimCase OVERWORLD_SIM_CASES[] = { {.input = {"no hold over a ledge", test_no_hold_over_ledge}, .expectation = {},}, {.input = {"a short leg, then a sign", test_short_leg_then_sign}, .expectation = {},}, {.input = {"a short leg, nothing seen", test_short_leg_unseen}, .expectation = {},}, - {.input = {"a dropped turn tap before a one-tile leg", test_dropped_turn_tap}, .expectation = {},}, {.input = {"a trainer on the way out of Pewter Gym", test_trainer_on_way_out}, .expectation = {},}, {.input = {"out of Viridian Mart from the clerk's scene", test_mart_exit}, .expectation = {},}, {.input = {"Mt. Moon: down the ladders to B2F", test_mt_moon_ladders}, .expectation = {},}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp index 60568958df..10e79ccb20 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp @@ -6,9 +6,12 @@ #include #include +#include #include #include #include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_OverworldMaps.h" +#include "PokemonFRLG_OverworldSim.h" #include "PokemonFRLG_OverworldWalk.h" namespace PokemonAutomation{ @@ -116,6 +119,72 @@ const OverworldWalkTestCase OVERWORLD_WALK_CASES[] = { }, }; + +struct TurnTapInput{ + std::string name; + // SimScript::dropped_turn_taps. + std::set dropped_turn_taps; + // SimWalkerRules::confirm_turn. + bool confirm_turn = true; +}; + +struct TurnTapExpectation{ + // Where the leg ends. + MapPosition end; +}; + +struct TurnTapCase{ + TurnTapInput input; + TurnTapExpectation expectation; +}; + +const MapPosition TURN_START{"ViridianForest", {13, 28}}; +const MapPosition TURN_END{"ViridianForest", {12, 28}}; + +// Console B, 2026-11-09 (00.28 run 2): the game missed the turn tap before +// a one-tile open leg, the leg's hold only turned the player, and the leg +// was taken as walked. On the sim, a leg west 1 for a player facing north. +class Test_OverworldTurnTap : public UnitTest{ +public: + explicit Test_OverworldTurnTap(TurnTapCase test_case) + : UnitTest("PokemonFRLG::OverworldWalk - turn tap: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + static const std::vector MAPS = overworld_maps(); + RouteStep west; + west.direction = Direction::WEST; + west.tiles = 1; + west.facing_after = Direction::WEST; + west.end = TURN_END; + SimScript script; + script.dropped_turn_taps = m_case.input.dropped_turn_taps; + SimWalkerRules rules; + rules.confirm_turn = m_case.input.confirm_turn; + OverworldSim sim(MAPS, TURN_START, Direction::NORTH, script); + OverworldSimWalker walker(sim, rules); + const RoutePlanning planning{.maps = &MAPS, .costs = default_route_costs(), .start = TURN_START, .label = "Sim"}; + const std::string failure = walker.run({west}, planning); + if (failure.empty() && sim.state().position == m_case.expectation.end){ + return true; + } + return std::format( + "Expected the leg to end on {}; ended on {}, failure \"{}\".", + to_string(m_case.expectation.end), to_string(sim.state().position), failure + ); + } + +private: + TurnTapCase m_case; +}; + +const TurnTapCase TURN_TAP_CASES[] = { + {.input = {.name = "taken"}, .expectation = {.end = TURN_END}}, + {.input = {.name = "dropped, tapped again", .dropped_turn_taps = {1}}, .expectation = {.end = TURN_END}}, + {.input = {.name = "dropped twice, tapped again", .dropped_turn_taps = {1, 2}}, .expectation = {.end = TURN_END}}, + {.input = {.name = "dropped, not checked: the leg only turns", .dropped_turn_taps = {1}, .confirm_turn = false}, .expectation = {.end = TURN_START}}, +}; + } // namespace @@ -123,6 +192,9 @@ void add_tests_OverworldWalk(UnitTestDatabase& database){ for (const auto& scenario : OVERWORLD_WALK_CASES){ database.add(scenario); } + for (const TurnTapCase& item : TURN_TAP_CASES){ + database.add(item); + } } From 75c8c8532f2d01e2026ee3abf431060fa963955f Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 13:35:46 -0800 Subject: [PATCH 11/64] FRLG AutoStory: test that every resource it loads is in Resources A lab deployment without PokemonFRLG/PlayerSprites/red_normal.png failed 00.28 with a FileException; no test checked the files the readers load. autostory_resource_paths() lists the files AutoStory and its readers and detectors load, and the test fails naming each one missing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_AutoStoryLavender_Tests.cpp | 2 + .../PokemonFRLG_AutoStoryResources.cpp | 87 +++++++++++++++++++ .../PokemonFRLG_AutoStoryResources.h | 35 ++++++++ .../PokemonFRLG_AutoStoryResources_Tests.cpp | 78 +++++++++++++++++ SerialPrograms/cmake/SourceFiles.cmake | 3 + 5 files changed, 205 insertions(+) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources_Tests.cpp diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp index 4de9243862..49849c4edc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp @@ -26,6 +26,7 @@ #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" #include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryResources.h" #include "PokemonFRLG_AutoStoryRowSim.h" #include "PokemonFRLG_AutoStoryTable.h" #include "PokemonFRLG_AutoStoryTableSteps.h" @@ -487,6 +488,7 @@ void add_tests_AutoStoryLavender(UnitTestDatabase& database){ for (const auto& item : AUTO_STORY_LAVENDER_CASES){ database.add(item); } + add_tests_AutoStoryResources(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources.cpp new file mode 100644 index 0000000000..f0004cf491 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources.cpp @@ -0,0 +1,87 @@ +/* AutoStory Resources + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonFRLG_AutoStoryResources.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +const std::string_view PATHS[] = { + // Overworld/PokemonFRLG_PlayerFacingReader.cpp + "PokemonFRLG/PlayerSprites/red_normal.png", + + // Inference/PokemonFRLG_SelectionArrowDetector.cpp + "PokemonFRLG/SelectionArrow.png", + // Inference/PokemonFRLG_BattleSelectionArrowDetector.cpp + "PokemonFRLG/BattleSelectionArrow.png", + // Inference/PokemonFRLG_PokedexRegisteredDetector.cpp + "PokemonFRLG/PokedexButtonA.png", + // Inference/Menus/PokemonFRLG_PartyHeldItemDetector.cpp + "PokemonFRLG/PartyHeldItem.png", + // Inference/PokemonFRLG_StatsReader.cpp + "PokemonFRLG/NatureCheckerOCR.json", + + // Inference/Box/PokemonFRLG_BoxSelectionModeDetector.cpp + "PokemonFRLG/Box/SelectionHand_White.png", + "PokemonFRLG/Box/SelectionHand_White2.png", + "PokemonFRLG/Box/SelectionHand_White_Inverted.png", + "PokemonFRLG/Box/SelectionHand_Gold.png", + "PokemonFRLG/Box/SelectionHand_Gold2.png", + "PokemonFRLG/Box/SelectionHand_Gold_Inverted.png", + "PokemonFRLG/Box/SelectionHand_Closed_White.png", + "PokemonFRLG/Box/SelectionHand_Closed_Gold.png", + + // Inference/PokemonFRLG_DigitReader.cpp, digits 0 to 9 of each box. + "PokemonFRLG/Digits/0.png", "PokemonFRLG/Digits/1.png", "PokemonFRLG/Digits/2.png", + "PokemonFRLG/Digits/3.png", "PokemonFRLG/Digits/4.png", "PokemonFRLG/Digits/5.png", + "PokemonFRLG/Digits/6.png", "PokemonFRLG/Digits/7.png", "PokemonFRLG/Digits/8.png", + "PokemonFRLG/Digits/9.png", + "PokemonFRLG/LevelDigits/0.png", "PokemonFRLG/LevelDigits/1.png", "PokemonFRLG/LevelDigits/2.png", + "PokemonFRLG/LevelDigits/3.png", "PokemonFRLG/LevelDigits/4.png", "PokemonFRLG/LevelDigits/5.png", + "PokemonFRLG/LevelDigits/6.png", "PokemonFRLG/LevelDigits/7.png", "PokemonFRLG/LevelDigits/8.png", + "PokemonFRLG/LevelDigits/9.png", + "PokemonFRLG/DialogDigits/0.png", "PokemonFRLG/DialogDigits/1.png", "PokemonFRLG/DialogDigits/2.png", + "PokemonFRLG/DialogDigits/3.png", "PokemonFRLG/DialogDigits/4.png", "PokemonFRLG/DialogDigits/5.png", + "PokemonFRLG/DialogDigits/6.png", "PokemonFRLG/DialogDigits/7.png", "PokemonFRLG/DialogDigits/8.png", + "PokemonFRLG/DialogDigits/9.png", + + // Inference/Sounds/PokemonFRLG_ShinySoundDetector.cpp and + // PokemonFRLG_CatchFanfareDetector.cpp, one per sample rate. + "PokemonFRLG/ShinySound-44100.wav", + "PokemonFRLG/ShinySound-48000.wav", + "PokemonFRLG/CatchFanfare-44100.wav", + "PokemonFRLG/CatchFanfare-48000.wav", + + // Resources/PokemonFRLG_PokemonSprites.cpp + "PokemonFRLG/PokemonSprites.png", + "PokemonFRLG/PokemonSpritesFlipped.png", + "PokemonFRLG/PokemonSprites.json", + + // Programs/RngManipulation/PokemonFRLG_SeedsDatabase.cpp, for the + // story's RNG gifts. + "PokemonFRLG/RngSeeds/FR_Eng.json", + "PokemonFRLG/RngSeeds/FR_Jpn.json", + "PokemonFRLG/RngSeeds/LG_Eng.json", + "PokemonFRLG/RngSeeds/LG_Jpn.json", +}; + +} // namespace + + +const std::vector& autostory_resource_paths(){ + static const std::vector LIST(std::begin(PATHS), std::end(PATHS)); + return LIST; +} + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources.h new file mode 100644 index 0000000000..818fa41e34 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources.h @@ -0,0 +1,35 @@ +/* AutoStory Resources + * + * From: https://github.com/PokemonAutomation/ + * + * The files under the Resources folder that AutoStory, and the readers + * and detectors it calls, load while a program runs. A deployment whose + * Packages lack one of them stops mid-story with a FileException, so the + * test checks every one of them exists. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryResources_H +#define PokemonAutomation_PokemonFRLG_AutoStoryResources_H + +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Paths relative to RESOURCE_PATH(). When a reader or detector that +// AutoStory uses starts loading a new file, add it here. +const std::vector& autostory_resource_paths(); + +// Adds the test that every path above is under RESOURCE_PATH(). +void add_tests_AutoStoryResources(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources_Tests.cpp new file mode 100644 index 0000000000..e49c7efce9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources_Tests.cpp @@ -0,0 +1,78 @@ +/* AutoStory Resources Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Checks that every file in autostory_resource_paths() is in the + * Resources folder the program runs with. + * + */ + +#include +#include +#include +#include "Common/Cpp/Filesystem/Filesystem.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/GlobalAutoPaths.h" +#include "PokemonFRLG_AutoStoryResources.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +namespace{ + +struct ResourcesInput{ + const char* name; + const std::vector& (*paths)(); +}; +struct ResourcesExpectation{ + // The paths that may be missing; none, for a list a program loads. + size_t missing; +}; +struct ResourcesCase{ + ResourcesInput input; + ResourcesExpectation expectation; +}; + +class Test_AutoStoryResources : public UnitTest{ +public: + explicit Test_AutoStoryResources(ResourcesCase test_case) + : UnitTest(std::string("PokemonFRLG::AutoStoryResources - ") + test_case.input.name) + , m_case(test_case) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + std::string missing; + size_t count = 0; + for (std::string_view path : m_case.input.paths()){ + if (!Filesystem::exists(Filesystem::Path(RESOURCE_PATH() + std::string(path)))){ + missing += "\n " + std::string(path); + count++; + } + } + if (count == m_case.expectation.missing){ + return true; + } + return std::to_string(count) + " missing under " + RESOURCE_PATH() + ":" + missing; + } + +private: + ResourcesCase m_case; +}; + +const ResourcesCase RESOURCES_CASES[] = { + {.input = {"every file AutoStory loads is in Resources", autostory_resource_paths}, .expectation = {.missing = 0}}, +}; + +} // namespace + + +void add_tests_AutoStoryResources(UnitTestDatabase& database){ + for (const ResourcesCase& item : RESOURCES_CASES){ + database.add(item); + } +} + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 0b44daf242..9d8ef5b060 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1931,6 +1931,9 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPcStorage.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPcStorage.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPcStorage_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryResources_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp From 2134dbb2311e80ef0220c5c9194b9f2690d03fba Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 13:35:36 -0800 Subject: [PATCH 12/64] FRLG: movement mechanics table; sim taps as measured on the console Move the walker's pace, tap and release times into PokemonFRLG_MovementMechanics.h with the tap rules measured on console B (2026-11-09, Route 10 Center 1F): a tap from a standstill only turns a player facing another way and steps once for one facing its way, a step tap within 620 ms of the last one's start is ignored, and taps with no release between them are one hold. OverworldSim now moves its player by these rules; the random turn-tap drop is gone (dropped_turn_taps stays as fault injection for the turn check). Red: sim_step_once() still taps at the turn tap's pace (340 ms), so three step_once() lose a step under the lockout. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Overworld/PokemonFRLG_MovementMechanics.h | 88 ++++++++++++++++++ .../PokemonFRLG_OverworldRecoveryWalk.cpp | 1 + .../Overworld/PokemonFRLG_OverworldSim.cpp | 87 +++++++++++++++--- .../Overworld/PokemonFRLG_OverworldSim.h | 57 +++++++++--- .../Overworld/PokemonFRLG_OverworldWalk.cpp | 2 +- .../Overworld/PokemonFRLG_OverworldWalk.h | 21 +---- .../PokemonFRLG_OverworldWalk_Tests.cpp | 92 +++++++++++++++++++ .../PokemonFRLG_AutoStoryLavender_Tests.cpp | 28 ++---- .../PokemonFRLG_AutoStoryPaceSim.cpp | 5 +- .../AutoStory/PokemonFRLG_AutoStoryRowSim.cpp | 12 +-- .../PokemonFRLG_AutoStorySimulation_Tests.cpp | 5 +- SerialPrograms/cmake/SourceFiles.cmake | 1 + 12 files changed, 314 insertions(+), 85 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_MovementMechanics.h diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_MovementMechanics.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_MovementMechanics.h new file mode 100644 index 0000000000..f8d328d617 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_MovementMechanics.h @@ -0,0 +1,88 @@ +/* Movement Mechanics + * + * From: https://github.com/PokemonAutomation/ + * + * How FireRed and LeafGreen move the player for a press of the D-pad, as + * measured on the console, and the presses the walker sends because of + * it. The overworld walker (OverworldWalkSteps, AutoStory's step_once()) + * presses by this table, and OverworldSim moves its player by the same + * rules. + * + * Taps measured on console B (2026-11-09, Route 10's Pokemon Center 1F, + * D-pad presses with a 700ms release, tiles counted by exact frame match + * against reference shots), 140 of 140 alike: + * - From a standstill, a tap of 16 to 133ms while the player faces + * another way only turns them, never steps (pokefirered turns in 8 + * frames). + * - The same tap while they face its way takes exactly one step. + * - No tap was dropped. + * Repeated step taps (66ms each, after a turn tap and a 1000ms wait): + * - A step tap that starts within STEP_TAP_LOCKOUT of the previous step + * tap's start is ignored. + * - Taps with no release between them are one hold: after a turn, 3 of + * them took 0 or 1 steps. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_MovementMechanics_H +#define PokemonAutomation_PokemonFRLG_MovementMechanics_H + +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ +namespace MovementMechanics{ + + +// The game. + +// Walking: a tile per 16 frames at 60 fps (console B, 2026-11-09). +inline constexpr Milliseconds TILE_TIME(267); +// Running with B held: a tile per 8 frames (console B, 2026-11-02, video +// of run 00.11). +inline constexpr Milliseconds RUN_TILE_TIME(133); +// Surfing: a tile per 8 frames. +inline constexpr Milliseconds SURF_TILE_TIME(133); +// The longest tap measured to only turn a player facing another way, and +// to take exactly one step for one facing its way. +inline constexpr Milliseconds LONGEST_TAP(133); +// A step tap that starts sooner than this after the previous step tap +// started is ignored. Measured between 566ms (66ms taps 500ms apart: the +// 2nd of 3 ignored, 3 of 3 times) and 666ms (600 to 900ms apart: 8 of 8 +// worked). +inline constexpr Milliseconds STEP_TAP_LOCKOUT(620); +// The shortest step tap spacing, start to start, measured to work. +inline constexpr Milliseconds STEP_TAP_SPACING_WORKED(666); + + +// The walker's presses. + +// Turns a player facing another way, without a step. +inline constexpr Milliseconds TURN_TAP(40); +// How long to wait after a turn tap for the turn to show. +inline constexpr Milliseconds TURN_SETTLE(300); +// How many taps turn_to() tries before it takes the player as turned. +inline constexpr size_t MAX_TURN_TAPS = 3; +// Turns the player to face something, short enough not to step. +inline constexpr Milliseconds FACE_HOLD(40); +// The turn animation, before an A press reaches what is ahead. +inline constexpr Milliseconds FACE_SETTLE(300); +// The release between a leg's hold and what comes next. +inline constexpr Milliseconds STEP_RELEASE(100); +// A one-step tap (step_once()) and the release after it: the next step +// tap starts STEP_TAP + STEP_TAP_RELEASE after it, past the lockout. +inline constexpr Milliseconds STEP_TAP(66); +inline constexpr Milliseconds STEP_TAP_RELEASE(700); + +static_assert(TURN_TAP <= LONGEST_TAP && FACE_HOLD <= LONGEST_TAP && STEP_TAP <= LONGEST_TAP); +static_assert(STEP_TAP + STEP_TAP_RELEASE > STEP_TAP_SPACING_WORKED); +static_assert(STEP_TAP_SPACING_WORKED > STEP_TAP_LOCKOUT); + + +} // namespace MovementMechanics +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp index 8bf845563a..a2d26f6e2d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp @@ -25,6 +25,7 @@ namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonFRLG{ +using namespace MovementMechanics; using namespace OverworldWalkSteps; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index 3b92f27ef2..3ded120dcd 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -91,8 +91,6 @@ Pokemon::ScreenEventLog screen_event_log(const SimState& state, Milliseconds fro namespace{ -// A short press: TURN_TAP and TURN_SETTLE. -constexpr Milliseconds TAP_TIME(340); // The story's battle loop takes a battle that doesn't show in this long // for none. constexpr Milliseconds NO_BATTLE_WAIT(15000); @@ -145,7 +143,6 @@ OverworldSim::OverworldSim(std::vector maps, MapPosition start, Directi , m_script(std::move(script)) , m_map(find_map(m_maps, start.map)) , m_encounter_rng(m_script.encounter_seed) - , m_tap_rng(m_script.turn_tap_seed) { if (m_map < 0){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Sim: start on a map that isn't loaded: " + start.map); @@ -468,7 +465,13 @@ void OverworldSim::walk_hold(Direction direction, Milliseconds duration, int sho m_state.facing = direction; pressed += tile; } - int left = (int)((end - pressed + tile - 1ms) / tile) - short_by; + take_steps(direction, pressed, end, (int)((end - pressed + tile - 1ms) / tile) - short_by); +} + +// Up to `left` steps of a hold of `direction` until `end`, the first +// pressed at `pressed`. +void OverworldSim::take_steps(Direction direction, Milliseconds pressed, Milliseconds end, int left){ + const Milliseconds tile = m_script.timing.tile; for (; left > 0 && pressed < end; left--){ const std::optional step = press(direction); if (!step){ @@ -512,8 +515,13 @@ std::optional OverworldSim::hold( ){ const Milliseconds start = m_now; m_holds++; + m_last_tap.reset(); if (m_state.screen != SimScreen::OVERWORLD || m_frozen){ stuck_hold(direction); + }else if (duration <= MovementMechanics::LONGEST_TAP && m_state.facing == direction){ + // A hold as short as a tap is one (a one-tile leg). + step_tap(direction, duration); + m_last_tap.reset(); }else{ const auto short_hold = m_script.short_holds.find(m_holds); walk_hold(direction, duration, short_hold == m_script.short_holds.end() ? 0 : short_hold->second); @@ -521,10 +529,17 @@ std::optional OverworldSim::hold( return watch_until(watchers, start, start + std::max(duration + release, watch)); } -void OverworldSim::tap(Direction direction){ +void OverworldSim::tap(Direction direction, Milliseconds duration, Milliseconds release){ + const Milliseconds start = m_now; if (m_state.screen != SimScreen::OVERWORLD || m_frozen){ stuck_hold(direction); + m_last_tap.reset(); + }else if (m_last_tap && m_last_tap->direction == direction && m_last_tap->end == start){ + hold_on(direction, start + duration); }else if (m_state.facing != direction){ + // From a standstill a tap only turns the player, even one as long + // as LONGEST_TAP. + m_last_tap = TapPress{direction, start, start + duration, m_state.facing, 0}; if (drops_turn_tap()){ m_state.turn_taps_dropped++; note(std::string("the turn tap ") + direction_name(direction) + " is dropped."); @@ -532,20 +547,54 @@ void OverworldSim::tap(Direction direction){ m_state.facing = direction; } }else{ - walk_hold(direction, m_script.timing.tile / 2, 0); + step_tap(direction, duration); } - advance_to(m_now + TAP_TIME); + advance_to(start + duration + release); } -bool OverworldSim::drops_turn_tap(){ - m_turn_taps++; - if (m_script.dropped_turn_taps.contains(m_turn_taps)){ - return true; +// A tap of `direction` by a player facing that way: one step, unless it +// starts inside the lockout after the last step tap. +void OverworldSim::step_tap(Direction direction, Milliseconds duration){ + const Milliseconds start = m_now; + m_last_tap = TapPress{direction, start, start + duration, direction, 0}; + if (m_last_step_tap && start < *m_last_step_tap + MovementMechanics::STEP_TAP_LOCKOUT){ + m_state.step_taps_ignored++; + note(std::format( + "the step tap {} is ignored, {} ms after the last.", + direction_name(direction), (start - *m_last_step_tap).count() + )); + return; } - if (m_script.turn_tap_drop_rate <= 0){ - return false; + const int before = m_state.steps; + walk_hold(direction, duration, 0); + m_last_tap->steps = m_state.steps - before; + if (m_last_tap->steps > 0){ + m_last_step_tap = start; } - return std::uniform_real_distribution(0, 1)(m_tap_rng) < m_script.turn_tap_drop_rate; +} + +// A tap of the last tap's way with no release before it: the two are one +// hold, from the last one's start until `end`. +void OverworldSim::hold_on(Direction direction, Milliseconds end){ + TapPress& press = *m_last_tap; + const Milliseconds tile = m_script.timing.tile; + Milliseconds pressed = press.start; + if (press.facing_before != direction){ + pressed += tile; + } + m_state.facing = direction; + const int steps = (int)((end - pressed + tile - 1ms) / tile); + if (steps > press.steps){ + const int before = m_state.steps; + take_steps(direction, pressed + tile * press.steps, end, steps - press.steps); + press.steps += m_state.steps - before; + } + press.end = end; +} + +bool OverworldSim::drops_turn_tap(){ + m_turn_taps++; + return m_script.dropped_turn_taps.contains(m_turn_taps); } std::optional OverworldSim::watch(const std::vector& watchers, Milliseconds duration){ @@ -627,6 +676,7 @@ bool OverworldSim::cut_tree(){ namespace{ +using namespace MovementMechanics; using namespace OverworldWalkSteps; // As the console's watch for a trainer (PokemonFRLG_OverworldRecoveryWalk.cpp). @@ -896,7 +946,7 @@ StepEnd OverworldSimWalker::watch_for_trainer(const RouteStep& step, int approac bool OverworldSimWalker::moved_past_wall(const RouteStep& step){ const MapPosition before = m_sim.state().position; - m_sim.tap(step.direction); + m_sim.tap(step.direction, TURN_TAP, TILE_TIME + TURN_SETTLE); return !(m_sim.state().position == before); } @@ -921,6 +971,13 @@ void sim_turn_to(OverworldSim& sim, Direction direction, bool confirm){ } } +void sim_step_once(OverworldSim& sim, Direction direction){ + if (sim.state().facing != direction){ + sim_turn_to(sim, direction); + } + sim.tap(direction); +} + std::string OverworldSimWalker::run(const std::vector& route, const RoutePlanning& planning){ try{ run_route(route, m_sim.state().facing, &planning, calls()); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index a349edbd64..2b3e1df6fb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -38,6 +38,7 @@ #include "Common/Cpp/Time.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" +#include "PokemonFRLG_MovementMechanics.h" #include "PokemonFRLG_OverworldRecovery.h" #include "PokemonFRLG_OverworldRoute.h" #include "PokemonFRLG_OverworldWalk.h" @@ -84,7 +85,7 @@ struct SimEncounter{ // detection delays (OverworldInterrupt::detection_delay()) are its guesses // at these. struct SimTiming{ - Milliseconds tile{267}; + Milliseconds tile = MovementMechanics::TILE_TIME; Milliseconds flash{300}; Milliseconds battle_screen{3700}; // A wild battle's text box, before the HP boxes (battle_screen). Not @@ -121,14 +122,13 @@ struct SimScript{ // src/data/wild_encounters.json), rolled from `encounter_seed`. std::map encounter_rates; uint32_t encounter_seed = 0; - // Turn taps (taps while the player faces another way) the game misses: - // the player goes on facing the old way. By number, from 1, and each - // with probability `turn_tap_drop_rate`, rolled from `turn_tap_seed`. - // After one, a hold of a tile only turns the player (console B, - // 2026-11-09, 00.28 run 2). + // Fault injection: turn taps (taps while the player faces another way) + // the game misses, by number from 1; the player goes on facing the old + // way. The game drops none from a standstill (MovementMechanics: 70 of + // 70 turned); these test the walker's check of the turn + // (SimWalkerRules::confirm_turn) after 00.28 run 2 (console B, + // 2026-11-09), where a one-tile leg only turned the player. std::set dropped_turn_taps; - double turn_tap_drop_rate = 0; - uint32_t turn_tap_seed = 0; SimTiming timing; }; @@ -157,6 +157,9 @@ struct SimState{ Milliseconds in_wild_battles{0}; int signs_read = 0; int turn_taps_dropped = 0; + // Step taps the game ignored, inside the lockout after the last one + // (MovementMechanics::STEP_TAP_LOCKOUT). + int step_taps_ignored = 0; std::vector trainers_beaten; // Things the walker did that the game wouldn't let pass: D-pad holds // under a battle, a trainer's battle fled, a battle fought that wasn't @@ -210,9 +213,18 @@ class OverworldSim{ const std::vector& watchers ); - // A short press of `direction`: turns the player, or steps if they - // already face that way. A turn may be dropped (SimScript::dropped_turn_taps). - void tap(Direction direction); + // A press of `direction` for `duration` (at most MovementMechanics:: + // LONGEST_TAP), then `release`, as the console measured it: a player + // facing another way only turns; one facing that way steps once, + // unless the tap starts inside the lockout after the last step tap + // (STEP_TAP_LOCKOUT), which the game ignores. A tap that starts as + // the last one ends, with no release between, holds it on. A turn may + // be dropped by fault injection (SimScript::dropped_turn_taps). + void tap( + Direction direction, + Milliseconds duration = MovementMechanics::TURN_TAP, + Milliseconds release = MovementMechanics::TURN_SETTLE + ); // Watches `watchers` for `duration`, as wait_until(). std::optional watch(const std::vector& watchers, Milliseconds duration); @@ -253,7 +265,19 @@ class OverworldSim{ bool sees(SimWatcher watcher, SimScreen screen) const; std::optional first_seen(SimWatcher watcher, Milliseconds from, Milliseconds to) const; std::optional watch_until(const std::vector& watchers, Milliseconds from, Milliseconds to); + // A tap, for the next one's lockout and to hold on: when it started + // and ended, the player's facing before it and the steps it took. + struct TapPress{ + Direction direction = Direction::NORTH; + Milliseconds start{0}; + Milliseconds end{0}; + Direction facing_before = Direction::NORTH; + int steps = 0; + }; void walk_hold(Direction direction, Milliseconds duration, int short_by); + void take_steps(Direction direction, Milliseconds pressed, Milliseconds end, int left); + void step_tap(Direction direction, Milliseconds duration); + void hold_on(Direction direction, Milliseconds end); void stuck_hold(Direction direction); void bump(Direction direction, Milliseconds pressed); std::optional press(Direction direction) const; @@ -292,9 +316,12 @@ class OverworldSim{ std::mt19937 m_encounter_rng; int m_steps_since_encounter = 0; int m_encounter_rate_buff = 0; - // The turn taps so far, and what rolls their drops. + // The turn taps so far, for SimScript::dropped_turn_taps. int m_turn_taps = 0; - std::mt19937 m_tap_rng; + // The last tap, until a hold. + std::optional m_last_tap; + // When the last tap that stepped started. + std::optional m_last_step_tap; Milliseconds m_wild_battle_from{0}; int m_holds = 0; SimState m_state; @@ -375,6 +402,10 @@ struct SimWalkerRules{ // overworld only; with `confirm` false, the one tap before it. void sim_turn_to(OverworldSim& sim, Direction direction, bool confirm = SimWalkerRules{}.confirm_turn); +// AutoStory's step_once() on `sim`: turns the player if they face another +// way, then one step tap. +void sim_step_once(OverworldSim& sim, Direction direction); + // The console side of run_route() on an OverworldSim, as // walk_overworld_route_with_recovery() does it, with the story's // interrupts: a wild battle (flashes, or seen late) is fought or run from, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp index 008e7089cc..04bc3de098 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp @@ -26,12 +26,12 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ using namespace std::chrono_literals; +using namespace MovementMechanics; using namespace OverworldWalkSteps; namespace{ -constexpr Milliseconds FACE_SETTLE = 300ms; // the turn animation, before A reaches what is ahead // From the end of the hold, through the fade out and in. constexpr Milliseconds WARP_TIMEOUT = 8000ms; constexpr Milliseconds SURF_PROMPT_TIMEOUT = 5000ms; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h index 8325dac772..a81e1a9eda 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h @@ -27,6 +27,7 @@ #include "Pokemon/Navigation/Pokemon_LegWalker.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" #include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonFRLG_MovementMechanics.h" #include "PokemonFRLG_OverworldRoute.h" namespace PokemonAutomation{ @@ -99,23 +100,9 @@ void walk_overworld_route( // walk_overworld_route() describes. namespace OverworldWalkSteps{ -// Walking duration for a single tile (16 frames at 60 fps). -inline constexpr Milliseconds TILE_TIME(267); -// Surfing duration for a single tile. -inline constexpr Milliseconds SURF_TILE_TIME(133); -// 8 frames: running is 2 pixels a frame, twice walking. Not measured on the -// console yet; the walker logs each leg to a wall (speed_note()) for that. -inline constexpr Milliseconds RUN_TILE_TIME(133); -// turns a player facing another way, without a step. -inline constexpr Milliseconds TURN_TAP(40); -// duration to wait after turning to allow state to settle. -inline constexpr Milliseconds TURN_SETTLE(300); -// How many taps turn_to() tries before it takes the player as turned. -inline constexpr size_t MAX_TURN_TAPS = 3; -// short enough to turn without stepping. -inline constexpr Milliseconds FACE_HOLD(40); -// duration of button release between movement steps. -inline constexpr Milliseconds STEP_RELEASE(100); +// The pace, tap and release times are the game's movement mechanics +// (PokemonFRLG_MovementMechanics.h). + // After a warp's fade: leaving by a door the game walks the player a tile out // on its own, and a leg started before that ends loses tiles (on the console a // 600ms wait cost 2 tiles). diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp index 10e79ccb20..24b97896f0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp @@ -18,6 +18,7 @@ namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonFRLG{ +using namespace MovementMechanics; using namespace OverworldWalkSteps; @@ -185,6 +186,94 @@ const TurnTapCase TURN_TAP_CASES[] = { {.input = {.name = "dropped, not checked: the leg only turns", .dropped_turn_taps = {1}, .confirm_turn = false}, .expectation = {.end = TURN_START}}, }; + +struct TapMechanicsInput{ + std::string name; + // The player's facing at the start. + Direction facing = Direction::NORTH; + // The presses, on the sim. + std::function presses; +}; + +struct TapMechanicsExpectation{ + // Tiles stepped east. + int steps = 0; + Direction facing = Direction::EAST; + // Step taps the game ignored. + int ignored = 0; +}; + +struct TapMechanicsCase{ + TapMechanicsInput input; + TapMechanicsExpectation expectation; +}; + +// Open floor east of the start: where the taps were measured (console B, +// 2026-11-09, MovementMechanics). +const MapPosition TAP_START{"Route10_PokemonCenter_1F", {3, 4}}; + +// The sim's taps east, as the console moved the player for them. +class Test_OverworldTapMechanics : public UnitTest{ +public: + explicit Test_OverworldTapMechanics(TapMechanicsCase test_case) + : UnitTest("PokemonFRLG::OverworldWalk - tap: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + static const std::vector MAPS = overworld_maps(); + OverworldSim sim(MAPS, TAP_START, m_case.input.facing); + m_case.input.presses(sim); + const SimState& state = sim.state(); + const TapMechanicsExpectation& expected = m_case.expectation; + const MapPosition end{TAP_START.map, {TAP_START.point.x + expected.steps, TAP_START.point.y}}; + if (state.position == end && state.facing == expected.facing && state.step_taps_ignored == expected.ignored){ + return true; + } + return std::format( + "Expected {} step(s) east to {} facing {}, {} tap(s) ignored; on {} facing {}, {} ignored.", + expected.steps, to_string(end), Pokemon::direction_name(expected.facing), expected.ignored, + to_string(state.position), Pokemon::direction_name(state.facing), state.step_taps_ignored + ); + } + +private: + TapMechanicsCase m_case; +}; + +// `count` taps east of `duration`, each released for `release`. +std::function taps_east(int count, Milliseconds duration, Milliseconds release){ + return [=](OverworldSim& sim){ + for (int c = 0; c < count; c++){ + sim.tap(Direction::EAST, duration, release); + } + }; +} + +// A turn tap east and a 1000ms wait, then `count` taps east of 66ms, +// each released for `release`. +std::function turn_then_taps(int count, Milliseconds release){ + return [=](OverworldSim& sim){ + sim.tap(Direction::EAST, TURN_TAP, Milliseconds(1000)); + taps_east(count, Milliseconds(66), release)(sim); + }; +} + +const TapMechanicsCase TAP_MECHANICS_CASES[] = { + {.input = {.name = "133ms facing another way only turns", .presses = taps_east(1, LONGEST_TAP, Milliseconds(700))}, .expectation = {}}, + {.input = {.name = "16ms facing that way steps once", .facing = Direction::EAST, .presses = taps_east(1, Milliseconds(16), Milliseconds(700))}, .expectation = {.steps = 1}}, + {.input = {.name = "3 step taps 566ms apart take 2 steps", .presses = turn_then_taps(3, Milliseconds(500))}, .expectation = {.steps = 2, .ignored = 1}}, + {.input = {.name = "3 step taps 666ms apart take 3 steps", .presses = turn_then_taps(3, Milliseconds(600))}, .expectation = {.steps = 3}}, + {.input = {.name = "3 step taps with no release are one hold", .presses = turn_then_taps(3, Milliseconds(0))}, .expectation = {.steps = 1}}, + { + .input = {.name = "step_once 3 times takes 3 steps", .presses = [](OverworldSim& sim){ + for (int c = 0; c < 3; c++){ + sim_step_once(sim, Direction::EAST); + } + }}, + .expectation = {.steps = 3}, + }, +}; + } // namespace @@ -195,6 +284,9 @@ void add_tests_OverworldWalk(UnitTestDatabase& database){ for (const TurnTapCase& item : TURN_TAP_CASES){ database.add(item); } + for (const TapMechanicsCase& item : TAP_MECHANICS_CASES){ + database.add(item); + } } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp index 49849c4edc..e201a86da0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp @@ -342,39 +342,33 @@ const std::map ROCK_TUNNEL_ENCOUNTER_RATES{ }; constexpr unsigned GAME_ODDS_SEEDS = 30; -// The share of turn taps the sim drops (SimScript::turn_tap_drop_rate): -// a guess well above what the console showed, one in 00.28 run 2. -constexpr double TURN_TAP_DROP_RATE = 0.1; // 00.28 whole, its wild battles at the game's own odds (OverworldSim:: -// rolls_encounter()) and `turn_tap_drop_rate` of its turn taps dropped, -// from each of these seeds: every run ends where it should. Logs the -// runs' numbers. -UnitTestResult rock_tunnel_game_odds(Logger& logger, double turn_tap_drop_rate){ +// rolls_encounter()), from each of these seeds: every run ends where it +// should. Logs the runs' numbers and the step taps the game ignored. +UnitTestResult test_rock_tunnel_game_odds(Logger& logger){ OverworldSim clean_sim = row_start_sim("00.28", SimScript{}); if (const UnitTestResult clean = row_checked(clean_sim, "00.28", {ROCK_TUNNEL_TRAINERS}, MapPosition{StoryTable::ROUTE10, {8, 58}}); clean.result != UnitTestResult::PASSED){ return clean; } std::vector runs; std::string failures; - int dropped = 0; + int ignored = 0; for (unsigned seed = 1; seed <= GAME_ODDS_SEEDS; seed++){ SimScript script; script.encounter_rates = ROCK_TUNNEL_ENCOUNTER_RATES; script.encounter_seed = seed; - script.turn_tap_drop_rate = turn_tap_drop_rate; - script.turn_tap_seed = seed; OverworldSim sim = row_start_sim("00.28", script); const UnitTestResult result = row_checked(sim, "00.28", {ROCK_TUNNEL_TRAINERS}, MapPosition{StoryTable::ROUTE10, {8, 58}}); const bool passed = result.result == UnitTestResult::PASSED; runs.push_back(row_numbers(sim.state(), passed, clean_sim.state())); - dropped += sim.state().turn_taps_dropped; + ignored += sim.state().step_taps_ignored; if (!passed){ failures += std::format("{}Seed {}: {}", failures.empty() ? "" : " | ", seed, result.message); } } logger.log(std::format( - "00.28 at the game's encounter odds, {} turn taps dropped: {}", dropped, numbers_summary(runs) + "00.28 at the game's encounter odds, {} step taps ignored: {}", ignored, numbers_summary(runs) )); if (!failures.empty()){ return failures; @@ -382,15 +376,6 @@ UnitTestResult rock_tunnel_game_odds(Logger& logger, double turn_tap_drop_rate){ return true; } -UnitTestResult test_rock_tunnel_game_odds(Logger& logger){ - return rock_tunnel_game_odds(logger, 0); -} - -// The same with one turn tap in TURN_TAP_DROP_RATE dropped by the game -// (console B, 2026-11-09, 00.28 run 2). -UnitTestResult test_rock_tunnel_dropped_turn_taps(Logger& logger){ - return rock_tunnel_game_odds(logger, TURN_TAP_DROP_RATE); -} // 00.29 on the sim: no trainer met, the ledge hopped, Lavender's nurse. UnitTestResult test_lavender_row(Logger&){ @@ -477,7 +462,6 @@ const AutoStoryLavenderCase AUTO_STORY_LAVENDER_CASES[] = { {.input = {"00.28 B1F row 37 with a wild battle every 10 to 14 steps", test_b1f_row37_battles_every_12}, .expectation = {}}, {.input = {"00.28 a wild battle every 7 to 25 steps, 12 seeds", test_rock_tunnel_frequent_battles}, .expectation = {}}, {.input = {"00.28 wild battles at the game's odds, 30 seeds", test_rock_tunnel_game_odds}, .expectation = {}}, - {.input = {"00.28 wild battles at the game's odds and 1 in 10 turn taps dropped, 30 seeds", test_rock_tunnel_dropped_turn_taps}, .expectation = {}}, {.input = {"00.28 B1F a wild battle into row 38, then a step short: Martha still sees the player", test_b1f_martha_after_row38_battle}, .expectation = {}}, {.input = {"00.29 Route 10 south, the ledge, Lavender Town's Pokemon Center", test_lavender_row}, .expectation = {}}, {.input = {"00.29 a tile off after each open leg", test_lavender_tile_off}, .expectation = {}}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPaceSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPaceSim.cpp index 46a8fe1ea7..6e16d20bc2 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPaceSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPaceSim.cpp @@ -24,10 +24,7 @@ SimPatch::SimPatch(OverworldSim& sim, Direction pace, Direction back, std::funct bool SimPatch::step(){ const Direction way = m_displaced ? m_back : m_pace; - if (m_sim.state().facing != way){ - sim_turn_to(m_sim, way); - } - m_sim.tap(way); + sim_step_once(m_sim, way); m_displaced = !m_displaced; return m_sim.watch({SimWatcher::FLASH}, std::chrono::milliseconds(1000)).has_value(); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp index e54680468e..a739d0b9e4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp @@ -400,10 +400,7 @@ std::string OverworldStepSim::step_ahead(const StoryStep& step){ return step_onto(step); } const auto tap = [this, &step]{ - if (m_sim.state().facing != step.direction){ - sim_turn_to(m_sim, step.direction); - } - m_sim.tap(step.direction); + sim_step_once(m_sim, step.direction); }; // A wild battle, with no message before it, is run from, and the // stepping goes on, as step_into_line() does. @@ -423,10 +420,7 @@ std::string OverworldStepSim::step_ahead(const StoryStep& step){ // A hop() or step_onto(): one step, ending where the table says. std::string OverworldStepSim::step_onto(const StoryStep& step){ - if (m_sim.state().facing != step.direction){ - sim_turn_to(m_sim, step.direction); - } - m_sim.tap(step.direction); + sim_step_once(m_sim, step.direction); m_at = *story_pose(*step.pose_after); return m_sim.state().position == MapPosition{m_at.map, m_at.tile} ? "" : "expected to end on " + to_string(MapPosition{m_at.map, m_at.tile}) + "."; } @@ -440,7 +434,7 @@ std::string OverworldStepSim::cut(const StoryStep& step){ if (!m_sim.cut_tree()){ return "no tree to cut."; } - m_sim.tap(step.direction); + sim_step_once(m_sim, step.direction); m_at = StoryPose{m_at.map, m_at.tile.next(step.direction), step.direction}; if (!(m_sim.state().position == MapPosition{m_at.map, m_at.tile})){ return "expected to step onto the tree's tile " + to_string(MapPosition{m_at.map, m_at.tile}) + "."; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp index 6685da4ef9..a874f2e22b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp @@ -349,10 +349,7 @@ std::string walk_on_sim(OverworldSim& sim, StoryPose& at, const StoryStep& step) open_end = last.action == RouteAction::WALK && !last.to_wall && !last.warps; at = StoryPose{last.end.map, last.end.point, last.facing_after}; }else if (step.kind == StoryStepKind::STEP){ - if (sim.state().facing != step.direction){ - sim.tap(step.direction); - } - sim.tap(step.direction); + sim_step_once(sim, step.direction); sim.watch({SimWatcher::MESSAGE}, std::chrono::milliseconds(2000)); at = *story_pose(*step.pose_after); } diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 9d8ef5b060..10cb4b5792 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1846,6 +1846,7 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Inference/Sounds/PokemonFRLG_CatchFanfareDetector.h Source/VideoGames/PokemonFRLG/Inference/Sounds/PokemonFRLG_ShinySoundDetector.cpp Source/VideoGames/PokemonFRLG/Inference/Sounds/PokemonFRLG_ShinySoundDetector.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_MovementMechanics.h Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldLateBattle.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldLateBattle.h Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldLateBattle_Tests.cpp From 2bd587495a9012869842c4e690844b61d4ba2a97 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 13:37:00 -0800 Subject: [PATCH 13/64] FRLG: space step taps past the lockout step_once() tapped 120 ms and released 500 ms, 620 ms from tap to tap: inside the band where the console's lockout ends (a step tap 566 ms after the last is ignored, 666 ms works). It now taps STEP_TAP (66 ms) and releases STEP_TAP_RELEASE (700 ms), 766 ms apart, and sim_step_once() does the same. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp | 2 +- .../Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index 3ded120dcd..be87d3f162 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -975,7 +975,7 @@ void sim_step_once(OverworldSim& sim, Direction direction){ if (sim.state().facing != direction){ sim_turn_to(sim, direction); } - sim.tap(direction); + sim.tap(direction, STEP_TAP, STEP_TAP_RELEASE); } std::string OverworldSimWalker::run(const std::vector& route, const RoutePlanning& planning){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp index e009d01701..72386fb022 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp @@ -582,8 +582,9 @@ void step_once(ConsoleHandle& console, ProControllerContext& context, Direction if (facing != direction){ OverworldWalkSteps::turn_to(console, context, direction); } - // A step, once started, finishes on its own. - pbf_press_dpad(context, dpad(direction), 120ms, 500ms); + // A step, once started, finishes on its own. The release waits out the + // lockout before a next step tap (MovementMechanics::STEP_TAP_LOCKOUT). + pbf_press_dpad(context, dpad(direction), MovementMechanics::STEP_TAP, MovementMechanics::STEP_TAP_RELEASE); context.wait_for_all_requests(); } From 91b9ff706f602e45be63336f44f3f9367093ddf0 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 13:37:53 -0800 Subject: [PATCH 14/64] FRLG: code health for the movement table and tap tests Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Overworld/PokemonFRLG_MovementMechanics.h | 5 +++-- .../PokemonFRLG_OverworldWalk_Tests.cpp | 18 ++++++++++-------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_MovementMechanics.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_MovementMechanics.h index f8d328d617..9fc6df8df6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_MovementMechanics.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_MovementMechanics.h @@ -71,9 +71,10 @@ inline constexpr Milliseconds FACE_HOLD(40); inline constexpr Milliseconds FACE_SETTLE(300); // The release between a leg's hold and what comes next. inline constexpr Milliseconds STEP_RELEASE(100); -// A one-step tap (step_once()) and the release after it: the next step -// tap starts STEP_TAP + STEP_TAP_RELEASE after it, past the lockout. +// A one-step tap (step_once()). inline constexpr Milliseconds STEP_TAP(66); +// The release after a step tap: the next one starts STEP_TAP + +// STEP_TAP_RELEASE after it, past the lockout. inline constexpr Milliseconds STEP_TAP_RELEASE(700); static_assert(TURN_TAP <= LONGEST_TAP && FACE_HOLD <= LONGEST_TAP && STEP_TAP <= LONGEST_TAP); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp index 24b97896f0..a488f376ae 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp @@ -258,20 +258,22 @@ std::function turn_then_taps(int count, Milliseconds releas }; } +// AutoStory's step_once() east `count` times. +std::function step_once_east(int count){ + return [=](OverworldSim& sim){ + for (int c = 0; c < count; c++){ + sim_step_once(sim, Direction::EAST); + } + }; +} + const TapMechanicsCase TAP_MECHANICS_CASES[] = { {.input = {.name = "133ms facing another way only turns", .presses = taps_east(1, LONGEST_TAP, Milliseconds(700))}, .expectation = {}}, {.input = {.name = "16ms facing that way steps once", .facing = Direction::EAST, .presses = taps_east(1, Milliseconds(16), Milliseconds(700))}, .expectation = {.steps = 1}}, {.input = {.name = "3 step taps 566ms apart take 2 steps", .presses = turn_then_taps(3, Milliseconds(500))}, .expectation = {.steps = 2, .ignored = 1}}, {.input = {.name = "3 step taps 666ms apart take 3 steps", .presses = turn_then_taps(3, Milliseconds(600))}, .expectation = {.steps = 3}}, {.input = {.name = "3 step taps with no release are one hold", .presses = turn_then_taps(3, Milliseconds(0))}, .expectation = {.steps = 1}}, - { - .input = {.name = "step_once 3 times takes 3 steps", .presses = [](OverworldSim& sim){ - for (int c = 0; c < 3; c++){ - sim_step_once(sim, Direction::EAST); - } - }}, - .expectation = {.steps = 3}, - }, + {.input = {.name = "step_once 3 times takes 3 steps", .presses = step_once_east(3)}, .expectation = {.steps = 3}}, }; } // namespace From 853a6b5af3f727b836ad8315f431143d65ea0673 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 14:01:36 -0800 Subject: [PATCH 15/64] FRLG AutoStory sim: sweep scene end poses, wild battles and late fades over every row Each row with a start runs on the overworld sim clean, then with the classes of failure console B showed injected everywhere they can happen: a scene that moved the player ending on each open tile next to the table's pose; wild battles at pokefirered's land encounter rates on every map the story walks, 30 seeds, logging passed, time, tiles walked again and time lost per battle; and every warp's fade 1.5 s late. Steps the sim does not play put the player on their pose_after; scene triggers and leaders' battles it has no script for pass where the clean run let them. 00.06 is known failing: two seeds give up on Route 1 after 9 stops. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_AutoStoryFaultSweep_Tests.cpp | 433 ++++++++++++++++++ .../PokemonFRLG_AutoStoryFaultSweep_Tests.h | 26 ++ .../PokemonFRLG_AutoStoryLavender_Tests.cpp | 2 + SerialPrograms/cmake/SourceFiles.cmake | 2 + 4 files changed, 463 insertions(+) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.h diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.cpp new file mode 100644 index 0000000000..12ac3a535b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.cpp @@ -0,0 +1,433 @@ +/* AutoStory Fault Sweep Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Each class of failure console B showed, injected at every row of the + * story on the overworld sim, instead of only where it was seen: + * + * - SCENE_END_POSE: a step the sim does not play (a scene, a talk, an + * event) that moved the player leaves them on another walkable tile + * within one of the table's pose, while the program goes on from the + * table's (BDSP 00.03, lab-B 2026-11-09). + * - WILD_BATTLES: wild battles at the game's own odds on every map with + * land encounters, over GAME_ODDS_SEEDS seeds (00.28's Rock Tunnel). + * - LATE_FADE: every warp's fade ends LATE_FADE later than the sim's + * usual (00.27's warp to Cerulean City). + * + * Not swept here: a missed fade, which needs a knob in OverworldSim; a + * battle's opening at a step's start, which needs one in OverworldStepSim; + * and lost taps from the input lockout (FaultClass::LOST_TAP), for the + * measured movement table. + * + * The sim plays walks, steps, cuts and trainers' battles; after a step it + * does not play, the player is put on the table's pose. Each row runs + * clean first; a row that fails clean, or has no start, is not swept. A + * variant fails when the row then fails or ends elsewhere. A sweep the + * program fails today is on KNOWN_FAILING with its likely fix: its test + * passes while it still fails, and fails once it passes. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryRowSim.h" +#include "PokemonFRLG_AutoStoryTable.h" +#include "PokemonFRLG_AutoStoryFaultSweep_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +using namespace std::chrono_literals; + +enum class FaultClass{ + SCENE_END_POSE, + WILD_BATTLES, + LATE_FADE, + // Not swept yet: the measured movement table's lost taps. + LOST_TAP, +}; +const char* fault_class_name(FaultClass fault){ + switch (fault){ + case FaultClass::SCENE_END_POSE: + return "scene end pose"; + case FaultClass::WILD_BATTLES: + return "wild battles at the game's odds"; + case FaultClass::LATE_FADE: + return "late warp fade"; + case FaultClass::LOST_TAP: + return "lost tap"; + } + return "?"; +} + +// Sweeps the program fails today, by test name, with the likely fix. +const std::map KNOWN_FAILING{ + {"PokemonFRLG::AutoStory - Fault sweep: 00.06, wild battles at the game's odds", + "below_oak on Route 1 gives up after 9 stops part-way (seeds 16, 30): count stops that make no progress, not every battle"}, +}; + +// The land encounter rates of the maps the story walks (pokefirered +// src/data/wild_encounters.json, FireRed). Mt. Moon's floor is wild +// on every tile (WILD_FLOOR_MAPS). +const std::map STORY_ENCOUNTER_RATES{ + {"Route1", 21}, {"Route2", 21}, {"Route3", 21}, {"Route4", 21}, {"Route5", 21}, {"Route6", 21}, + {"Route9", 21}, {"Route10", 21}, {"Route11", 21}, {"Route22", 21}, {"Route24", 21}, {"Route25", 21}, + {"ViridianForest", 14}, {"MtMoon_1F", 7}, {"MtMoon_B1F", 5}, {"MtMoon_B2F", 7}, + {"RockTunnel_1F", 7}, {"RockTunnel_B1F", 7}, +}; +// Caves wild on every floor tile, also where the maps mark no wild tiles +// (Mt. Moon B2F, console B, 2026-11-03). +const std::set WILD_FLOOR_MAPS{"MtMoon_1F", "MtMoon_B1F", "MtMoon_B2F"}; +constexpr unsigned GAME_ODDS_SEEDS = 30; +// How much later than SimTiming's a late fade ends: the new map shows +// this long after the usual. +constexpr Milliseconds LATE_FADE = 1500ms; + +// The maps as the story after the Hall of Fame and a new game flag them: +// the same set for every row, as each stage's tests use. +const std::vector& sweep_maps(){ + static const std::vector maps = []{ + const std::vector all = overworld_maps(); + std::set flags = map_flag_set(all, "after_hall_of_fame"); + flags.merge(map_flag_set(all, "new_game")); + return overworld_maps(flags); + }(); + return maps; +} + +// Whether the overworld sim plays `step` (OverworldStepSim): the rest is stubbed. +bool sim_plays(const StoryStep& step){ + switch (step.kind){ + case StoryStepKind::ROUTE: + case StoryStepKind::LEGS: + case StoryStepKind::STEP: + case StoryStepKind::BATTLE: + return true; + case StoryStepKind::GAME: + return step.variant == CUT_TREE_VARIANT; + default: + return false; + } +} + +// A row run on the sim. +struct RowRun{ + // The first failure, "" if none. + std::string failure; + // The steps whose failure was let pass, by index (run_row()). + std::set scripted; + // Where the player stood before each step, by index. + std::map before; + MapPosition end; + Milliseconds time{0}; + int steps = 0; + int wild_battles = 0; + Milliseconds in_wild_battles{0}; +}; + +// Where a stubbed step leaves the player instead of its pose_after: by step index. +using Landings = std::map; + +// Whether `failure` is a script the sim does not have: a scene's trigger +// stepped onto (no trainer sees the player there) or a leader's battle +// after a talk (no trainer's message up). +bool unscripted(const std::string& failure){ + return failure.find(": no trainer saw the player.") != std::string::npos + || failure.find(": no_battle.") != std::string::npos; +} + +// Row `row` on the sim with `script`, from its start. After a step the sim +// does not play, the player is put on its pose_after, or on `landings`' +// tile for it, the program going on from the pose_after either way. A +// step that fails as unscripted() is let pass as one the sim does not +// play: in a clean run (`scripted` unset) at any step, else only at the +// steps in `scripted`, where the clean run let it pass. +RowRun run_row( + const StoryCheckpoint& row, const SimScript& script, const Landings& landings = {}, + const std::optional>& scripted = std::nullopt +){ + RowRun out; + StoryPose at = *story_pose(*row.start); + auto sim = std::make_unique(sweep_maps(), MapPosition{at.map, at.tile}, at.facing.value_or(Direction::SOUTH), script); + const auto add = [&out](const SimState& state){ + out.time += state.time; + out.steps += state.steps; + out.wild_battles += state.wild_battles; + out.in_wild_battles += state.in_wild_battles; + }; + for (size_t c = 0; c < row.steps.size() && out.failure.empty(); c++){ + const StoryStep& step = row.steps[c]; + out.before.emplace(c, sim->state().position); + out.failure = row_step_on_sim(*sim, at, step, row.id); + const bool let_pass = unscripted(out.failure) && (!scripted || scripted->contains(c)); + if (let_pass){ + out.failure.clear(); + out.scripted.insert(c); + } + if (!out.failure.empty() || (sim_plays(step) && !let_pass) || !step.pose_after){ + continue; + } + at = *story_pose(*step.pose_after); + const auto landing = landings.find(c); + const MapPosition land{at.map, landing == landings.end() ? at.tile : landing->second}; + if (!(sim->state().position == land)){ + add(sim->state()); + sim = std::make_unique(sweep_maps(), land, at.facing.value_or(sim->state().facing), script); + } + } + if (out.failure.empty() && !sim->state().violations.empty()){ + out.failure = "a violation on the way: " + sim->state().violations.back(); + } + out.end = sim->state().position; + add(sim->state()); + return out; +} + +// Why `run` differs from the clean run `clean`, or "". +std::string differs(const RowRun& run, const RowRun& clean){ + if (!run.failure.empty()){ + return run.failure; + } + if (!(run.end == clean.end)){ + return std::format("ended on {}, not {}.", to_string(run.end), to_string(clean.end)); + } + return ""; +} + +// One injected variant that failed its row. +struct SweepFailure{ + std::string step; + std::string variant; + std::string stopped; +}; + +UnitTestResult sweep_result(Logger& logger, FaultClass fault, const std::string& row, size_t variants, const std::vector& failures){ + logger.log(std::format("Fault sweep {} {}: {} variants, {} fail.", row, fault_class_name(fault), variants, failures.size())); + if (failures.empty()){ + return true; + } + std::string out = std::format("{} of {} variants fail {}:", failures.size(), variants, row); + for (const SweepFailure& failure : failures){ + logger.log(std::format("| {} | {} | {} | {} | {} |", row, failure.step, fault_class_name(fault), failure.variant, failure.stopped)); + out += std::format("\n {} {}: {}", failure.step, failure.variant, failure.stopped); + } + return out; +} + +// The open tiles within one of `pose`, diagonals too: where a scene can +// leave the player instead. +std::vector open_neighbors(const StoryPose& pose){ + const std::vector& maps = sweep_maps(); + const auto map = std::find_if(maps.begin(), maps.end(), [&](const MapData& data){ return data.name == pose.map; }); + std::vector out; + if (map == maps.end()){ + return out; + } + for (int dy = -1; dy <= 1; dy++){ + for (int dx = -1; dx <= 1; dx++){ + const TilePos tile{pose.tile.x + dx, pose.tile.y + dy}; + const bool open = (dx != 0 || dy != 0) && in_bounds(*map, tile) && object_at(*map, tile) == nullptr + && (tile_at(*map, tile) == TileKind::OPEN || tile_at(*map, tile) == TileKind::TALL_GRASS); + if (open){ + out.push_back(tile); + } + } + } + return out; +} + +// Row `row`'s stubbed steps that moved the player and have a walk after +// them, each ending on every open tile next to the table's pose in turn. +UnitTestResult sweep_scene_end_pose(Logger& logger, const StoryCheckpoint& row, const RowRun& clean){ + std::vector failures; + size_t variants = 0; + for (size_t c = 0; c < row.steps.size(); c++){ + const StoryStep& step = row.steps[c]; + const std::optional after = step.pose_after ? story_pose(*step.pose_after) : std::nullopt; + // A scene that only turns the player (the S.S. Ticket's, the aide's) + // ends where our walk did: not the game's end pose. + const auto from = clean.before.find(c); + // With no walk after it, nothing in the row goes on from the pose. + const bool walk_after = std::any_of(row.steps.begin() + c + 1, row.steps.end(), [](const StoryStep& next){ + return next.kind == StoryStepKind::ROUTE || next.kind == StoryStepKind::LEGS || next.kind == StoryStepKind::STEP; + }); + if (sim_plays(step) || !walk_after || !after || (from != clean.before.end() && from->second == MapPosition{after->map, after->tile})){ + continue; + } + for (const TilePos& tile : open_neighbors(*after)){ + variants++; + const std::string stopped = differs(run_row(row, SimScript{}, {{c, tile}}, clean.scripted), clean); + if (!stopped.empty()){ + failures.push_back({step.name, std::format("ends on {}", to_string(tile)), stopped}); + } + } + } + return sweep_result(logger, FaultClass::SCENE_END_POSE, row.id, variants, failures); +} + +// The mean of `values`, "-" if none. +std::string mean_of(const std::vector& values){ + if (values.empty()){ + return "-"; + } + return std::format("{:.1f}", std::accumulate(values.begin(), values.end(), 0.) / values.size()); +} + +// Row `row` with wild battles at the game's odds, from each seed. Logs +// passed, time, tiles walked again and time lost per battle. +UnitTestResult sweep_wild_battles(Logger& logger, const StoryCheckpoint& row, const RowRun& clean){ + std::vector failures; + std::vector seconds, again, lost; + int battles = 0; + for (unsigned seed = 1; seed <= GAME_ODDS_SEEDS; seed++){ + SimScript script; + script.encounter_rates = STORY_ENCOUNTER_RATES; + script.encounter_seed = seed; + script.wild_floor_maps = WILD_FLOOR_MAPS; + const RowRun run = run_row(row, script, {}, clean.scripted); + battles += run.wild_battles; + const std::string stopped = differs(run, clean); + if (!stopped.empty()){ + failures.push_back({"", std::format("seed {}", seed), stopped}); + continue; + } + seconds.push_back(run.time.count() / 1000.); + again.push_back(run.steps - clean.steps); + if (run.wild_battles > 0){ + lost.push_back((run.time - clean.time - run.in_wild_battles).count() / 1000. / run.wild_battles); + } + } + logger.log(std::format( + "Fault sweep {} wild battles: passed {}/{}, {} battles; of those passed: time (s) mean {}, clean {:.1f}; tiles walked again mean {}; s lost per battle mean {}", + row.id, GAME_ODDS_SEEDS - failures.size(), GAME_ODDS_SEEDS, battles, mean_of(seconds), clean.time.count() / 1000., mean_of(again), mean_of(lost) + )); + return sweep_result(logger, FaultClass::WILD_BATTLES, row.id, GAME_ODDS_SEEDS, failures); +} + +// Row `row` with every warp's fade ending LATE_FADE late. +UnitTestResult sweep_late_fade(Logger& logger, const StoryCheckpoint& row, const RowRun& clean){ + SimScript script; + script.timing.fade += LATE_FADE; + const std::string stopped = differs(run_row(row, script, {}, clean.scripted), clean); + std::vector failures; + if (!stopped.empty()){ + failures.push_back({"", std::format("every fade {} ms late", LATE_FADE.count()), stopped}); + } + return sweep_result(logger, FaultClass::LATE_FADE, row.id, 1, failures); +} + +// A fault class swept over row `row` (empty in FAULT_SWEEP_CASES: each +// row with a start). +struct FaultSweepInput{ + FaultClass fault = FaultClass::SCENE_END_POSE; + std::string row = {}; +}; +// Whether a sweep is expected to fail is KNOWN_FAILING's, by name. +struct FaultSweepExpectation{ +}; +struct FaultSweepCase{ + FaultSweepInput input; + FaultSweepExpectation expectation; +}; + +// The table's row `id`. +const StoryCheckpoint& table_row(const std::string& id){ + for (const StoryCheckpoint& row : story_checkpoints()){ + if (row.id == id){ + return row; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No row " + id); +} + +class Test_AutoStoryFaultSweep : public UnitTest{ +public: + explicit Test_AutoStoryFaultSweep(FaultSweepCase test_case) + : UnitTest(std::format("PokemonFRLG::AutoStory - Fault sweep: {}, {}", test_case.input.row, fault_class_name(test_case.input.fault))) + , m_fault(test_case.input.fault) + , m_row(table_row(test_case.input.row)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + UnitTestResult result; + try{ + result = sweep(logger); + }catch (Exception& e){ + result = std::string(e.name()) + ": " + e.message(); + } + const auto known = KNOWN_FAILING.find(name()); + if (known == KNOWN_FAILING.end()){ + return result; + } + if (result.result == UnitTestResult::PASSED){ + return "on KNOWN_FAILING (" + known->second + ") but passes now: take it off the list."; + } + logger.log("Known failing until " + known->second + ": " + result.message); + return true; + } + +private: + UnitTestResult sweep(Logger& logger) const{ + const RowRun clean = run_row(m_row, SimScript{}); + if (!clean.failure.empty()){ + logger.log(std::format("Fault sweep {}: not swept, the row fails clean: {}", m_row.id, clean.failure)); + return true; + } + switch (m_fault){ + case FaultClass::SCENE_END_POSE: + return sweep_scene_end_pose(logger, m_row, clean); + case FaultClass::WILD_BATTLES: + return sweep_wild_battles(logger, m_row, clean); + case FaultClass::LATE_FADE: + return sweep_late_fade(logger, m_row, clean); + case FaultClass::LOST_TAP: + break; + } + return true; + } + + FaultClass m_fault; + const StoryCheckpoint& m_row; +}; + +} // namespace + + +const FaultSweepCase FAULT_SWEEP_CASES[] = { + {.input = {.fault = FaultClass::SCENE_END_POSE}, .expectation = {}}, + {.input = {.fault = FaultClass::WILD_BATTLES}, .expectation = {}}, + {.input = {.fault = FaultClass::LATE_FADE}, .expectation = {}}, +}; + +void add_tests_AutoStoryFaultSweep(UnitTestDatabase& database){ + for (const FaultSweepCase& item : FAULT_SWEEP_CASES){ + for (const StoryCheckpoint& row : story_checkpoints()){ + if (!row.start || !story_pose(*row.start)){ + continue; + } + database.add(FaultSweepCase{.input = {.fault = item.input.fault, .row = row.id}, .expectation = item.expectation}); + } + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.h new file mode 100644 index 0000000000..cda979a2f3 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.h @@ -0,0 +1,26 @@ +/* AutoStory Fault Sweep Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryFaultSweep_Tests_H +#define PokemonAutomation_PokemonFRLG_AutoStoryFaultSweep_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Each class of console failure injected at every row of the story on the +// overworld sim; the rows the program still fails are known failing +// (PokemonFRLG_AutoStoryFaultSweep_Tests.cpp). +void add_tests_AutoStoryFaultSweep(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp index e201a86da0..739cd6bedb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp @@ -26,6 +26,7 @@ #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" #include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryFaultSweep_Tests.h" #include "PokemonFRLG_AutoStoryResources.h" #include "PokemonFRLG_AutoStoryRowSim.h" #include "PokemonFRLG_AutoStoryTable.h" @@ -473,6 +474,7 @@ void add_tests_AutoStoryLavender(UnitTestDatabase& database){ database.add(item); } add_tests_AutoStoryResources(database); + add_tests_AutoStoryFaultSweep(database); } diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 10cb4b5792..976060be1f 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1917,6 +1917,8 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGrind_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMart.h From f6080f0fa955dc2915e8bdf4336346ffa9e2d367 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 14:04:56 -0800 Subject: [PATCH 16/64] FRLG 00.28: honest stops in the dark cave; Martha via the corner (11, 35) Rock Tunnel without Flash is black but for a lit circle on the player. The battle text box and black screen checks read it as a battle on its way, so the check before each step ran a 15 s battle loop, and an open leg's stop was placed 0 to 3 tiles in when the battle came at its end (console B, 2026-11-09 13:35). The walker then "found" the player at the rock (20, 35) while they stood against the wall (25, 35). - dark_cave_screen(): black corners, lit middle. The observer reports nothing on it, and the check before or after a step sees no battle. - A stop on an open leg that started in a dark cave may be anywhere on the leg (whole_leg()), whatever the timing says. - below_martha_line: west 16, north 2, west 2 to the corner (11, 35), east 5 to (16, 35). The corner finds the player from any of (11..14, 35) and (11..16, 35) after a battle. - Sim: SimScript::dark_maps, with walker rules dark_cave_not_battle and whole_leg_in_dark; 00.28's game-odds runs walk Rock Tunnel dark. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_OverworldRecoveryWalk.cpp | 35 +++++++- .../Overworld/PokemonFRLG_OverworldSim.cpp | 33 ++++++- .../Overworld/PokemonFRLG_OverworldSim.h | 24 +++++- .../Overworld/PokemonFRLG_OverworldWalk.cpp | 40 ++++++++- .../Overworld/PokemonFRLG_OverworldWalk.h | 11 +++ .../PokemonFRLG_AutoStoryLavender_Tests.cpp | 85 +++++++++++++++++++ .../PokemonFRLG_AutoStoryScreenEvents.cpp | 5 ++ .../PokemonFRLG_AutoStoryScreenEvents.h | 2 + ...okemonFRLG_AutoStoryScreenEvents_Tests.cpp | 16 ++++ .../PokemonFRLG_AutoStoryTableLavender.cpp | 5 +- 10 files changed, 245 insertions(+), 11 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp index a2d26f6e2d..68c63608af 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp @@ -48,19 +48,39 @@ Pokemon::LegSpec leg_spec(const RouteStep& step, MoveSpeed speed){ } // How one step's walk went: if an open leg stopped part-way, how far the -// timing puts the player along it; and when its hold started. +// timing puts the player along it; when its hold started; and whether the +// screen was a dark cave's then (dark_cave_screen()). struct StepWalk{ std::optional stopped; WallClock hold_start; + bool dark = false; }; +// Where a stop on `step` leaves the player, from `timed`, the timing's +// tiles: anywhere on the leg if the leg started in a dark cave. There the +// timing has no basis: the screen is black before any battle's wipe, and +// a battle at the end of "east 12" on Rock Tunnel B1F was placed 0 to 3 +// tiles in (console B, 2026-11-09, 00.28); the player was found again at +// a wall 5 tiles off. +WalkedTiles stop_tiles(ConsoleHandle& console, const RouteStep& step, bool dark, WalkedTiles timed){ + if (!dark){ + return timed; + } + const WalkedTiles out = whole_leg(step); + console.log(std::format( + "Route: {} started in a dark cave: the stop's timing ({} to {} tiles in) isn't trusted; {} to {} tiles in.", + to_string(step), timed.min, timed.max, out.min, out.max + ), COLOR_ORANGE); + return out; +} + // One step of a route, for a player facing `facing`. StepWalk walk_step( ConsoleHandle& console, ProControllerContext& context, const RouteStep& step, std::optional facing, const OverworldInterruptSet& interrupts, MoveSpeed speed ){ - StepWalk out{std::nullopt, current_time()}; + StepWalk out{std::nullopt, current_time(), false}; switch (step.action){ case RouteAction::WALK:{ // Turning first, with a tap, makes the hold start from a standstill @@ -73,6 +93,9 @@ StepWalk walk_step( console.log(note); } context.wait_for_all_requests(); + if (VideoSnapshot before = console.video().snapshot()){ + out.dark = dark_cave_screen(*before.frame); + } out.hold_start = current_time(); BlackScreenOverWatcher arrival(COLOR_RED); Pokemon::WatchAlong fade(arrival); @@ -81,7 +104,7 @@ StepWalk walk_step( leg_spec(step, speed), MAX_INTERRUPTIONS_PER_LEG, warp_hold_watchers(step, fade) ); if (result.stopped){ - out.stopped = walked_near(step, result.tiles, tile_time(step, speed)); + out.stopped = stop_tiles(console, step, out.dark, walked_near(step, result.tiles, tile_time(step, speed))); return out; } if (step.warps){ @@ -187,7 +210,11 @@ StepOutcome walk_and_watch( if (done){ return StepOutcome{}; } - return StepOutcome{.end = StepEnd::LATE, .walked = recorder.place(console, step, tile_time(step, speed), walked.hold_start)}; + std::optional placed = recorder.place(console, step, tile_time(step, speed), walked.hold_start); + if (walked.dark && step.action == RouteAction::WALK && !step.to_wall){ + placed = stop_tiles(console, step, true, placed.value_or(whole_leg(step))); + } + return StepOutcome{.end = StepEnd::LATE, .walked = placed}; } // Holds on along `step`, stopped part-way off the grass or by a wild diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index be87d3f162..29f586f31b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -601,6 +601,10 @@ std::optional OverworldSim::watch(const std::vector& watche return watch_until(watchers, m_now, m_now + duration); } +bool OverworldSim::dark() const{ + return m_script.dark_maps.contains(map().name); +} + SimBattleEnd OverworldSim::handle_battle(SimBattleChoice choice){ if (!m_battle_pending){ violation("fought a battle that isn't there, on " + std::string(sim_screen_name(m_state.screen)) + "."); @@ -837,9 +841,10 @@ std::optional OverworldSimWalker::walk_step(const RouteStep& step, calls.log = [&](const std::string& message){ m_log.push_back("Leg: " + message); }; calls.fail = [&](const std::string& message){ fail(message); }; m_leg_start = m_sim.state().time; + m_leg_dark = m_sim.dark(); const Pokemon::LegResult result = Pokemon::walk_leg_with(leg, calls, MAX_INTERRUPTIONS_PER_LEG); if (result.stopped){ - return walked_near(step, result.tiles, TILE_TIME); + return dark_stop(step, walked_near(step, result.tiles, TILE_TIME)); } const Milliseconds fade_watched_from = m_rules.watch_fade_along_hold ? m_leg_start : m_sim.state().time; if (step.warps && !after_warp(step, warps_before, fade_watched_from)){ @@ -885,7 +890,13 @@ StepOutcome OverworldSimWalker::walk(const RouteStep& step, std::optional OverworldSimWalker::late_stop(const RouteStep& step){ - if (step.to_wall || !m_rules.place_late_battle){ + if (step.to_wall){ + return std::nullopt; + } + if (m_leg_dark){ + return dark_stop(step, whole_leg(step)); + } + if (!m_rules.place_late_battle){ return std::nullopt; } const WallClock start = sim_wall_clock(m_leg_start); @@ -896,10 +907,26 @@ std::optional OverworldSimWalker::late_stop(const RouteStep& step){ return stop.walked; } +// stop_tiles(): anywhere on `step` if it started in a dark cave. Without +// SimWalkerRules::whole_leg_in_dark, there the dark screen placed the stop +// at the hold's start. +WalkedTiles OverworldSimWalker::dark_stop(const RouteStep& step, WalkedTiles timed){ + if (!m_leg_dark){ + return timed; + } + const WalkedTiles out = m_rules.whole_leg_in_dark ? whole_leg(step) : walked_near(step, 0, TILE_TIME); + m_log.push_back(std::format("Route: {} started in a dark cave: {} to {} tiles in.", to_string(step), out.min, out.max)); + return out; +} + // Whether the screen shows a battle on its way: its wipe's black, or its -// text box before the HP boxes. +// text box before the HP boxes; without SimWalkerRules:: +// dark_cave_not_battle, also a dark cave's overworld. bool OverworldSimWalker::battle_on_its_way() const{ const SimScreen screen = m_sim.state().screen; + if (!m_rules.dark_cave_not_battle && screen == SimScreen::OVERWORLD && m_sim.dark()){ + return true; + } return screen == SimScreen::BATTLE_WIPE || screen == SimScreen::BATTLE_OPENING; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index 2b3e1df6fb..d141fa8f63 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -129,6 +129,11 @@ struct SimScript{ // (SimWalkerRules::confirm_turn) after 00.28 run 2 (console B, // 2026-11-09), where a one-tile leg only turned the player. std::set dropped_turn_taps; + // Caves dark without Flash (Rock Tunnel): the overworld is black but + // for a lit circle on the player, which the walker's battle text box + // check and screen observer read as a battle on its way (console B, + // 2026-11-09, 00.28), unless SimWalkerRules::dark_cave_not_battle. + std::set dark_maps; SimTiming timing; }; @@ -204,6 +209,8 @@ class OverworldSim{ OverworldSim(std::vector maps, MapPosition start, Direction facing, SimScript script = {}); const SimState& state() const{ return m_state; } + // Whether the player's map is one of SimScript::dark_maps. + bool dark() const; // Holds `direction` for `duration` then lets go for `release`, while // `watchers` watch until `watch` (at least the hold and release) from @@ -396,6 +403,18 @@ struct SimWalkerRules{ // Without it a dropped tap left a one-tile leg turning the player // only, taken as walked (console B, 2026-11-09, 00.28 run 2). bool confirm_turn = true; + // A dark cave's overworld isn't a battle on its way + // (OverworldWalkSteps::dark_cave_screen()). Without it the check + // before each step watched for a battle on it (console B, 2026-11-09, + // 00.28: "running from a wild Pokemon", then "not a battle"). + bool dark_cave_not_battle = true; + // A stop on an open leg that started in a dark cave may be anywhere on + // the leg (whole_leg()). Without it the stop is placed by the dark + // screen's black, read as the battle at the hold's start: a battle at + // the end of "east 12" on Rock Tunnel B1F was placed 0 to 3 tiles in, + // and the player was found again at a wall 5 tiles off (console B, + // 2026-11-09, 00.28). + bool whole_leg_in_dark = true; }; // OverworldWalkSteps::turn_to() on `sim`, which reads the facing on the @@ -442,6 +461,7 @@ class OverworldSimWalker{ }; StepOutcome walk(const RouteStep& step, std::optional facing); std::optional late_stop(const RouteStep& step); + WalkedTiles dark_stop(const RouteStep& step, WalkedTiles timed); std::optional walk_step(const RouteStep& step, std::optional facing); bool after_warp(const RouteStep& step, int warps_before, Milliseconds watched_from); bool fade_over_since(Milliseconds from) const; @@ -464,8 +484,10 @@ class OverworldSimWalker{ std::vector m_wild; std::vector m_other; std::vector m_log; - // When the last WALK leg's first hold started, on the sim's clock. + // When the last WALK leg's first hold started, on the sim's clock, + // and whether its map was dark then. Milliseconds m_leg_start{0}; + bool m_leg_dark = false; }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp index 04bc3de098..80cf4de310 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp @@ -7,6 +7,8 @@ #include #include #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" #include "CommonTools/Async/InferenceRoutines.h" #include "CommonTools/VisualDetectors/BlackScreenDetector.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" @@ -18,6 +20,7 @@ #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleScreenDetector.h" #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleTextBoxDetector.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" +#include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" #include "PokemonFRLG_PlayerFacingReader.h" #include "PokemonFRLG_OverworldWalk.h" @@ -292,11 +295,12 @@ void clear_open_message( namespace{ // What on screen shows a wild battle on its way: its text box, or the -// black of its wipe. Nothing if neither shows. +// black of its wipe. Nothing if neither shows, or on a dark cave's +// overworld (dark_cave_screen()). const char* battle_on_its_way(ConsoleHandle& console, ProControllerContext& context){ context.wait_for_all_requests(); VideoSnapshot screen = console.video().snapshot(); - if (!screen){ + if (!screen || dark_cave_screen(*screen.frame)){ return nullptr; } if (BattleTextBoxDetector(COLOR_RED).detect(screen)){ @@ -308,8 +312,40 @@ const char* battle_on_its_way(ConsoleHandle& console, ProControllerContext& cont return nullptr; } +// The parts of the game screen a dark cave shows black (its corners) and +// lit (the player's tile and the ones next to it), and how bright each +// may be, as the sum of the average's channels. Not measured on the +// console's frames yet: the corners are a GBA screen's 2 by 2 tiles, the +// middle its player's tile. +constexpr double DARK_CORNER_MAX = 45.0; +constexpr double LIT_MIDDLE_MIN = 120.0; + +bool box_brightness_below(const ImageViewRGB32& screen, const ImageFloatBox& box, double limit){ + return image_stats(extract_box_reference(screen, box)).average.sum() < limit; +} + } // namespace +bool dark_cave_screen(const ImageViewRGB32& screen){ + if (screen.width() == 0 || screen.height() == 0){ + return false; + } + const ImageFloatBox game = GameSettings::instance().GAME_BOX; + auto part = [&](double x, double y, double width, double height){ + return ImageFloatBox(game.x + game.width * x, game.y + game.height * y, game.width * width, game.height * height); + }; + const ImageFloatBox corners[] = { + part(0.00, 0.00, 0.13, 0.20), part(0.87, 0.00, 0.13, 0.20), + part(0.00, 0.80, 0.13, 0.20), part(0.87, 0.80, 0.13, 0.20), + }; + for (const ImageFloatBox& corner : corners){ + if (!box_brightness_below(screen, corner, DARK_CORNER_MAX)){ + return false; + } + } + return !box_brightness_below(screen, part(0.45, 0.42, 0.10, 0.16), LIT_MIDDLE_MIN); +} + size_t clear_unseen_battle( ConsoleHandle& console, ProControllerContext& context, const OverworldInterrupts& wild, const RouteStep& step diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h index a81e1a9eda..d2120b8e04 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h @@ -23,6 +23,7 @@ #include #include #include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" #include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" #include "Pokemon/Navigation/Pokemon_LegWalker.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" @@ -213,6 +214,16 @@ size_t clear_battle_before( const OverworldInterrupts& wild, const RouteStep& step ); +// Whether `screen` is the overworld of a cave dark without Flash (Rock +// Tunnel): black around a lit circle on the player in the middle. The +// battle text box detector and the black screen check read its black as +// a battle on its way (console B, 2026-11-09, 00.28: the check before +// each step ran a 15 s battle loop on it, "not a battle", and an open +// leg's stop was placed by it 0 to 3 tiles in, where the battle came at +// the leg's end). A battle's wipe is black in the middle too; its text +// box and HP boxes aren't black in the corners. +bool dark_cave_screen(const ImageViewRGB32& screen); + // After a warp's fade: if it was a wild battle's, runs from the battle and // returns true. bool run_from_battle_after_warp(ConsoleHandle& console, ProControllerContext& context); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp index e201a86da0..93fdd5741c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp @@ -241,6 +241,88 @@ UnitTestResult test_b1f_martha_after_row38_battle(Logger&){ return true; } +// Rock Tunnel has no Flash: both floors are dark. +const std::set ROCK_TUNNEL_DARK{StoryTable::ROCK_TUNNEL_1F, StoryTable::ROCK_TUNNEL_B1F}; + +// below_martha_line as `legs` from Winston's tile (29, 37) on `sim`, by the +// walker with `rules`: the failure, or empty if it ended on (16, 35). +std::string walk_below_martha(OverworldSim& sim, const std::vector& legs, const SimWalkerRules& rules){ + const MapPosition start{StoryTable::ROCK_TUNNEL_B1F, {29, 37}}; + const std::vector& maps = story_maps(); + const std::optional> route = fixed_route(maps, start, legs); + if (!route){ + return "the legs don't fit the map"; + } + const RoutePlanning planning{.maps = &maps, .costs = story_route_costs(), .start = start, .label = "below_martha_line"}; + std::string failure = OverworldSimWalker(sim, rules).run(*route, planning); + if (failure.empty() && !(sim.state().position == MapPosition{StoryTable::ROCK_TUNNEL_B1F, {16, 35}})){ + failure = "ended on " + to_string(sim.state().position) + ", not (16, 35)"; + } + return failure; +} + +// Console B, 2026-11-09 13:35, below_martha_line as it was then: west 16, +// north 2, east 6 to the wall (19, 35), west 3. A battle 6 tiles into +// west 16; the player found again at (1, 38); a battle seen late at the +// end of the walk back east 12 along row 38, placed 0 to 3 tiles in by +// the dark screen; "found again" at the rock (20, 35) while against the +// wall (25, 35); ended on (21, 35), where martha_line found no trainer. +// Here the second battle on each step of that walk back: with the dark +// cave's stops placed anywhere on their leg, every one ends on (16, 35); +// without, some don't. +UnitTestResult test_b1f_dark_row38_battle_old_legs(Logger& logger){ + const std::vector old_legs{{Direction::WEST, 16}, {Direction::NORTH, 2}, {Direction::EAST, 6}, {Direction::WEST, 3}}; + std::string failures; + int old_wrong = 0; + for (int second = 8; second <= 60; second++){ + SimScript script; + script.dark_maps = ROCK_TUNNEL_DARK; + script.encounters = {SimEncounter{.grass_step = 6}, SimEncounter{.grass_step = second, .seen_late = true}}; + OverworldSim fixed(maps_after_route10(), MapPosition{StoryTable::ROCK_TUNNEL_B1F, {29, 37}}, Direction::NORTH, script); + if (const std::string failure = walk_below_martha(fixed, old_legs, SimWalkerRules{}); !failure.empty()){ + failures += std::format("{}battle on step {}: {}", failures.empty() ? "" : " | ", second, failure); + } + SimWalkerRules old_rules; + old_rules.whole_leg_in_dark = false; + old_rules.dark_cave_not_battle = false; + OverworldSim old(maps_after_route10(), MapPosition{StoryTable::ROCK_TUNNEL_B1F, {29, 37}}, Direction::NORTH, script); + if (const std::string failure = walk_below_martha(old, old_legs, old_rules); !failure.empty()){ + old_wrong++; + logger.log(std::format("Without the dark cave rules, battle on step {}: {}", second, failure)); + } + } + if (!failures.empty()){ + return failures; + } + if (old_wrong == 0){ + return "Without the dark cave rules every walk still ended on (16, 35): the test doesn't show the failure."; + } + return true; +} + +// Rock Tunnel dark, from Winston's tile: below_martha_line, martha_line +// and Martha's battle with one wild battle on each step the walk takes, +// on rows 37 and 38 and on row 35 between the corner (11, 35) and +// (16, 35), seen as it starts and seen late: Martha alone is fought. +UnitTestResult test_b1f_dark_martha_battle_anywhere(Logger&){ + std::string failures; + for (int step = 1; step <= 40; step++){ + for (const bool late : {false, true}){ + SimScript script; + script.dark_maps = ROCK_TUNNEL_DARK; + script.encounters = {SimEncounter{.grass_step = step, .seen_late = late}}; + OverworldSim sim(maps_after_route10(), MapPosition{StoryTable::ROCK_TUNNEL_B1F, {29, 37}}, Direction::NORTH, script); + if (const std::string failure = winston_to_martha(sim); !failure.empty()){ + failures += std::format("{}step {}{}: {}", failures.empty() ? "" : " | ", step, late ? " late" : "", failure); + } + } + } + if (!failures.empty()){ + return failures; + } + return true; +} + // 00.28 whole with a wild battle every 7 to 25 steps on the tunnel's floor, // the gaps drawn from each of these seeds: the row ends where it should. UnitTestResult test_rock_tunnel_frequent_battles(Logger&){ @@ -358,6 +440,7 @@ UnitTestResult test_rock_tunnel_game_odds(Logger& logger){ SimScript script; script.encounter_rates = ROCK_TUNNEL_ENCOUNTER_RATES; script.encounter_seed = seed; + script.dark_maps = ROCK_TUNNEL_DARK; OverworldSim sim = row_start_sim("00.28", script); const UnitTestResult result = row_checked(sim, "00.28", {ROCK_TUNNEL_TRAINERS}, MapPosition{StoryTable::ROUTE10, {8, 58}}); const bool passed = result.result == UnitTestResult::PASSED; @@ -463,6 +546,8 @@ const AutoStoryLavenderCase AUTO_STORY_LAVENDER_CASES[] = { {.input = {"00.28 a wild battle every 7 to 25 steps, 12 seeds", test_rock_tunnel_frequent_battles}, .expectation = {}}, {.input = {"00.28 wild battles at the game's odds, 30 seeds", test_rock_tunnel_game_odds}, .expectation = {}}, {.input = {"00.28 B1F a wild battle into row 38, then a step short: Martha still sees the player", test_b1f_martha_after_row38_battle}, .expectation = {}}, + {.input = {"00.28 B1F dark, the 13:35 legs: a battle at the end of the walk back along row 38", test_b1f_dark_row38_battle_old_legs}, .expectation = {}}, + {.input = {"00.28 B1F dark, a wild battle on any step to Martha's line", test_b1f_dark_martha_battle_anywhere}, .expectation = {}}, {.input = {"00.29 Route 10 south, the ledge, Lavender Town's Pokemon Center", test_lavender_row}, .expectation = {}}, {.input = {"00.29 a tile off after each open leg", test_lavender_tile_off}, .expectation = {}}, {.input = {"00.28 and 00.29 save on Route 10 and in Lavender Town", test_save_places}, .expectation = {}}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp index 85edb74b36..de1f0072c7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp @@ -4,6 +4,7 @@ * */ +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h" #include "PokemonFRLG_AutoStoryScreenEvents.h" namespace PokemonAutomation{ @@ -26,6 +27,10 @@ ScreenEvents FrlgScreenObserver::observe(const VideoSnapshot& frame, WallClock){ return {}; } const ImageViewRGB32& screen = *frame.frame; + if (OverworldWalkSteps::dark_cave_screen(screen)){ + // Its black below passes for a battle's text box. + return {}; + } ScreenEvents out = Pokemon::fade_events(Pokemon::fade_of_screen(screen)); if (Pokemon::fade_in(out) != Pokemon::WarpFade::NONE){ // A uniform screen has no box or menu to read. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h index d6403a765f..63cfa22307 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h @@ -25,6 +25,8 @@ namespace PokemonFRLG{ // - CHOICE_BOX: a Yes/No or answer box beside it (SelectionDialogDetector); // - BATTLE_STARTED: the battle menu or a battle's text box; // - FADE_BLACK / FADE_WHITE: fade_of_screen(). +// Nothing on a dark cave's overworld (dark_cave_screen()), whose black +// the battle text box detector reads as a box. // Not reported yet, as FRLG has no detector for them here: the map-name // popup (LOCATION_BANNER), PLAYER_CAN_MOVE, SCREEN_STILL, the interact // prompt (FRLG has none) and a battle's end. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp index 7f8182bccc..4ed0f3d1a5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp @@ -29,6 +29,9 @@ struct ScreenEventsInput{ std::string name; // The frame's colour; 0 for no frame. uint32_t color; + // The colour of a square in the middle of the frame, around the + // player; 0 for none. + uint32_t middle = 0; }; struct ScreenEventsExpectation{ @@ -52,6 +55,13 @@ class Test_AutoStoryScreenEvents : public UnitTest{ if (m_case.input.color != 0){ ImageRGB32 image(1920, 1080); image.fill(m_case.input.color); + if (m_case.input.middle != 0){ + for (size_t y = 380; y < 700; y++){ + for (size_t x = 800; x < 1120; x++){ + image.pixel(x, y) = m_case.input.middle; + } + } + } frame = VideoSnapshot(std::move(image), WallClock()); } FrlgScreenObserver observer; @@ -82,6 +92,12 @@ const ScreenEventsCase SCREEN_EVENTS_CASES[] = { .input = {"a white screen is a white fade only", 0xffffffff}, .expectation = {{ScreenEvent::FADE_WHITE}}, }, + { + // Rock Tunnel without Flash (console B, 2026-11-09, 00.28): its + // black read as a battle's text box before each step. + .input = {"a dark cave, black but for a lit middle, shows nothing", 0xff000000, 0xff8c7c64}, + .expectation = {{}}, + }, }; void add_tests_AutoStoryScreenEvents(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableLavender.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableLavender.cpp index 9613070677..9ba3bf882d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableLavender.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTableLavender.cpp @@ -72,7 +72,10 @@ StoryCheckpoint rock_tunnel(){ running(legs("winston_line_end", {{WEST, 5}, {SOUTH, 10}, {NORTH, 1}, {WEST, 1}}, "west to the wall (33, 28), down column 33 to the wall (33, 38), up to (33, 37) and west to (32, 37)")), into_line("winston_line", WEST, "along row 37 onto (29, 37), the end of Winston's line: he walks down to (29, 36)"), battle("pokemaniac_winston", at(ROCK_TUNNEL_B1F, 29, 37, NORTH), false, "Slowpoke and Slowpoke"), - running(legs("below_martha_line", {{WEST, 16}, {NORTH, 2}, {EAST, 6}, {WEST, 3}}, "west along row 37 to (13, 37), up to the wall (13, 35), east to the wall (19, 35), west to (16, 35)")), + // The corner (11, 35), wall north and rock west, finds the player + // from any of (11..14, 35) after a battle; east to the wall (19, + // 35) did not (console B, 2026-11-09 13:35: found 5 tiles off). + running(legs("below_martha_line", {{WEST, 16}, {NORTH, 2}, {WEST, 2}, {EAST, 5}}, "west along row 37 to (13, 37), up to the wall (13, 35), west to the corner (11, 35), east to (16, 35)")), into_line("martha_line", NORTH, "up column 16 onto (16, 33), beside Martha; from (17, 35), a tile short, up column 17 onto (17, 33), the end of her line"), battle("picnicker_martha", at(ROCK_TUNNEL_B1F, 16, 33, WEST), false, "Oddish and Bulbasaur"), running(legs("below_allen_line", {{EAST, 1}, {NORTH, 5}, {EAST, 12}, {NORTH, 9}, {EAST, 11}, {NORTH, 2}, {WEST, 2}, {NORTH, 5}}, "east to the wall (17, 33), up column 17 to the wall (17, 28), east to the wall (29, 28), up column 29 past Steve's line to the wall (29, 19), east to (40, 19), up to row 17, west to the wall (38, 17) and up to the wall (38, 12)")), From 79bfa9735f518579d47d60698549da158f7472f3 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 14:07:04 -0800 Subject: [PATCH 17/64] FRLG 00.28: dark-cave stop rule shared in the reanchor code; code health Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonFRLG_OverworldReanchor.cpp | 4 ++ .../Overworld/PokemonFRLG_OverworldReanchor.h | 8 ++++ .../PokemonFRLG_OverworldRecoveryWalk.cpp | 37 +++++++++--------- .../Overworld/PokemonFRLG_OverworldSim.cpp | 38 ++++--------------- .../Overworld/PokemonFRLG_OverworldSim.h | 13 +++++-- 5 files changed, 46 insertions(+), 54 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp index f5328d5980..cca489347c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.cpp @@ -323,6 +323,10 @@ WalkedTiles whole_leg(const RouteStep& step){ return WalkedTiles{.min = 0, .max = step.tiles}; } +WalkedTiles stop_tiles(const RouteStep& step, WalkedTiles timed, bool dark){ + return dark ? whole_leg(step) : timed; +} + std::string to_string(const StopCandidate& candidate){ std::string text = to_string(candidate.player); if (candidate.trainer){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h index 28530d8c11..ae962e95b7 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h @@ -58,6 +58,14 @@ WalkedTiles walked_near(const RouteStep& step, int estimate, Milliseconds tile_t std::vector with_warp_slack(std::vector route); // Anywhere on `step`, for a stop the timing doesn't place. WalkedTiles whole_leg(const RouteStep& step); +// Where a stop on `step` leaves the player, from `timed`, the tiles its +// timing gives: anywhere on the leg (whole_leg()) if it started on a dark +// cave's screen (OverworldWalkSteps::dark_cave_screen()). There the timing +// has no basis: the screen is black before any battle's wipe, and a +// battle at the end of "east 12" on Rock Tunnel B1F was placed 0 to 3 +// tiles in (console B, 2026-11-09, 00.28). The player, "found again" at +// a wall from those, was 5 tiles off. +WalkedTiles stop_tiles(const RouteStep& step, WalkedTiles timed, bool dark); // A trainer who saw the player and walked up to them: which of `map`'s // objects, and the tile next to the player they stand on afterwards. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp index 68c63608af..9200c0e02b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp @@ -56,22 +56,21 @@ struct StepWalk{ bool dark = false; }; -// Where a stop on `step` leaves the player, from `timed`, the timing's -// tiles: anywhere on the leg if the leg started in a dark cave. There the -// timing has no basis: the screen is black before any battle's wipe, and -// a battle at the end of "east 12" on Rock Tunnel B1F was placed 0 to 3 -// tiles in (console B, 2026-11-09, 00.28); the player was found again at -// a wall 5 tiles off. -WalkedTiles stop_tiles(ConsoleHandle& console, const RouteStep& step, bool dark, WalkedTiles timed){ - if (!dark){ - return timed; +// stop_tiles(), logged when the leg started in a dark cave. +WalkedTiles logged_stop_tiles(ConsoleHandle& console, const RouteStep& step, bool dark, WalkedTiles timed){ + if (dark){ + console.log(std::format( + "Route: {} started in a dark cave: the stop's timing ({} to {} tiles in) isn't trusted.", + to_string(step), timed.min, timed.max + ), COLOR_ORANGE); } - const WalkedTiles out = whole_leg(step); - console.log(std::format( - "Route: {} started in a dark cave: the stop's timing ({} to {} tiles in) isn't trusted; {} to {} tiles in.", - to_string(step), timed.min, timed.max, out.min, out.max - ), COLOR_ORANGE); - return out; + return stop_tiles(step, timed, dark); +} + +// Whether the screen shows a dark cave's overworld (dark_cave_screen()). +bool on_dark_cave(ConsoleHandle& console){ + const VideoSnapshot screen = console.video().snapshot(); + return screen && dark_cave_screen(*screen.frame); } // One step of a route, for a player facing `facing`. @@ -93,9 +92,7 @@ StepWalk walk_step( console.log(note); } context.wait_for_all_requests(); - if (VideoSnapshot before = console.video().snapshot()){ - out.dark = dark_cave_screen(*before.frame); - } + out.dark = on_dark_cave(console); out.hold_start = current_time(); BlackScreenOverWatcher arrival(COLOR_RED); Pokemon::WatchAlong fade(arrival); @@ -104,7 +101,7 @@ StepWalk walk_step( leg_spec(step, speed), MAX_INTERRUPTIONS_PER_LEG, warp_hold_watchers(step, fade) ); if (result.stopped){ - out.stopped = stop_tiles(console, step, out.dark, walked_near(step, result.tiles, tile_time(step, speed))); + out.stopped = logged_stop_tiles(console, step, out.dark, walked_near(step, result.tiles, tile_time(step, speed))); return out; } if (step.warps){ @@ -212,7 +209,7 @@ StepOutcome walk_and_watch( } std::optional placed = recorder.place(console, step, tile_time(step, speed), walked.hold_start); if (walked.dark && step.action == RouteAction::WALK && !step.to_wall){ - placed = stop_tiles(console, step, true, placed.value_or(whole_leg(step))); + placed = logged_stop_tiles(console, step, true, placed.value_or(whole_leg(step))); } return StepOutcome{.end = StepEnd::LATE, .walked = placed}; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index 29f586f31b..9d65da8a27 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -166,6 +166,7 @@ void OverworldSim::update_view(){ m_state.position = MapPosition{map().name, m_player.position}; m_state.black_below = map().connections.empty() && map().tiles.height <= SMALL_ROOM_ROWS && m_player.position.y >= map().tiles.height - BLACK_BELOW_ROWS; + m_state.dark = m_script.dark_maps.contains(map().name); } void OverworldSim::schedule(Milliseconds at, SimScreen screen, bool unfreeze){ @@ -601,10 +602,6 @@ std::optional OverworldSim::watch(const std::vector& watche return watch_until(watchers, m_now, m_now + duration); } -bool OverworldSim::dark() const{ - return m_script.dark_maps.contains(map().name); -} - SimBattleEnd OverworldSim::handle_battle(SimBattleChoice choice){ if (!m_battle_pending){ violation("fought a battle that isn't there, on " + std::string(sim_screen_name(m_state.screen)) + "."); @@ -841,7 +838,7 @@ std::optional OverworldSimWalker::walk_step(const RouteStep& step, calls.log = [&](const std::string& message){ m_log.push_back("Leg: " + message); }; calls.fail = [&](const std::string& message){ fail(message); }; m_leg_start = m_sim.state().time; - m_leg_dark = m_sim.dark(); + m_leg_dark = m_sim.state().dark; const Pokemon::LegResult result = Pokemon::walk_leg_with(leg, calls, MAX_INTERRUPTIONS_PER_LEG); if (result.stopped){ return dark_stop(step, walked_near(step, result.tiles, TILE_TIME)); @@ -890,13 +887,7 @@ StepOutcome OverworldSimWalker::walk(const RouteStep& step, std::optional OverworldSimWalker::late_stop(const RouteStep& step){ - if (step.to_wall){ - return std::nullopt; - } - if (m_leg_dark){ - return dark_stop(step, whole_leg(step)); - } - if (!m_rules.place_late_battle){ + if (step.to_wall || (!m_leg_dark && !m_rules.place_late_battle)){ return std::nullopt; } const WallClock start = sim_wall_clock(m_leg_start); @@ -904,30 +895,15 @@ std::optional OverworldSimWalker::late_stop(const RouteStep& step){ step, TILE_TIME, screen_event_log(m_sim.state(), m_leg_start), start, sim_wall_clock(m_sim.state().time) ); m_log.push_back(late_stop_line(step, stop, start)); - return stop.walked; -} - -// stop_tiles(): anywhere on `step` if it started in a dark cave. Without -// SimWalkerRules::whole_leg_in_dark, there the dark screen placed the stop -// at the hold's start. -WalkedTiles OverworldSimWalker::dark_stop(const RouteStep& step, WalkedTiles timed){ - if (!m_leg_dark){ - return timed; - } - const WalkedTiles out = m_rules.whole_leg_in_dark ? whole_leg(step) : walked_near(step, 0, TILE_TIME); - m_log.push_back(std::format("Route: {} started in a dark cave: {} to {} tiles in.", to_string(step), out.min, out.max)); - return out; + return m_leg_dark ? std::optional(dark_stop(step, whole_leg(step))) : stop.walked; } // Whether the screen shows a battle on its way: its wipe's black, or its -// text box before the HP boxes; without SimWalkerRules:: -// dark_cave_not_battle, also a dark cave's overworld. +// text box before the HP boxes; without dark_cave_not_battle, a dark cave. bool OverworldSimWalker::battle_on_its_way() const{ const SimScreen screen = m_sim.state().screen; - if (!m_rules.dark_cave_not_battle && screen == SimScreen::OVERWORLD && m_sim.dark()){ - return true; - } - return screen == SimScreen::BATTLE_WIPE || screen == SimScreen::BATTLE_OPENING; + const bool dark_misread = !m_rules.dark_cave_not_battle && screen == SimScreen::OVERWORLD && m_sim.state().dark; + return dark_misread || screen == SimScreen::BATTLE_WIPE || screen == SimScreen::BATTLE_OPENING; } // clear_unseen_battle(): the battle's text box or wipe seen after the diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index d141fa8f63..c84653ded1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -155,6 +155,8 @@ struct SimState{ // Whether black shows below the map: the player stands near the bottom // of a map with nothing joined to it (a small room or a gate). bool black_below = false; + // Whether the player's map is one of SimScript::dark_maps. + bool dark = false; int steps = 0; int warps = 0; int wild_battles = 0; @@ -209,8 +211,6 @@ class OverworldSim{ OverworldSim(std::vector maps, MapPosition start, Direction facing, SimScript script = {}); const SimState& state() const{ return m_state; } - // Whether the player's map is one of SimScript::dark_maps. - bool dark() const; // Holds `direction` for `duration` then lets go for `release`, while // `watchers` watch until `watch` (at least the hold and release) from @@ -461,7 +461,14 @@ class OverworldSimWalker{ }; StepOutcome walk(const RouteStep& step, std::optional facing); std::optional late_stop(const RouteStep& step); - WalkedTiles dark_stop(const RouteStep& step, WalkedTiles timed); + // stop_tiles(); without SimWalkerRules::whole_leg_in_dark, the dark + // screen places the stop at the hold's start. + WalkedTiles dark_stop(const RouteStep& step, WalkedTiles timed) const{ + if (m_leg_dark && !m_rules.whole_leg_in_dark){ + return walked_near(step, 0, MovementMechanics::TILE_TIME); + } + return stop_tiles(step, timed, m_leg_dark); + } std::optional walk_step(const RouteStep& step, std::optional facing); bool after_warp(const RouteStep& step, int warps_before, Milliseconds watched_from); bool fade_over_since(Milliseconds from) const; From 46c99dca6c32acf83259c1137209196d8ef6f662 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 14:14:06 -0800 Subject: [PATCH 18/64] StoryInterrupts tests: a battle's opening before a walk step (red) The BDSP fault sweep (#226) injects a battle's opening at the start of each step after a walk: 51 steps of 00.01-01.11 fail as interrupt_unsettled after three looks, as the opening takes longer than three looks to show its battle. These cases expect the looks to wait for the battle and clear it before the walk. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon_StoryInterrupts_Tests.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp index 8f4d0644c5..a86d058fb8 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -71,6 +71,10 @@ ScreenLook warp(){ ScreenLook white_unsettled(){ return look_of({{0, WALK}, {100, WHITE}, {700, WALK}}, 1000); } +// A trainer's lines, then the battle's black, still down: no battle yet. +ScreenLook trainer_opening(){ + return look_of({{0, WALK}, {100, BOX}, {2000, BLACK}}, 2100); +} // The same white, looked at for long enough after it: a cave exit. ScreenLook white_settled(){ return look_of({{0, WALK}, {100, WHITE}, {700, WALK}, {10000, WALK}}, 10000); @@ -324,6 +328,30 @@ UnitTestResult test_unsettled_before_a_battle(){ return expect_trace(game, {"look", "run starly"}); } +// A battle's opening still playing when a walk step begins: the walk +// before it ended in grass or in a trainer's sight (BDSP fault sweep, 51 +// steps of 00.01-01.11). The looks wait for the battle, past max_looks, +// and its handler clears it before the step. +UnitTestResult test_opening_before_a_walk(ScreenLook opening, ScreenLook battle, const std::string& kind, const std::string& handler){ + FakeGame game; + game.screens = {opening, opening, opening, opening, std::move(battle), quiet()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (!run.outcome.succeeded()){ + return "Expected the walk to run after the battle, got " + to_string(run.outcome); + } + return expect_trace(game, { + "look", "look again", "look again", "look again", "look again", + "clear " + handler, "told " + kind + " ", "run walk", + }); +} +UnitTestResult test_wild_opening_before_a_walk(){ + return test_opening_before_a_walk(white_unsettled(), wild(), "wild encounter", "wild"); +} +UnitTestResult test_trainer_opening_before_a_walk(){ + return test_opening_before_a_walk(trainer_opening(), trainer(), "trainer sight", "trainer"); +} + UnitTestResult test_failure_explained(bool throws){ FakeGame game; // Before the step, after its failure, before its second run. @@ -462,6 +490,14 @@ const StoryInterruptsCase STORY_INTERRUPTS_CASES[] = { .input = {.name = "unsettled: a battle's opening before a battle step", .test = test_unsettled_before_a_battle}, .expectation = {.description = "the step's, after one look"}, }, + { + .input = {.name = "unsettled: a wild battle's opening before a walk", .test = test_wild_opening_before_a_walk}, + .expectation = {.description = "waits for the battle, clears it, then the walk"}, + }, + { + .input = {.name = "unsettled: a trainer battle's opening before a walk", .test = test_trainer_opening_before_a_walk}, + .expectation = {.description = "waits for the battle, fights it, then the walk"}, + }, { .input = {.name = "a failed step an interrupt explains runs again", .test = test_failed_outcome_explained}, .expectation = {.description = "cleared after the failure, then the step again"}, From 0be68acae1a1ab8ed43035bacc5672dc4afbf945 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 14:15:01 -0800 Subject: [PATCH 19/64] StoryInterrupts: wait for a battle's opening before any step A walk that ends in grass or in a trainer's sight leaves the next step to start on the battle's opening: a white flash, or a fade still down, with no battle yet. Three looks (0.9 s on BDSP) were too few for its battle to show, and the step failed as interrupt_unsettled (BDSP fault sweep, #226: 51 steps of 00.01-01.11). An unsettled screen that may be a battle's opening (a white fade, a fade still down, or a fade after a dialog box) is now looked at up to max_opening_looks (40) looks, until its battle shows; the battle is then cleared by its handler (wild: run, trainer: fight) and the step goes on. A door's fade, back up with no box before it, keeps the three looks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryInterrupts.cpp | 40 +++++++++++++++---- .../AutoStory/Pokemon_StoryInterrupts.h | 11 +++++ .../Pokemon_StoryInterrupts_Tests.cpp | 29 +++++++++++++- 3 files changed, 71 insertions(+), 9 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp index 0f64cbb35e..32a14b42fa 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp @@ -4,6 +4,7 @@ * */ +#include #include #include "Common/Cpp/Exceptions.h" #include "Pokemon_StoryInterrupts.h" @@ -49,20 +50,45 @@ bool InterruptHandlerTable::step_starts_on(StoryStepKind step, InterruptKind kin namespace{ -InterruptVerdict judge(const StoryInterrupts& interrupts, bool fresh){ - const ScreenLook look = interrupts.look(fresh); - return classify_interrupt(look.log, look.window, interrupts.knobs); +// Whether an UNSETTLED verdict on `look` may be a battle's opening: its +// fade is white (an encounter's flash), still down (a battle's fade ends +// on the battle), or came after a dialog box (a trainer's lines). +bool may_open_a_battle(const ScreenLook& look, const InterruptVerdict& verdict){ + const auto fade = std::find_if(verdict.evidence.begin(), verdict.evidence.end(), [](const ScreenEventChange& change){ + return change.edge == ScreenEventEdge::ROSE && + (change.event == ScreenEvent::FADE_WHITE || change.event == ScreenEvent::FADE_BLACK); + }); + if (fade == verdict.evidence.end()){ + return false; + } + const bool still_down = std::none_of(verdict.evidence.begin(), verdict.evidence.end(), [](const ScreenEventChange& change){ + return change.edge == ScreenEventEdge::FELL; + }); + if (fade->event == ScreenEvent::FADE_WHITE || still_down){ + return true; + } + return std::any_of(look.log.changes().begin(), look.log.changes().end(), [&](const ScreenEventChange& change){ + return change.event == ScreenEvent::DIALOG_BOX && change.edge == ScreenEventEdge::ROSE && + look.window.start <= change.time && change.time < fade->time; + }); } // The look's verdict, looked at again while it is unsettled, up to -// max_looks looks in all; not again before a step that starts on it. +// max_looks looks in all, or max_opening_looks while it may be a battle's +// opening; not again before a step that starts on it. InterruptVerdict settled_verdict(const StoryInterrupts& interrupts, StoryStepKind step){ - InterruptVerdict verdict = judge(interrupts, true); + ScreenLook look = interrupts.look(true); + InterruptVerdict verdict = classify_interrupt(look.log, look.window, interrupts.knobs); if (interrupts.handlers.step_starts_on(step, InterruptKind::UNSETTLED)){ return verdict; } - for (size_t looks = 1; verdict.kind == InterruptKind::UNSETTLED && looks < interrupts.max_looks; looks++){ - verdict = judge(interrupts, false); + for (size_t looks = 1; verdict.kind == InterruptKind::UNSETTLED; looks++){ + const size_t limit = may_open_a_battle(look, verdict) ? interrupts.max_opening_looks : interrupts.max_looks; + if (looks >= limit){ + break; + } + look = interrupts.look(false); + verdict = classify_interrupt(look.log, look.window, interrupts.knobs); } return verdict; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h index 76df68eb3e..1a43414580 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h @@ -22,6 +22,13 @@ * that is its battle's opening, still playing (BDSP's Starly battle right * after the starter is picked), and the step waits for it itself. * + * Before another step, an unsettled screen that may be a battle's opening + * (a white flash, a fade still down, a fade after a dialog box) is looked + * at until its battle shows, up to max_opening_looks looks: the walk + * before the step ended in grass or in a trainer's sight. The battle is + * then cleared as any other. A fade that came back up with no box before + * it (a door's) is looked at max_looks times only. + * */ #ifndef PokemonAutomation_Pokemon_StoryInterrupts_H @@ -96,6 +103,10 @@ struct StoryInterrupts{ // before it fails the step as "interrupt_unsettled". A step that // starts on it gets it on the first look. size_t max_looks = 3; + // The same, for a screen that may be a battle's opening: enough looks + // for its battle to show. BDSP's 300 ms looks cover 12 s, past its + // battle_after_fade (8 s), after which a fade with no battle settles. + size_t max_opening_looks = 40; // Interrupts cleared for one step before it fails as // "too_many_interrupts". size_t max_per_step = 3; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp index a86d058fb8..187a6b14a5 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -75,6 +75,10 @@ ScreenLook white_unsettled(){ ScreenLook trainer_opening(){ return look_of({{0, WALK}, {100, BOX}, {2000, BLACK}}, 2100); } +// A door's black, back up with no box before it: a warp, not yet settled. +ScreenLook black_unsettled(){ + return look_of({{0, WALK}, {100, BLACK}, {700, WALK}}, 1000); +} // The same white, looked at for long enough after it: a cave exit. ScreenLook white_settled(){ return look_of({{0, WALK}, {100, WHITE}, {700, WALK}, {10000, WALK}}, 10000); @@ -302,9 +306,10 @@ UnitTestResult test_unsettled_looks_again(){ return expect_trace(game, {"look", "look again", "clear warp", "told warp ", "run walk"}); } +// A door's fade is no battle's opening: three looks, as before. UnitTestResult test_unsettled_is_bounded(){ FakeGame game; - game.screens = {white_unsettled()}; + game.screens = {black_unsettled()}; StoryInterrupts interrupts = fake_interrupts(game); const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); if (run.outcome.failure != "interrupt_unsettled"){ @@ -352,6 +357,22 @@ UnitTestResult test_trainer_opening_before_a_walk(){ return test_opening_before_a_walk(trainer_opening(), trainer(), "trainer sight", "trainer"); } +// A white that shows no battle and does not settle: max_opening_looks. +UnitTestResult test_opening_is_bounded(){ + FakeGame game; + game.screens = {white_unsettled()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.max_opening_looks = 5; + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (run.outcome.failure != "interrupt_unsettled"){ + return "Expected interrupt_unsettled, got " + to_string(run.outcome); + } + return expect_trace(game, { + "look", "look again", "look again", "look again", "look again", + "told unsettled interrupt_unsettled: walk", + }); +} + UnitTestResult test_failure_explained(bool throws){ FakeGame game; // Before the step, after its failure, before its second run. @@ -484,7 +505,7 @@ const StoryInterruptsCase STORY_INTERRUPTS_CASES[] = { }, { .input = {.name = "unsettled: at most max_looks looks", .test = test_unsettled_is_bounded}, - .expectation = {.description = "interrupt_unsettled after three looks"}, + .expectation = {.description = "a door's fade: interrupt_unsettled after three looks"}, }, { .input = {.name = "unsettled: a battle's opening before a battle step", .test = test_unsettled_before_a_battle}, @@ -498,6 +519,10 @@ const StoryInterruptsCase STORY_INTERRUPTS_CASES[] = { .input = {.name = "unsettled: a trainer battle's opening before a walk", .test = test_trainer_opening_before_a_walk}, .expectation = {.description = "waits for the battle, fights it, then the walk"}, }, + { + .input = {.name = "unsettled: at most max_opening_looks for an opening", .test = test_opening_is_bounded}, + .expectation = {.description = "a white with no battle: interrupt_unsettled"}, + }, { .input = {.name = "a failed step an interrupt explains runs again", .test = test_failed_outcome_explained}, .expectation = {.description = "cleared after the failure, then the step again"}, From 500e624763a415b5c9d54fcdd9d1b45f9e7caa14 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 14:46:04 -0800 Subject: [PATCH 20/64] Scene judges tests: a closing fade is no quiet (red) Mom's Running Shoes scene (lab-B 2026-11-09 14:33) ended at the start of its closing fade: BDSP's overworld reads a black frame as no box and it stays still, so TalkOver counted it as quiet. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp index 2d0db31cfd..6620fd0204 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp @@ -115,6 +115,9 @@ int first_beat(TalkOver& judge, const std::vector& beats, SceneMov const ScreenEvents QUIET{ScreenEvent::PLAYER_CAN_MOVE, ScreenEvent::SCREEN_STILL}; const ScreenEvents CALM{ScreenEvent::PLAYER_CAN_MOVE}; const ScreenEvents BOX{ScreenEvent::DIALOG_BOX, ScreenEvent::PLAYER_CAN_MOVE, ScreenEvent::SCREEN_STILL}; +// A black frame as BDSP's eyes see it: no box, so "overworld", and still. +const ScreenEvents FADED{ScreenEvent::FADE_BLACK, ScreenEvent::PLAYER_CAN_MOVE, ScreenEvent::SCREEN_STILL}; +const ScreenEvents CALM_FADED{ScreenEvent::FADE_BLACK, ScreenEvent::PLAYER_CAN_MOVE}; std::vector repeat(const ScreenEvents& look, size_t count){ return std::vector(count, look); @@ -146,6 +149,14 @@ UnitTestResult test_talk_over(){ SceneMove::DONE, 6}, {"no quiet ends a talk before a battle", {.end_on_quiet = false}, repeat(QUIET, 30), SceneMove::DONE, -1}, {"a battle", {.end_on_quiet = false}, concat(repeat(QUIET, 6), {ScreenEvents{ScreenEvent::BATTLE_STARTED}}), SceneMove::BATTLE, 6}, + // Mom's Running Shoes scene (lab-B 2026-11-09 14:33): quiet, then + // the scene's closing fade. It ended at the fade's start and the + // next step's input landed in the fade. + {"a closing fade starts the quiet over", {}, + concat(concat(repeat(QUIET, 4), repeat(FADED, 3)), repeat(QUIET, 8)), + SceneMove::DONE, 12}, + {"a fade still down never ends it", {}, concat(repeat(QUIET, 3), repeat(FADED, 20)), SceneMove::DONE, -1}, + {"a fade is never calm", {}, concat(repeat(CALM, 10), repeat(CALM_FADED, 10)), SceneMove::DONE, -1}, }; for (const Row& row : rows){ TalkOver judge(row.rule); From 7c6e9bd4c41e6b74e8cad10d4b2c43d27cbca27c Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 14:49:51 -0800 Subject: [PATCH 21/64] Scene judges: a fade ends no quiet; log the screen before every step TalkOver counted a black frame as quiet overworld (BDSP reads it as no box, and it stays still), so Mom's Running Shoes scene ended as its closing fade went down and the next step's input landed in the fade (lab-B 2026-11-09 14:33). A look that shows a fade now starts the quiet and the calm over: a scene ends once every fade is back up, no box shows and the overworld has been quiet for TALK_OVER_QUIET. The look before each step now also says how the screen ended (judge_settle(): its last frame's events and how long they held), and the TableExecutor hands it to StepGuard::on_screen() for every step, interrupt or not, so a run log shows whether the scene had ended before the first input. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/AutoStory/Pokemon_SceneJudges.cpp | 14 +++- .../Pokemon/AutoStory/Pokemon_SceneJudges.h | 5 ++ .../AutoStory/Pokemon_StoryActions.cpp | 3 + .../Pokemon/AutoStory/Pokemon_StoryActions.h | 4 + .../AutoStory/Pokemon_StoryInterrupts.cpp | 66 +++++++++++++--- .../AutoStory/Pokemon_StoryInterrupts.h | 22 ++++++ .../Pokemon_StoryInterrupts_Tests.cpp | 75 +++++++++++++++++++ 7 files changed, 174 insertions(+), 15 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp index 628be668dc..b92a63e2a9 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp @@ -38,12 +38,17 @@ SceneMove TalkOver::look(const ScreenEvents& look, WallClock now){ m_calm_since = WallClock::max(); return SceneMove::BATTLE; } - if (fade_in(look) != WarpFade::NONE){ - m_fade = fade_in(look); + m_fade_showing = fade_in(look); + if (m_fade_showing != WarpFade::NONE){ + m_fade = m_fade_showing; } m_banner |= look.has(ScreenEvent::LOCATION_BANNER); const bool box = look.has(ScreenEvent::DIALOG_BOX); - const bool calm = !box && look.has(ScreenEvent::PLAYER_CAN_MOVE) && warped(); + // A fade is never calm: BDSP's overworld reads a black frame as no + // box, and black stays still, so a closing fade counted as quiet and + // ended Mom's scene as it went down (lab-B 2026-11-09 14:33). + const bool calm = !box && m_fade_showing == WarpFade::NONE && + look.has(ScreenEvent::PLAYER_CAN_MOVE) && warped(); const bool quiet = calm && look.has(ScreenEvent::SCREEN_STILL); if (!calm){ m_calm_since = WallClock::max(); @@ -73,6 +78,9 @@ std::string TalkOver::describe() const{ return "no fade or banner"; } std::string out = m_fade == WarpFade::NONE ? "" : warp_fade_name(m_fade); + if (m_fade != WarpFade::NONE){ + out += m_fade_showing == WarpFade::NONE ? " back up" : " still down"; + } if (m_banner){ out += out.empty() ? "banner read" : ", banner read"; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h index 704ecf9a86..908dcaa39c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h @@ -71,6 +71,9 @@ constexpr Milliseconds TALK_OVER_CALM = Milliseconds(15000); // When a talk or a scene is over, from looks alone. A look is a frame's // events: DIALOG_BOX, PLAYER_CAN_MOVE, SCREEN_STILL, a fade, // LOCATION_BANNER (the expected map's) and BATTLE_STARTED are read. +// It is over only once every fade has come back up, no box shows, and +// the overworld has been quiet (or calm) since: a look that shows a fade +// starts the quiet over, however still it is. class TalkOver{ public: explicit TalkOver(TalkOverRule rule = {}) @@ -86,7 +89,9 @@ class TalkOver{ private: TalkOverRule m_rule; + // The first fade seen, and the one the last look showed. WarpFade m_fade = WarpFade::NONE; + WarpFade m_fade_showing = WarpFade::NONE; bool m_banner = false; WallClock m_quiet_since = WallClock::max(); WallClock m_calm_since = WallClock::max(); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp index 349aa3e530..d09f78f553 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp @@ -87,6 +87,8 @@ void StepGuard::on_failure(const StoryStep&, const OperationFailedException&){} void StepGuard::on_interrupt(const StoryStep&, const InterruptCheck&){} +void StepGuard::on_screen(const StoryStep&, const ScreenSettle&){} + TableExecutor::TableExecutor(const StoryActionTable& table, StepGuard& guard) : m_table(table) @@ -133,6 +135,7 @@ std::optional TableExecutor::clear_interrupts(RunState& state, const St return std::nullopt; } InterruptCheck check = clear_story_interrupt(*m_interrupts, state, step); + m_guard.on_screen(step, check.screen); if (check.verdict.kind == InterruptKind::NONE){ return std::nullopt; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h index 9f66529814..e672b0df15 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h @@ -96,6 +96,10 @@ class StepGuard{ // A look before the step, or after it failed, found an interrupt and // cleared it or failed to (`check`): e.g. log it. virtual void on_interrupt(const StoryStep& step, const InterruptCheck& check); + // How the screen looked when the look before the step (or after it + // failed) ended, interrupt or not: e.g. log it, so a run log shows + // whether the scene before had ended before the step's first input. + virtual void on_screen(const StoryStep& step, const ScreenSettle& screen); }; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp index 32a14b42fa..8fe58620e9 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp @@ -5,6 +5,9 @@ */ #include +#include +#include +#include #include #include "Common/Cpp/Exceptions.h" #include "Pokemon_StoryInterrupts.h" @@ -75,30 +78,69 @@ bool may_open_a_battle(const ScreenLook& look, const InterruptVerdict& verdict){ // The look's verdict, looked at again while it is unsettled, up to // max_looks looks in all, or max_opening_looks while it may be a battle's -// opening; not again before a step that starts on it. -InterruptVerdict settled_verdict(const StoryInterrupts& interrupts, StoryStepKind step){ +// opening; not again before a step that starts on it. `screen` is how the +// last look ended. +InterruptVerdict settled_verdict(const StoryInterrupts& interrupts, StoryStepKind step, ScreenSettle& screen){ ScreenLook look = interrupts.look(true); InterruptVerdict verdict = classify_interrupt(look.log, look.window, interrupts.knobs); - if (interrupts.handlers.step_starts_on(step, InterruptKind::UNSETTLED)){ - return verdict; - } - for (size_t looks = 1; verdict.kind == InterruptKind::UNSETTLED; looks++){ - const size_t limit = may_open_a_battle(look, verdict) ? interrupts.max_opening_looks : interrupts.max_looks; - if (looks >= limit){ - break; + if (!interrupts.handlers.step_starts_on(step, InterruptKind::UNSETTLED)){ + for (size_t looks = 1; verdict.kind == InterruptKind::UNSETTLED; looks++){ + const size_t limit = may_open_a_battle(look, verdict) ? interrupts.max_opening_looks : interrupts.max_looks; + if (looks >= limit){ + break; + } + look = interrupts.look(false); + verdict = classify_interrupt(look.log, look.window, interrupts.knobs); } - look = interrupts.look(false); - verdict = classify_interrupt(look.log, look.window, interrupts.knobs); } + screen = judge_settle(look); return verdict; } } // namespace +ScreenSettle judge_settle(const ScreenLook& look){ + ScreenSettle out; + const std::optional last = look.log.last_frame(); + if (!last || *last < look.window.start){ + return out; + } + out.seen = true; + out.showing = look.log.showing(); + WallClock since = look.window.start; + for (const ScreenEventChange& change : look.log.changes()){ + if (change.time <= look.window.end){ + since = std::max(since, change.time); + } + } + const WallClock end = std::max(look.window.end, since); + out.quiet = std::chrono::duration_cast(end - since); + return out; +} + +bool is_settled(const ScreenSettle& settle){ + return settle.seen && + settle.showing.has(ScreenEvent::PLAYER_CAN_MOVE) && + !settle.showing.any_of({ScreenEvent::DIALOG_BOX, ScreenEvent::BATTLE_STARTED}) && + fade_in(settle.showing) == WarpFade::NONE; +} + +std::string describe(const ScreenSettle& settle){ + if (!settle.seen){ + return "no frame seen"; + } + const std::string quiet = std::format("quiet {:.1f} s", settle.quiet.count() / 1000.0); + if (is_settled(settle)){ + return "settled overworld (" + quiet + ")"; + } + return describe(settle.showing) + " showing (" + quiet + ")"; +} + + InterruptCheck clear_story_interrupt(const StoryInterrupts& interrupts, RunState& state, const StoryStep& step){ InterruptCheck out; - out.verdict = settled_verdict(interrupts, step.kind); + out.verdict = settled_verdict(interrupts, step.kind, out.screen); const InterruptKind kind = out.verdict.kind; if (kind == InterruptKind::NONE){ return out; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h index 1a43414580..2f7583c07f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h @@ -38,6 +38,7 @@ #include #include #include +#include #include #include "Pokemon_Interrupts.h" #include "Pokemon_ScreenEvents.h" @@ -113,8 +114,29 @@ struct StoryInterrupts{ }; +// How the screen looked at the end of a look: the line a run log needs to +// answer "had the scene ended before the step's first input?". +struct ScreenSettle{ + // Whether the look saw a frame at all. + bool seen = false; + // The events its last frame showed. + ScreenEvents showing = {}; + // How long the screen had shown them unchanged when the look ended. + Milliseconds quiet = Milliseconds(0); +}; +// The end of `look`: its last frame's events, and how long they held. +ScreenSettle judge_settle(const ScreenLook& look); +// Whether it ended on the overworld with no box, no fade and no battle. +bool is_settled(const ScreenSettle& settle); +// "settled overworld (quiet 0.3 s)", "black fade showing (quiet 0.1 s)", +// "no frame seen". +std::string describe(const ScreenSettle& settle); + + // What a look between steps found, and what clearing it came to. struct InterruptCheck{ + // How the screen looked when the look ended, judged or not. + ScreenSettle screen = {}; // NONE when nothing interrupted, or when the step starts on it. InterruptVerdict verdict = {}; // Failed when the look stayed unsettled, the kind had no handler, or diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp index 187a6b14a5..aaf2693940 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -433,6 +433,73 @@ UnitTestResult test_table_rejects(){ return true; } +// A guard that notes how the screen looked before each step. +class ScreenGuard : public StepGuard{ +public: + explicit ScreenGuard(FakeGame& game) + : m_game(game) + {} + virtual void on_screen(const StoryStep& step, const ScreenSettle& screen) override{ + m_game.trace.push_back("before " + step.name + ": " + describe(screen)); + } + +private: + FakeGame& m_game; +}; + +// The guard hears how the screen looked before every step, interrupt or +// not: the run log's answer to "had the scene ended before the input?". +UnitTestResult test_screen_before_each_step(){ + FakeGame game; + // A scene's closing fade still down: no battle comes, so the step + // fails unsettled, and the guard hears the fade was showing. + game.screens = {look_of({{0, WALK}, {100, BLACK}}, 300)}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.max_opening_looks = 2; + const StoryActionTable table = table_of(game, {}); + ScreenGuard guard(game); + TableExecutor executor(table, guard); + executor.set_interrupts(&interrupts); + RunState state; + StoryStep step = make(StoryStepKind::ROUTE, "by_the_counter"); + step.variant = "act"; + const Outcome faded = executor.run(state, step); + if (faded.succeeded()){ + return "Expected a step in a fade to fail unsettled, got " + to_string(faded); + } + game.screens = {quiet()}; + game.looks = 0; + const Outcome settled = executor.run(state, step); + if (!settled.succeeded()){ + return "Expected the step on a quiet screen to run, got " + to_string(settled); + } + return expect_trace(game, { + "look", "look again", "before by_the_counter: black fade showing (quiet 0.2 s)", + "look", "before by_the_counter: settled overworld (quiet 0.3 s)", "run by_the_counter", + }); +} + +UnitTestResult test_settle_of_a_look(){ + struct Row{ + const char* name; + ScreenLook look; + const char* expected; + }; + const std::vector rows = { + {"no frame", ScreenLook{}, "no frame seen"}, + {"a quiet overworld", quiet(), "settled overworld (quiet 0.3 s)"}, + {"a box", dialog(), "dialog box, player can move showing (quiet 0.2 s)"}, + {"a door's fade back up", black_unsettled(), "settled overworld (quiet 0.3 s)"}, + }; + for (const Row& row : rows){ + const std::string got = describe(judge_settle(row.look)); + if (got != row.expected){ + return std::format("{}: expected \"{}\", got \"{}\"", row.name, row.expected, got); + } + } + return true; +} + struct StoryInterruptsInput{ std::string_view name; @@ -543,6 +610,14 @@ const StoryInterruptsCase STORY_INTERRUPTS_CASES[] = { .input = {.name = "table: one handler a kind that can be cleared", .test = test_table_rejects}, .expectation = {.description = "rejects NONE, UNSETTLED and a second handler"}, }, + { + .input = {.name = "the screen before each step, for the log", .test = test_screen_before_each_step}, + .expectation = {.description = "a fade still down is told, and fails unsettled; a quiet overworld is settled"}, + }, + { + .input = {.name = "how a look ended", .test = test_settle_of_a_look}, + .expectation = {.description = "the last frame's events and how long they held"}, + }, }; } // namespace From 8c007f53306bff4ba4a22527c14d44226622bf6a Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 14:51:12 -0800 Subject: [PATCH 22/64] FRLG AutoStory: log the screen before every step Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp | 4 ++++ .../Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h | 4 +++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp index 83409af59a..5930c46d2e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp @@ -105,6 +105,10 @@ void InterruptLogGuard::on_interrupt(const Pokemon::StoryStep& step, const Pokem ), cleared ? COLOR_ORANGE : COLOR_RED); } +void InterruptLogGuard::on_screen(const Pokemon::StoryStep& step, const Pokemon::ScreenSettle& screen){ + m_logger.log(std::format("[Screen] before {}: {}", step.name, Pokemon::describe(screen))); +} + } // namespace PokemonFRLG diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h index e9b91d2686..63336a8b2c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h @@ -92,7 +92,8 @@ class ConsoleScreenLook{ }; // The console's guard: a failed step fails it, as before; each interrupt -// found between steps is logged, cleared or not. +// found between steps is logged, cleared or not, and how the screen looked +// before every step. class InterruptLogGuard : public Pokemon::StepGuard{ public: explicit InterruptLogGuard(Logger& logger) @@ -100,6 +101,7 @@ class InterruptLogGuard : public Pokemon::StepGuard{ {} virtual void on_interrupt(const Pokemon::StoryStep& step, const Pokemon::InterruptCheck& check) override; + virtual void on_screen(const Pokemon::StoryStep& step, const Pokemon::ScreenSettle& screen) override; private: Logger& m_logger; From 2b8b70e95a72abe67c0d66fb4b4edd0c1d986182 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 15:20:21 -0800 Subject: [PATCH 23/64] FRLG: red tests for a battle won in a dark cave Console B, 2026-11-09, 00.28 hiker_lenny in Rock Tunnel without Flash: the battle was won, and the dark overworld after it read as the battle's text box with no HP box. The loop held B for an evolution three times for 20 s, then failed with "no battle screen and no START menu for 60 s after the battle". The sim now plays the battle loop's end after each trainer's battle (battle_end_on_sim(), on EvolutionHold and BattleEndWatch), with the dark cave's overworld when the map is dark. New: a decisions test, an 00.28 dark sim test, and a DARK_CAVE fault sweep. All fail until the fix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Overworld/PokemonFRLG_OverworldSim.cpp | 10 ++- .../Overworld/PokemonFRLG_OverworldSim.h | 5 ++ .../AutoStory/PokemonFRLG_AutoStoryBattle.cpp | 8 +-- .../PokemonFRLG_AutoStoryBattleDecisions.h | 7 ++ .../PokemonFRLG_AutoStoryFaultSweep_Tests.cpp | 46 +++++++++++++ .../PokemonFRLG_AutoStoryLavender_Tests.cpp | 10 +++ .../PokemonFRLG_AutoStoryParty_Tests.cpp | 40 +++++++++++ .../AutoStory/PokemonFRLG_AutoStoryRowSim.cpp | 66 ++++++++++++++++++- 8 files changed, 183 insertions(+), 9 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index 9d65da8a27..3d7bcfdbd6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -736,8 +736,14 @@ void OverworldSimWalker::clear(const Interrupt& interrupt){ } return; } - if (m_sim.close_message() && m_rules.fight_trainer_after_message){ - m_sim.handle_battle(SimBattleChoice::FIGHT); + if (!m_sim.close_message() || !m_rules.fight_trainer_after_message){ + return; + } + m_sim.handle_battle(SimBattleChoice::FIGHT); + if (m_rules.trainer_battle_end){ + if (const std::string failure = m_rules.trainer_battle_end(m_sim); !failure.empty()){ + fail(failure); + } } } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index c84653ded1..0e95c34368 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -28,6 +28,7 @@ #ifndef PokemonAutomation_PokemonFRLG_OverworldSim_H #define PokemonAutomation_PokemonFRLG_OverworldSim_H +#include #include #include #include @@ -415,6 +416,10 @@ struct SimWalkerRules{ // and the player was found again at a wall 5 tiles off (console B, // 2026-11-09, 00.28). bool whole_leg_in_dark = true; + // The end of a trainer's battle the walker fought, as the story's + // battle loop takes it on the screen the sim shows after it: its + // failure, or empty. Not set: the battle just ends. + std::function trainer_battle_end = nullptr; }; // OverworldWalkSteps::turn_to() on `sim`, which reads the facing on the diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp index 9d5e93b652..47c39e1037 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp @@ -62,9 +62,6 @@ constexpr Milliseconds OVERWORLD_CHECK = 3000ms; // No battle menu or HP box this long after a battle was seen: there was // none (console B, 2026-11-01, Viridian Forest's north gate mat). constexpr Milliseconds NOT_A_BATTLE = 15000ms; -// An evolution's animation, with no presses: as long as exit_wild_battle() -// (PokemonFRLG_Navigation.cpp) waits for one. -constexpr Milliseconds EVOLUTION = 20000ms; // Text and the move learn prompts after a battle, on the overworld. constexpr Milliseconds AFTER_BATTLE_TEXT = 60000ms; // The move list to fade in after "Delete a move?", and its cursor to move. @@ -427,11 +424,12 @@ class BattleLoop{ m_last_press = now; } - // Nothing pressed while the screen may be an evolution, up to EVOLUTION. + // Nothing pressed while the screen may be an evolution, up to + // EvolutionHold::MAX_HOLD. void wait_out_evolution(){ const WallClock start = current_time(); bool holds = true; - while (holds && current_time() - start < EVOLUTION){ + while (holds && current_time() - start < EvolutionHold::MAX_HOLD){ pbf_wait(m_context, POLL); m_context.wait_for_all_requests(); VideoSnapshot screen = m_console.video().snapshot(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h index 5fb5f5a6cc..f08ed2442b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h @@ -87,6 +87,9 @@ struct BattleTextScreen{ bool arrow = false; // A YES/NO box. bool yes_no = false; + // The overworld of a cave dark without Flash (dark_cave_screen()), + // whose black reads as the text box. + bool dark_cave = false; }; // Answer to an in-battle prompt dialogue. @@ -193,6 +196,10 @@ class BattleDecisions{ // battle loop's B presses). class EvolutionHold{ public: + // The longest one hold lasts: as long as exit_wild_battle() + // (PokemonFRLG_Navigation.cpp) waits for an evolution. + static constexpr Milliseconds MAX_HOLD = std::chrono::milliseconds(20000); + explicit EvolutionHold(PartyMember& lead); // The loop took a turn: only one that attacked can end the battle in a diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.cpp index 12ac3a535b..58d2d9e891 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.cpp @@ -13,6 +13,10 @@ * land encounters, over GAME_ODDS_SEEDS seeds (00.28's Rock Tunnel). * - LATE_FADE: every warp's fade ends LATE_FADE later than the sim's * usual (00.27's warp to Cerulean City). + * - DARK_CAVE: the caves without Flash dark (DARK_MAPS), so each + * battle there ends on the dark cave's overworld, with no wild + * battles and with them at the game's odds (00.28 hiker_lenny, lab-B + * 2026-11-09). * * Not swept here: a missed fade, which needs a knob in OverworldSim; a * battle's opening at a step's start, which needs one in OverworldStepSim; @@ -60,6 +64,7 @@ enum class FaultClass{ SCENE_END_POSE, WILD_BATTLES, LATE_FADE, + DARK_CAVE, // Not swept yet: the measured movement table's lost taps. LOST_TAP, }; @@ -71,6 +76,8 @@ const char* fault_class_name(FaultClass fault){ return "wild battles at the game's odds"; case FaultClass::LATE_FADE: return "late warp fade"; + case FaultClass::DARK_CAVE: + return "dark cave without Flash"; case FaultClass::LOST_TAP: return "lost tap"; } @@ -96,6 +103,11 @@ const std::map STORY_ENCOUNTER_RATES{ // (Mt. Moon B2F, console B, 2026-11-03). const std::set WILD_FLOOR_MAPS{"MtMoon_1F", "MtMoon_B1F", "MtMoon_B2F"}; constexpr unsigned GAME_ODDS_SEEDS = 30; +// The caves the story walks dark: no Flash before Lavender Town. +const std::set DARK_MAPS{"RockTunnel_1F", "RockTunnel_B1F"}; +// Seeds of wild battles at the game's odds in the dark, after a run +// with none. +constexpr unsigned DARK_CAVE_SEEDS = 10; // How much later than SimTiming's a late fade ends: the new map shows // this long after the usual. constexpr Milliseconds LATE_FADE = 1500ms; @@ -333,6 +345,37 @@ UnitTestResult sweep_late_fade(Logger& logger, const StoryCheckpoint& row, const return sweep_result(logger, FaultClass::LATE_FADE, row.id, 1, failures); } +// Row `row` with DARK_MAPS dark: once with no wild battles, then with +// them at the game's odds from DARK_CAVE_SEEDS seeds. Each trainer's +// battle there ends on the dark overworld (battle_end_on_sim() in +// PokemonFRLG_AutoStoryRowSim.cpp); wild ones are run from, after which +// nothing is held for an evolution. A row that walks no dark cave is +// not swept. +UnitTestResult sweep_dark_cave(Logger& logger, const StoryCheckpoint& row, const RowRun& clean){ + const bool walks_dark = DARK_MAPS.contains(clean.end.map) || std::any_of(clean.before.begin(), clean.before.end(), [](const auto& before){ + return DARK_MAPS.contains(before.second.map); + }); + if (!walks_dark){ + logger.log(std::format("Fault sweep {}: not swept, the row walks no dark cave.", row.id)); + return true; + } + std::vector failures; + for (unsigned seed = 0; seed <= DARK_CAVE_SEEDS; seed++){ + SimScript script; + script.dark_maps = DARK_MAPS; + if (seed > 0){ + script.encounter_rates = STORY_ENCOUNTER_RATES; + script.encounter_seed = seed; + script.wild_floor_maps = WILD_FLOOR_MAPS; + } + const std::string stopped = differs(run_row(row, script, {}, clean.scripted), clean); + if (!stopped.empty()){ + failures.push_back({"", seed == 0 ? std::string("no wild battles") : std::format("seed {}", seed), stopped}); + } + } + return sweep_result(logger, FaultClass::DARK_CAVE, row.id, DARK_CAVE_SEEDS + 1, failures); +} + // A fault class swept over row `row` (empty in FAULT_SWEEP_CASES: each // row with a start). struct FaultSweepInput{ @@ -396,6 +439,8 @@ class Test_AutoStoryFaultSweep : public UnitTest{ return sweep_wild_battles(logger, m_row, clean); case FaultClass::LATE_FADE: return sweep_late_fade(logger, m_row, clean); + case FaultClass::DARK_CAVE: + return sweep_dark_cave(logger, m_row, clean); case FaultClass::LOST_TAP: break; } @@ -413,6 +458,7 @@ const FaultSweepCase FAULT_SWEEP_CASES[] = { {.input = {.fault = FaultClass::SCENE_END_POSE}, .expectation = {}}, {.input = {.fault = FaultClass::WILD_BATTLES}, .expectation = {}}, {.input = {.fault = FaultClass::LATE_FADE}, .expectation = {}}, + {.input = {.fault = FaultClass::DARK_CAVE}, .expectation = {}}, }; void add_tests_AutoStoryFaultSweep(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp index 2262b6a2cf..73b5f010be 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp @@ -245,6 +245,15 @@ UnitTestResult test_b1f_martha_after_row38_battle(Logger&){ // Rock Tunnel has no Flash: both floors are dark. const std::set ROCK_TUNNEL_DARK{StoryTable::ROCK_TUNNEL_1F, StoryTable::ROCK_TUNNEL_B1F}; +// Regression: console B, 2026-11-09, 00.28 hiker_lenny: won, and the dark +// overworld after it was taken for an evolution until fight_battle() gave +// up. 00.28 dark: every trainer's battle ends on the dark cave's overworld. +UnitTestResult test_rock_tunnel_dark_battle_ends(Logger&){ + SimScript script; + script.dark_maps = ROCK_TUNNEL_DARK; + return row_on_sim("00.28", script, {ROCK_TUNNEL_TRAINERS}, MapPosition{StoryTable::ROUTE10, {8, 58}}); +} + // below_martha_line as `legs` from Winston's tile (29, 37) on `sim`, by the // walker with `rules`: the failure, or empty if it ended on (16, 35). std::string walk_below_martha(OverworldSim& sim, const std::vector& legs, const SimWalkerRules& rules){ @@ -542,6 +551,7 @@ UnitTestResult test_save_places(Logger&){ const AutoStoryLavenderCase AUTO_STORY_LAVENDER_CASES[] = { {.input = {"00.28 the tree, Rock Tunnel's nine trainers, out of its south mouth", test_rock_tunnel_row}, .expectation = {}}, {.input = {"00.28 a wild battle mid-leg in the tunnel", test_rock_tunnel_wild_battles}, .expectation = {}}, + {.input = {"00.28 dark: each trainer's battle ends on the dark cave's overworld", test_rock_tunnel_dark_battle_ends}, .expectation = {}}, {.input = {"00.28 a tile off after each open leg", test_rock_tunnel_tile_off}, .expectation = {}}, {.input = {"00.28 B1F row 37 with a wild battle every 10 to 14 steps", test_b1f_row37_battles_every_12}, .expectation = {}}, {.input = {"00.28 a wild battle every 7 to 25 steps, 12 seeds", test_rock_tunnel_frequent_battles}, .expectation = {}}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp index 0219b7b703..8694afd9e4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_Tests.cpp @@ -616,6 +616,45 @@ UnitTestResult test_run_then_overworld(Logger&){ return "START never looked for the overworld in the dark cave."; } +// Regression: console B, 2026-11-09, 00.28 hiker_lenny in Rock Tunnel +// without Flash: the battle won with a move, then the dark cave's +// overworld, black but for the lit circle on the player, read as the +// text box with no HP box. The loop held B for an evolution three times +// for 20 s, and gave up: "no battle screen and no START menu for 60 s +// after the battle". A dark cave's overworld is no evolution: START looks +// for the overworld within seconds of the last HP box. +UnitTestResult test_trainer_win_then_dark_cave(Logger&){ + const BattleTextScreen defeated{.text_box = true, .hp_box = true, .arrow = true, .yes_no = false}; + const BattleTextScreen dark_cave{.text_box = true, .hp_box = false, .arrow = false, .yes_no = false, .dark_cave = true}; + std::vector polls{{.ms = 0, .screen = defeated}}; + for (int ms = 300; ms <= 1500; ms += 300){ + polls.push_back({.ms = ms, .screen = defeated}); + } + for (int ms = 1800; ms <= 60000; ms += 300){ + polls.push_back({.ms = ms, .screen = dark_cave}); + } + + Supplies supplies; + EvolutionHold hold(supplies.lead); + BattleEndWatch watch; + const WallClock start = current_time(); + hold.turn_taken(TurnChoice::MOVE); + for (const LoopPoll& poll : polls){ + const WallClock now = start + std::chrono::milliseconds(poll.ms); + if (hold.holds(poll.screen)){ + return std::format("Held B for an evolution at {} ms, on the dark cave's overworld.", poll.ms); + } + watch.seen(poll.screen.hp_box || poll.screen.yes_no ? BattleSeen::BATTLE : BattleSeen::NONE, now); + if (watch.check_overworld(now)){ + if (poll.ms > 5000){ + return std::format("START first looked for the overworld at {} ms.", poll.ms); + } + return true; + } + } + return "START never looked for the overworld in the dark cave."; +} + // START only once the battle is gone for a while, and then not at every // poll; A and B blind for at most 30 s since the last battle menu. UnitTestResult test_end_watch_timing(Logger&){ @@ -923,6 +962,7 @@ const AutoStoryPartyTestCase AUTO_STORY_PARTY_CASES[] = { {.input = {.name = "summary members: fewer moves, unread PP, strongest attack", .body = test_summary_members}, .expectation = {.description = "handles party members with partial move data"},}, {.input = {.name = "no B during an evolution", .body = test_no_b_during_evolution}, .expectation = {.description = "prevents cancelling evolution sequence"},}, {.input = {.name = "RUN, then a dark cave: no evolution wait, START soon", .body = test_run_then_overworld}, .expectation = {.description = "handles post-battle overworld transition in dark cave"},}, + {.input = {.name = "a trainer beaten, then a dark cave without Flash: no evolution wait, START soon", .body = test_trainer_win_then_dark_cave}, .expectation = {.description = "takes a dark cave's overworld after a win for no evolution"},}, {.input = {.name = "battle end: START after the battle is gone, A and B for 30 s at most", .body = test_end_watch_timing}, .expectation = {.description = "verifies timing constraints on battle end loop"},}, {.input = {.name = "attacks by matchup: Bite on the rival's Bulbasaur and Misty", .body = test_attack_by_matchup}, .expectation = {.description = "selects optimal attack move based on type matchup"},}, {.input = {.name = "attacks against an unknown foe: the plan's order", .body = test_attack_unknown_foe}, .expectation = {.description = "falls back to default move preference order against unknown foe"},}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp index a739d0b9e4..c39aac361c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp @@ -14,6 +14,7 @@ #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryBattleDecisions.h" #include "PokemonFRLG_AutoStoryRowSim.h" namespace PokemonAutomation{ @@ -378,6 +379,62 @@ Pokemon::StoryAction OverworldStepSim::action(StoryActionId id){ }); } +namespace{ + +// fight_battle()'s end on the overworld the sim shows after a battle won +// with a move: the battle loop's polls replayed through its EvolutionHold +// and BattleEndWatch, as BattleLoop::step() takes them. The overworld of a +// dark cave reads as the battle's text box with no HP box (console B, +// 2026-11-09, 00.28 hiker_lenny: three 20 s holds for an evolution, then +// "no battle screen and no START menu for 60 s after the battle"). Empty +// once START would look for the overworld, else the loop's failure. +std::string battle_end_on_sim(const OverworldSim& sim){ + constexpr Milliseconds POLL(300); + // The battle as the loop saw it: a Potion turn's bag, where START + // looked for the overworld and found none (as hiker_lenny's turns 2, + // 4 and 5), then the last turn's text up to the win. + constexpr Milliseconds BAG(4000); + constexpr Milliseconds LAST_TEXT(10000); + // The loop gives up on the overworld after this (BattleEndWatch's + // NO_OVERWORLD); a little longer, so its failure shows. + constexpr Milliseconds GIVE_UP(65000); + const WallClock start{}; + Supplies supplies; + EvolutionHold hold(supplies.lead); + BattleEndWatch watch; + watch.seen(BattleSeen::MENU, start); + Milliseconds at(0); + for (; at <= BAG; at += POLL){ + watch.seen(BattleSeen::NONE, start + at); + if (watch.check_overworld(start + at)){ + break; + } + } + hold.turn_taken(TurnChoice::MOVE); + for (; at <= LAST_TEXT; at += POLL){ + watch.seen(BattleSeen::BATTLE, start + at); + } + const bool dark = sim.state().dark; + const BattleTextScreen overworld{.text_box = dark, .hp_box = false, .arrow = false, .yes_no = false, .dark_cave = dark}; + for (; at <= LAST_TEXT + GIVE_UP; at += POLL){ + if (watch.overworld_lost(start + at)){ + return "fight_battle(): no battle screen and no START menu for 60 s after the battle."; + } + if (hold.holds(overworld)){ + hold.held(EvolutionHold::MAX_HOLD, false); + at += EvolutionHold::MAX_HOLD; + continue; + } + watch.seen(BattleSeen::NONE, start + at); + if (watch.check_overworld(start + at)){ + return ""; + } + } + return "fight_battle(): START never looked for the overworld."; +} + +} // namespace + // A ROUTE or LEGS by the sim's walker, fighting a trainer who sees the // player on the way. std::string OverworldStepSim::walk(const StoryStep& step){ @@ -387,7 +444,9 @@ std::string OverworldStepSim::walk(const StoryStep& step){ return ""; } const RoutePlanning planning{.maps = &story_maps(), .costs = story_route_costs(), .start = MapPosition{m_at.map, m_at.tile}, .label = step.name}; - const std::string failure = route ? OverworldSimWalker(m_sim).run(*route, planning) : "no legs."; + SimWalkerRules rules; + rules.trainer_battle_end = battle_end_on_sim; + const std::string failure = route ? OverworldSimWalker(m_sim, rules).run(*route, planning) : "no legs."; m_at = route ? StoryPose{route->back().end.map, route->back().end.point, route->back().facing_after} : m_at; return failure; } @@ -443,11 +502,14 @@ std::string OverworldStepSim::cut(const StoryStep& step){ } // A battle from the trainer's message, which must be up, ending where the -// table says. +// table says, the battle loop's end played on the overworld after it. std::string OverworldStepSim::battle(const StoryStep& step){ if (!m_sim.close_message() || m_sim.handle_battle(SimBattleChoice::FIGHT) != SimBattleEnd::ENDED){ return "no_battle."; } + if (const std::string failure = battle_end_on_sim(m_sim); !failure.empty()){ + return failure; + } m_at = *story_pose(*step.pose_after); if (!(m_sim.state().position == MapPosition{m_at.map, m_at.tile})){ return "expected " + to_string(MapPosition{m_at.map, m_at.tile}) + "."; From 710e5de9ba1ae8bef94d772f19e9b1429f4b2fa0 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 15:23:49 -0800 Subject: [PATCH 24/64] FRLG: a dark cave's overworld ends the battle loop's evolution wait After a battle won in Rock Tunnel without Flash, the dark overworld read as the battle's text box with no HP box, which EvolutionHold took for "is evolving!". The loop now reads a dark cave's screen (dark_cave_screen()) as no battle screen and holds nothing on it, so START looks for the overworld within seconds, as after any battle. An evolution's scene keeps its text box in the bottom corners, which a dark cave's are not. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp | 7 +++++++ .../AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp | 2 +- .../AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h | 4 +++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp index 47c39e1037..6d3cb3d36a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp @@ -22,6 +22,7 @@ #include "VideoGames/PokemonFRLG/Inference/PokemonFRLG_BattleScreenDetector.h" #include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_PartyMenuDetector.h" #include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_SummaryMovesReader.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" #include "PokemonFRLG_AutoStoryActions.h" @@ -107,6 +108,11 @@ BattleScreen read_battle_screen(const ImageViewRGB32& screen, bool confirmed){ if (battle_yes_no_shows(screen)){ return BattleScreen::LEARN; } + // A dark cave's overworld after the battle: its black reads as the + // text box (console B, 2026-11-09, Rock Tunnel). + if (OverworldWalkSteps::dark_cave_screen(screen)){ + return BattleScreen::NONE; + } if (!confirmed && !BattleScreenDetector(COLOR_RED).detect(screen)){ return BattleScreen::NONE; } @@ -125,6 +131,7 @@ BattleTextScreen read_text_screen(const ImageViewRGB32& screen){ .hp_box = BattleScreenDetector(COLOR_RED).detect(screen), .arrow = AdvanceBattleDialogDetector(COLOR_RED).detect(screen), .yes_no = battle_yes_no_shows(screen) || yes_no_cursor(screen).has_value(), + .dark_cave = OverworldWalkSteps::dark_cave_screen(screen), }; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp index 57fc597e03..d8d8ed4fe3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.cpp @@ -509,7 +509,7 @@ void EvolutionHold::turn_taken(TurnChoice choice){ } bool EvolutionHold::holds(const BattleTextScreen& screen) const{ - return m_attacked && m_held < EVOLUTION_HOLDS && screen.text_box && !screen.hp_box && !screen.arrow && !screen.yes_no; + return m_attacked && m_held < EVOLUTION_HOLDS && screen.text_box && !screen.hp_box && !screen.arrow && !screen.yes_no && !screen.dark_cave; } void EvolutionHold::held(Milliseconds held, bool lead_fainted){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h index f08ed2442b..6d63a5ecf6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattleDecisions.h @@ -208,7 +208,9 @@ class EvolutionHold{ // Whether `screen` may be an evolution: after a turn that attacked (not // after RUN: console B, 2026-11-03, a minute without B after "Got away // safely!"), the text box with no HP box and no arrow or YES/NO, as - // "What? is evolving!" shows through the animation. Nothing + // "What? is evolving!" shows through the animation; not a + // dark cave's overworld, whose black reads as the text box (console B, + // 2026-11-09, 00.28 hiker_lenny: three holds, then a stop). Nothing // is pressed while it shows, for at most EVOLUTION_HOLDS in all in a // battle, in case it is something else. bool holds(const BattleTextScreen& screen) const; From db14a253f04cb42e0adfd27ddff3c780dd3ba19d Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 15:26:14 -0800 Subject: [PATCH 25/64] FRLG: keep the battle loop and the sim walker within the file limit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Overworld/PokemonFRLG_OverworldSim.cpp | 7 ++----- .../Overworld/PokemonFRLG_OverworldSim.h | 6 ++++-- .../AutoStory/PokemonFRLG_AutoStoryBattle.cpp | 13 ++++--------- 3 files changed, 10 insertions(+), 16 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index 3d7bcfdbd6..f2e590e288 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -736,11 +736,8 @@ void OverworldSimWalker::clear(const Interrupt& interrupt){ } return; } - if (!m_sim.close_message() || !m_rules.fight_trainer_after_message){ - return; - } - m_sim.handle_battle(SimBattleChoice::FIGHT); - if (m_rules.trainer_battle_end){ + if (m_sim.close_message() && m_rules.fight_trainer_after_message){ + m_sim.handle_battle(SimBattleChoice::FIGHT); if (const std::string failure = m_rules.trainer_battle_end(m_sim); !failure.empty()){ fail(failure); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index 0e95c34368..0db86f8980 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -418,8 +418,10 @@ struct SimWalkerRules{ bool whole_leg_in_dark = true; // The end of a trainer's battle the walker fought, as the story's // battle loop takes it on the screen the sim shows after it: its - // failure, or empty. Not set: the battle just ends. - std::function trainer_battle_end = nullptr; + // failure, or empty. By default the battle just ends. + std::function trainer_battle_end = [](const OverworldSim&){ + return std::string(); + }; }; // OverworldWalkSteps::turn_to() on `sim`, which reads the facing on the diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp index 6d3cb3d36a..e01867804f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryBattle.cpp @@ -100,7 +100,8 @@ const char* screen_name(BattleScreen screen){ } // Until `confirmed`, the battle text box alone counts for nothing: it also -// reads on the black below a small indoor map. +// reads on the black below a small indoor map. Nor ever on a dark cave's +// overworld after the battle (console B, 2026-11-09, Rock Tunnel). BattleScreen read_battle_screen(const ImageViewRGB32& screen, bool confirmed){ if (BattleMenuDetector(COLOR_RED).detect(screen)){ return BattleScreen::MENU; @@ -108,12 +109,7 @@ BattleScreen read_battle_screen(const ImageViewRGB32& screen, bool confirmed){ if (battle_yes_no_shows(screen)){ return BattleScreen::LEARN; } - // A dark cave's overworld after the battle: its black reads as the - // text box (console B, 2026-11-09, Rock Tunnel). - if (OverworldWalkSteps::dark_cave_screen(screen)){ - return BattleScreen::NONE; - } - if (!confirmed && !BattleScreenDetector(COLOR_RED).detect(screen)){ + if ((!confirmed && !BattleScreenDetector(COLOR_RED).detect(screen)) || OverworldWalkSteps::dark_cave_screen(screen)){ return BattleScreen::NONE; } if (AdvanceBattleDialogDetector(COLOR_RED).detect(screen)){ @@ -431,8 +427,7 @@ class BattleLoop{ m_last_press = now; } - // Nothing pressed while the screen may be an evolution, up to - // EvolutionHold::MAX_HOLD. + // Nothing pressed while the screen may be an evolution, up to MAX_HOLD. void wait_out_evolution(){ const WallClock start = current_time(); bool holds = true; From 9b00e533402494806a042b2521b3d5c6c8dd2cdb Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 15:41:40 -0800 Subject: [PATCH 26/64] Story interrupts: red tests for a step that starts on the Switch HOME menu lab-B 2026-11-09 15:31: BDSP AutoStory started with the game closed; the look before the save said "settled overworld", X went to HOME and the next step walked east 22 tiles on it. Adds ScreenEvent::SWITCH_HOME_MENU and the cases: told as HOME, the step fails as game_not_running before any input, and the segment neither recovers nor reloads. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_ScreenEvents.cpp | 1 + .../Pokemon/AutoStory/Pokemon_ScreenEvents.h | 3 +- .../Pokemon_StoryInterrupts_Tests.cpp | 97 +++++++++++++++++++ 3 files changed, 100 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp index e80ed6161f..b796c50e69 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp @@ -25,6 +25,7 @@ const char* screen_event_name(ScreenEvent event){ case ScreenEvent::BATTLE_ENDED: return "battle ended"; case ScreenEvent::PLAYER_CAN_MOVE: return "player can move"; case ScreenEvent::SCREEN_STILL: return "screen still"; + case ScreenEvent::SWITCH_HOME_MENU: return "Switch HOME menu"; } return "?"; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h index cd633e0f60..66e5a1384c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h @@ -46,9 +46,10 @@ enum class ScreenEvent : uint8_t{ BATTLE_ENDED, // A battle's closing screen. PLAYER_CAN_MOVE, // The overworld with the player in control. SCREEN_STILL, // The screen barely changed since the frame before. + SWITCH_HOME_MENU, // The Switch's HOME menu: the game is not on the screen. }; // How many ScreenEvent values there are. -constexpr size_t SCREEN_EVENT_COUNT = 10; +constexpr size_t SCREEN_EVENT_COUNT = 11; // "dialog box", for the log. const char* screen_event_name(ScreenEvent event); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp index aaf2693940..f8d0ae445c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -19,6 +19,7 @@ #include "CommonFramework/Exceptions/OperationFailedException.h" #include "Pokemon_StoryActions.h" #include "Pokemon_StoryInterrupts.h" +#include "Pokemon_StorySegments.h" #include "Pokemon_AutoStory_Tests.h" namespace PokemonAutomation{ @@ -41,6 +42,8 @@ const ScreenEvents WHITE{ScreenEvent::FADE_WHITE}; const ScreenEvents BLACK{ScreenEvent::FADE_BLACK}; const ScreenEvents BATTLE{ScreenEvent::BATTLE_STARTED}; const ScreenEvents BANNER{ScreenEvent::LOCATION_BANNER, ScreenEvent::PLAYER_CAN_MOVE}; +// The Switch's HOME menu: the game is not running. +const ScreenEvents HOME{ScreenEvent::SWITCH_HOME_MENU}; // A look at `frames`, judged up to `until_ms`. ScreenLook look_of(const std::vector& frames, int until_ms){ @@ -83,6 +86,10 @@ ScreenLook black_unsettled(){ ScreenLook white_settled(){ return look_of({{0, WALK}, {100, WHITE}, {700, WALK}, {10000, WALK}}, 10000); } +// The HOME menu, still: the program started with the game closed. +ScreenLook home_menu(){ + return look_of({{0, HOME}, {300, HOME}}, 300); +} // The fake game: the screen its looks show, one per look and then the @@ -479,6 +486,86 @@ UnitTestResult test_screen_before_each_step(){ }); } +// The program started on the HOME menu (lab-B 2026-11-09 15:31: "before +// save: settled overworld", then X on HOME and a 22-tile walk on it). The +// screen is told as HOME and the step fails at once, before any input, +// and before a step that starts on a battle's opening too. +UnitTestResult test_home_menu_before_a_step(){ + for (StoryStepKind kind : {StoryStepKind::SAVE, StoryStepKind::ROUTE, StoryStepKind::BATTLE}){ + FakeGame game; + game.screens = {home_menu()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers.starts_on(StoryStepKind::BATTLE, InterruptKind::TRAINER_SIGHT); + const StoryActionTable table = table_of(game, {}); + ScreenGuard guard(game); + TableExecutor executor(table, guard); + executor.set_interrupts(&interrupts); + RunState state; + StoryStep step = make(kind, "save"); + step.variant = "act"; + const Outcome outcome = executor.run(state, step); + if (to_string(outcome) != "game_not_running: the game is not running: the Switch HOME menu is showing"){ + return "Expected the step on HOME to fail as game_not_running, got " + to_string(outcome); + } + if (UnitTestResult trace = expect_trace(game, {"look", "before save: Switch HOME menu (quiet 0.3 s)"}); trace.result != UnitTestResult::PASSED){ + return trace; + } + } + return true; +} + +// A checkpoint that fails on the HOME menu is neither recovered in place +// nor reloaded: every press would go to the console's menus. +UnitTestResult test_home_menu_stops_the_segment(){ + std::vector trace; + CheckpointSpec spec; + spec.id = "00.03"; + spec.build = [&trace]{ + Checkpoint checkpoint; + checkpoint.id = "00.03"; + Event save; + save.name = "save"; + save.act = [&trace](RunState&){ + trace.push_back("save"); + return outcome_failed("game_not_running", "the game is not running: the Switch HOME menu is showing"); + }; + Recovery wait; + wait.kind = RecoveryKind::WAIT; + wait.prepare = [&trace](RunState&){ + trace.push_back("recover"); + return outcome_ok(); + }; + save.recoveries.push_back(std::move(wait)); + checkpoint.events.push_back(std::move(save)); + return checkpoint; + }; + Segment segment; + segment.id = "00"; + segment.checkpoints.push_back(std::move(spec)); + SegmentHooks hooks; + hooks.reload = [&trace](RunState&){ + trace.push_back("reload"); + return outcome_ok(); + }; + hooks.recover = [&trace](RunState&, const std::string&){ + trace.push_back("recover in place"); + return outcome_ok(); + }; + RunState state; + const SegmentReport report = run_segment(state, segment, SegmentRange{}, SegmentPolicy{.recoveries_per_event = 2}, hooks); + if (report.completed || report.failure.failure != "game_not_running" || report.reloads != 0){ + return "Expected the segment to stop on game_not_running with no reload, got " + to_string(report.failure); + } + if (trace != std::vector{"save"}){ + std::string got; + for (const std::string& line : trace){ + got += " " + line; + } + return "Expected the save tried once and nothing else, got:" + got; + } + return true; +} + UnitTestResult test_settle_of_a_look(){ struct Row{ const char* name; @@ -490,6 +577,8 @@ UnitTestResult test_settle_of_a_look(){ {"a quiet overworld", quiet(), "settled overworld (quiet 0.3 s)"}, {"a box", dialog(), "dialog box, player can move showing (quiet 0.2 s)"}, {"a door's fade back up", black_unsettled(), "settled overworld (quiet 0.3 s)"}, + {"the HOME menu", home_menu(), "Switch HOME menu (quiet 0.3 s)"}, + {"HOME read as a quiet overworld too", look_of({{0, ScreenEvents{ScreenEvent::SWITCH_HOME_MENU, ScreenEvent::PLAYER_CAN_MOVE}}}, 300), "Switch HOME menu (quiet 0.3 s)"}, }; for (const Row& row : rows){ const std::string got = describe(judge_settle(row.look)); @@ -618,6 +707,14 @@ const StoryInterruptsCase STORY_INTERRUPTS_CASES[] = { .input = {.name = "how a look ended", .test = test_settle_of_a_look}, .expectation = {.description = "the last frame's events and how long they held"}, }, + { + .input = {.name = "the HOME menu before a step", .test = test_home_menu_before_a_step}, + .expectation = {.description = "told as HOME; game_not_running before any input"}, + }, + { + .input = {.name = "the HOME menu stops the segment", .test = test_home_menu_stops_the_segment}, + .expectation = {.description = "no recovery in place, no reload"}, + }, }; } // namespace From fd603cac25e899577fbb1b535a6b28904fcf0e67 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 15:43:08 -0800 Subject: [PATCH 27/64] Story interrupts: the HOME menu is not an overworld; a step on it fails at once A look that ends on the Switch's HOME menu is told as "Switch HOME menu", never settled. The step before it fails as game_not_running ("the game is not running: the Switch HOME menu is showing") before any input, whatever it starts on; no recovery runs and the segment stops without a reload. SwitchHomeObserver puts the shared HomeMenuDetector in front of a game's observer, for the games' looks between steps. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_ScreenEvents.cpp | 17 +++++++++++++++++ .../Pokemon/AutoStory/Pokemon_ScreenEvents.h | 19 +++++++++++++++++++ .../AutoStory/Pokemon_StoryActions.cpp | 3 ++- .../Pokemon/AutoStory/Pokemon_StoryEvents.cpp | 7 +++++++ .../Pokemon/AutoStory/Pokemon_StoryEvents.h | 7 +++++++ .../AutoStory/Pokemon_StoryInterrupts.cpp | 17 +++++++++++++++-- .../AutoStory/Pokemon_StoryInterrupts.h | 10 +++++++--- .../Pokemon_StoryInterrupts_Tests.cpp | 8 +++++++- .../AutoStory/Pokemon_StorySegments.cpp | 11 ++++++----- 9 files changed, 87 insertions(+), 12 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp index b796c50e69..b58a85cd9a 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp @@ -148,6 +148,23 @@ std::string describe(const ScreenEventLog& log, WallClock origin){ } +SwitchHomeObserver::SwitchHomeObserver(NintendoSwitch::ConsoleHandle& console, ScreenEventObserver& game) + : m_game(game) + , m_home(console, COLOR_RED) +{} + +ScreenEvents SwitchHomeObserver::observe(const VideoSnapshot& frame, WallClock now){ + if (frame && m_home.detect_only(*frame.frame)){ + return {ScreenEvent::SWITCH_HOME_MENU}; + } + return m_game.observe(frame, now); +} + +void SwitchHomeObserver::make_overlays(VideoOverlaySet& items) const{ + m_game.make_overlays(items); +} + + ScreenEventWatcher::ScreenEventWatcher(ScreenEventObserver& observer, ScreenEvents stop_on) : VisualInferenceCallback("ScreenEventWatcher") , m_observer(observer) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h index 66e5a1384c..800351a306 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h @@ -28,6 +28,8 @@ #include "CommonFramework/ImageTypes/ImageViewRGB32.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" #include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -203,6 +205,23 @@ class ScreenEventObserver{ }; +// A game's observer behind a look at the Switch itself: a frame showing +// the HOME menu shows SWITCH_HOME_MENU and nothing else, as a game's +// detectors may read HOME's plain screen as a quiet overworld (BDSP, +// lab-B 2026-11-09). Every other frame is the game's to read. +class SwitchHomeObserver : public ScreenEventObserver{ +public: + SwitchHomeObserver(NintendoSwitch::ConsoleHandle& console, ScreenEventObserver& game); + + virtual ScreenEvents observe(const VideoSnapshot& frame, WallClock now) override; + virtual void make_overlays(VideoOverlaySet& items) const override; + +private: + ScreenEventObserver& m_game; + NintendoSwitch::HomeMenuDetector m_home; +}; + + // An observer as a run_until callback: it records every event it sees, in // order in a log, and stops the action on any of `stop_on` (none: it only // records). diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp index d09f78f553..99138d9a23 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp @@ -137,7 +137,8 @@ std::optional TableExecutor::clear_interrupts(RunState& state, const St InterruptCheck check = clear_story_interrupt(*m_interrupts, state, step); m_guard.on_screen(step, check.screen); if (check.verdict.kind == InterruptKind::NONE){ - return std::nullopt; + // Nothing interrupted; failed only when the game is not running. + return check.outcome.succeeded() ? std::nullopt : std::optional(check.outcome); } if (check.outcome.succeeded() && ++cleared > m_interrupts->max_per_step){ check.outcome = outcome_failed("too_many_interrupts", step.name); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp index 79a095fb9f..ad22d7a6a7 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp @@ -83,6 +83,10 @@ std::string to_string(const Outcome& outcome){ return outcome.detail.empty() ? outcome.failure : outcome.failure + ": " + outcome.detail; } +Outcome outcome_game_not_running(){ + return outcome_failed(GAME_NOT_RUNNING, "the game is not running: the Switch HOME menu is showing"); +} + Condition condition(std::string name, Check check){ return Condition{std::move(name), std::move(check)}; } @@ -266,6 +270,9 @@ Recovery* next_recovery(EventRun& run, const std::string& failure){ // is answered in turn, so escalation goes on from there. std::optional recover(EventRun& run, Outcome failure){ while (true){ + if (failure.failure == GAME_NOT_RUNNING){ + return failure; + } Recovery* recovery = next_recovery(run, failure.failure); if (recovery == nullptr){ return failure; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h index 10e96b6bc4..388ce48b03 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h @@ -115,6 +115,13 @@ Outcome outcome_failed(std::string failure, std::string detail = ""); // "probe_exhausted: 4 rows": the failure and its detail, if any. std::string to_string(const Outcome& outcome); +// The failure of a step that found the Switch's HOME menu instead of the +// game. Nothing in the story can answer it, as every press goes to the +// console's menus: no recovery runs and no reload, the run stops. +constexpr const char* GAME_NOT_RUNNING = "game_not_running"; +// GAME_NOT_RUNNING, saying so for the run log. +Outcome outcome_game_not_running(); + // Callable action executed for a story event. using Act = MoveOnlyFunction; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp index 8fe58620e9..f431425718 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp @@ -83,7 +83,8 @@ bool may_open_a_battle(const ScreenLook& look, const InterruptVerdict& verdict){ InterruptVerdict settled_verdict(const StoryInterrupts& interrupts, StoryStepKind step, ScreenSettle& screen){ ScreenLook look = interrupts.look(true); InterruptVerdict verdict = classify_interrupt(look.log, look.window, interrupts.knobs); - if (!interrupts.handlers.step_starts_on(step, InterruptKind::UNSETTLED)){ + const bool home = look.log.showing().has(ScreenEvent::SWITCH_HOME_MENU); + if (!home && !interrupts.handlers.step_starts_on(step, InterruptKind::UNSETTLED)){ for (size_t looks = 1; verdict.kind == InterruptKind::UNSETTLED; looks++){ const size_t limit = may_open_a_battle(look, verdict) ? interrupts.max_opening_looks : interrupts.max_looks; if (looks >= limit){ @@ -119,8 +120,12 @@ ScreenSettle judge_settle(const ScreenLook& look){ return out; } +bool on_home_menu(const ScreenSettle& settle){ + return settle.seen && settle.showing.has(ScreenEvent::SWITCH_HOME_MENU); +} + bool is_settled(const ScreenSettle& settle){ - return settle.seen && + return settle.seen && !on_home_menu(settle) && settle.showing.has(ScreenEvent::PLAYER_CAN_MOVE) && !settle.showing.any_of({ScreenEvent::DIALOG_BOX, ScreenEvent::BATTLE_STARTED}) && fade_in(settle.showing) == WarpFade::NONE; @@ -131,6 +136,9 @@ std::string describe(const ScreenSettle& settle){ return "no frame seen"; } const std::string quiet = std::format("quiet {:.1f} s", settle.quiet.count() / 1000.0); + if (on_home_menu(settle)){ + return "Switch HOME menu (" + quiet + ")"; + } if (is_settled(settle)){ return "settled overworld (" + quiet + ")"; } @@ -141,6 +149,11 @@ std::string describe(const ScreenSettle& settle){ InterruptCheck clear_story_interrupt(const StoryInterrupts& interrupts, RunState& state, const StoryStep& step){ InterruptCheck out; out.verdict = settled_verdict(interrupts, step.kind, out.screen); + if (on_home_menu(out.screen)){ + out.verdict = {}; + out.outcome = outcome_game_not_running(); + return out; + } const InterruptKind kind = out.verdict.kind; if (kind == InterruptKind::NONE){ return out; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h index 2f7583c07f..15b024134e 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h @@ -126,10 +126,12 @@ struct ScreenSettle{ }; // The end of `look`: its last frame's events, and how long they held. ScreenSettle judge_settle(const ScreenLook& look); +// Whether it ended on the HOME menu: the game is not running. +bool on_home_menu(const ScreenSettle& settle); // Whether it ended on the overworld with no box, no fade and no battle. bool is_settled(const ScreenSettle& settle); // "settled overworld (quiet 0.3 s)", "black fade showing (quiet 0.1 s)", -// "no frame seen". +// "Switch HOME menu (quiet 0.3 s)", "no frame seen". std::string describe(const ScreenSettle& settle); @@ -140,13 +142,15 @@ struct InterruptCheck{ // NONE when nothing interrupted, or when the step starts on it. InterruptVerdict verdict = {}; // Failed when the look stayed unsettled, the kind had no handler, or - // the handler failed. + // the handler failed; GAME_NOT_RUNNING, with no verdict, when the + // look ended on the Switch's HOME menu. Outcome outcome = {}; }; // Looks at the screen before `step` (or after it failed) and clears what // interrupted the player, if anything, writing the handler's effect on -// the pose into `state`. +// the pose into `state`. On the HOME menu it fails as GAME_NOT_RUNNING +// and clears nothing, whatever the step starts on. InterruptCheck clear_story_interrupt(const StoryInterrupts& interrupts, RunState& state, const StoryStep& step); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp index f8d0ae445c..f9b4b9d079 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -90,6 +90,12 @@ ScreenLook white_settled(){ ScreenLook home_menu(){ return look_of({{0, HOME}, {300, HOME}}, 300); } +// The same, with a game's detectors reading it as the overworld too. +ScreenLook home_read_as_overworld(){ + ScreenEvents both = HOME; + both.set(ScreenEvent::PLAYER_CAN_MOVE, true); + return look_of({{0, both}}, 300); +} // The fake game: the screen its looks show, one per look and then the @@ -578,7 +584,7 @@ UnitTestResult test_settle_of_a_look(){ {"a box", dialog(), "dialog box, player can move showing (quiet 0.2 s)"}, {"a door's fade back up", black_unsettled(), "settled overworld (quiet 0.3 s)"}, {"the HOME menu", home_menu(), "Switch HOME menu (quiet 0.3 s)"}, - {"HOME read as a quiet overworld too", look_of({{0, ScreenEvents{ScreenEvent::SWITCH_HOME_MENU, ScreenEvent::PLAYER_CAN_MOVE}}}, 300), "Switch HOME menu (quiet 0.3 s)"}, + {"HOME read as a quiet overworld too", home_read_as_overworld(), "Switch HOME menu (quiet 0.3 s)"}, }; for (const Row& row : rows){ const std::string got = describe(judge_settle(row.look)); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp index e217d6ce0b..5653725467 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp @@ -155,12 +155,13 @@ CheckpointReport run_row( )); return result; } - if (policy.stop_at_first_failure){ - say(hooks, std::format( - "[Segment] {}: {} failed; stopping at the first failure, the game stays where it failed", - segment.id, spec.id + const bool not_running = result.failure.failure == GAME_NOT_RUNNING; + if (not_running || policy.stop_at_first_failure){ + say(hooks, std::format("[Segment] {}: {} failed; {}", segment.id, spec.id, not_running + ? "the game is not running, so no reload" + : "stopping at the first failure, the game stays where it failed" )); - report.stopped_at_first_failure = true; + report.stopped_at_first_failure = !not_running; return result; } if (attempt >= policy.attempts_per_checkpoint){ From 5e00efab13c28035efa1f2509b29b692a8aaec78 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 15:50:11 -0800 Subject: [PATCH 28/64] FRLG AutoStory: look for the Switch HOME menu before each step ConsoleScreenLook puts Pokemon::SwitchHomeObserver in front of FRLG's observer, so a step that starts on HOME fails as game_not_running before any input, as BDSP's (lab-B 2026-11-09 15:31). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp | 7 ++++--- .../AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h | 5 ++++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp index 5930c46d2e..e8774ec4af 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp @@ -80,10 +80,11 @@ Pokemon::StoryInterrupts step_interrupts(Pokemon::ScreenLookFunction look, const } -ConsoleScreenLook::ConsoleScreenLook(VideoStream& stream, ProControllerContext& context) - : m_stream(stream) +ConsoleScreenLook::ConsoleScreenLook(ConsoleHandle& console, ProControllerContext& context) + : m_stream(console) , m_context(context) - , m_watcher(m_observer) + , m_eyes(console, m_observer) + , m_watcher(m_eyes) , m_start(current_time()) {} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h index 63336a8b2c..d1d3e5d32a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h @@ -77,9 +77,11 @@ constexpr Milliseconds BETWEEN_STEPS_LOOK = Milliseconds(400); // The console's look between steps: FrlgScreenObserver's events for // BETWEEN_STEPS_LOOK, everything showing in it judged. +// The Switch's HOME menu comes first (Pokemon::SwitchHomeObserver), so a +// step that starts on it fails instead of pressing buttons on HOME. class ConsoleScreenLook{ public: - ConsoleScreenLook(VideoStream& stream, ProControllerContext& context); + ConsoleScreenLook(ConsoleHandle& console, ProControllerContext& context); Pokemon::ScreenLook look(bool fresh); @@ -87,6 +89,7 @@ class ConsoleScreenLook{ VideoStream& m_stream; ProControllerContext& m_context; FrlgScreenObserver m_observer; + Pokemon::SwitchHomeObserver m_eyes; Pokemon::ScreenEventWatcher m_watcher; WallClock m_start; }; From 413f1cba686f5d070d056eaee42c74dd3e0e490f Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 15:58:39 -0800 Subject: [PATCH 29/64] FRLG AutoStory: wait out a battle's exit before the next tap in a trainer's line Console B, 2026-11-09 15:50, 00.28 winston_line: a wild battle on the second of three taps into Winston's line was run from, and the third tap, sent as the battle's black ended, was lost; the step failed no_trainer. After a wild battle run from mid-line (and in the capture pacing), the next tap now waits until the overworld has shown nothing for AFTER_BATTLE_QUIET (wait_for_quiet_overworld() over the shared ScreenLook/ScreenSettle). The sim ignores taps for BATTLE_EXIT_LOCKOUT after a battle, and the fault sweep gains LOST_TAP: a wild battle on each tile of each trainer's line before its last. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Overworld/PokemonFRLG_MovementMechanics.h | 12 +++ .../Overworld/PokemonFRLG_OverworldSim.cpp | 10 +-- .../Overworld/PokemonFRLG_OverworldSim.h | 8 +- .../PokemonFRLG_AutoStoryActions.cpp | 13 ++++ .../AutoStory/PokemonFRLG_AutoStoryActions.h | 10 +++ .../PokemonFRLG_AutoStoryCapture.cpp | 3 + .../PokemonFRLG_AutoStoryFaultSweep_Tests.cpp | 76 +++++++++++++++++-- .../PokemonFRLG_AutoStoryLavender_Tests.cpp | 28 +++++++ .../AutoStory/PokemonFRLG_AutoStoryRowSim.cpp | 18 +++++ .../PokemonFRLG_AutoStoryStepInterrupts.cpp | 23 ++++++ .../PokemonFRLG_AutoStoryStepInterrupts.h | 14 ++++ 11 files changed, 204 insertions(+), 11 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_MovementMechanics.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_MovementMechanics.h index 9fc6df8df6..f7062858bc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_MovementMechanics.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_MovementMechanics.h @@ -21,6 +21,9 @@ * tap's start is ignored. * - Taps with no release between them are one hold: after a turn, 3 of * them took 0 or 1 steps. + * After a battle (console B, 2026-11-09 15:50, 00.28 winston_line): a + * step tap sent as flee_battle() returned, on the black's end, was lost; + * one more tap by hand stepped. * */ @@ -55,6 +58,10 @@ inline constexpr Milliseconds LONGEST_TAP(133); inline constexpr Milliseconds STEP_TAP_LOCKOUT(620); // The shortest step tap spacing, start to start, measured to work. inline constexpr Milliseconds STEP_TAP_SPACING_WORKED(666); +// After a battle's black ends, the overworld fades in and the game ignores +// the D-pad this long. Not measured: pokefirered's fade from black is 16 +// frames, then the field takes input; a tap sent at once was lost. +inline constexpr Milliseconds BATTLE_EXIT_LOCKOUT(500); // The walker's presses. @@ -77,9 +84,14 @@ inline constexpr Milliseconds STEP_TAP(66); // STEP_TAP_RELEASE after it, past the lockout. inline constexpr Milliseconds STEP_TAP_RELEASE(700); +// How long the overworld must show nothing (no box, fade or battle) after +// a battle before the next tap: twice the lockout. +inline constexpr Milliseconds AFTER_BATTLE_QUIET(1000); + static_assert(TURN_TAP <= LONGEST_TAP && FACE_HOLD <= LONGEST_TAP && STEP_TAP <= LONGEST_TAP); static_assert(STEP_TAP + STEP_TAP_RELEASE > STEP_TAP_SPACING_WORKED); static_assert(STEP_TAP_SPACING_WORKED > STEP_TAP_LOCKOUT); +static_assert(AFTER_BATTLE_QUIET > BATTLE_EXIT_LOCKOUT); } // namespace MovementMechanics diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index f2e590e288..e8625e13b3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -505,7 +505,7 @@ void OverworldSim::stuck_hold(Direction direction){ }else if (m_battle_pending){ violation(std::string("the D-pad held ") + direction_name(direction) + " into a battle."); }else{ - note(std::string("the D-pad held ") + direction_name(direction) + " under " + sim_screen_name(m_state.screen) + "."); + note(std::string("the D-pad held ") + direction_name(direction) + " under " + sim_screen_name(m_state.screen) + (m_frozen ? "." : ", in the lockout after a battle.")); } } @@ -532,7 +532,7 @@ std::optional OverworldSim::hold( void OverworldSim::tap(Direction direction, Milliseconds duration, Milliseconds release){ const Milliseconds start = m_now; - if (m_state.screen != SimScreen::OVERWORLD || m_frozen){ + if (m_state.screen != SimScreen::OVERWORLD || m_frozen || start < m_battle_lockout_end){ stuck_hold(direction); m_last_tap.reset(); }else if (m_last_tap && m_last_tap->direction == direction && m_last_tap->end == start){ @@ -620,14 +620,14 @@ SimBattleEnd OverworldSim::handle_battle(SimBattleChoice choice){ show(SimScreen::OVERWORLD, m_now); m_frozen = false; m_battle_pending = false; - if (!m_trainer){ - m_state.in_wild_battles += m_now - m_wild_battle_from; - } + m_battle_lockout_end = m_now + m_script.timing.battle_exit_lockout; if (m_trainer){ MapObject& trainer = m_maps[m_map].objects[*m_trainer]; trainer.trainer.reset(); m_state.trainers_beaten.push_back(trainer.name); m_trainer.reset(); + }else{ + m_state.in_wild_battles += m_now - m_wild_battle_from; } note(std::string(choice == SimBattleChoice::RUN ? "ran from" : "won") + " the battle."); return SimBattleEnd::ENDED; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index 0db86f8980..21038720d4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -99,6 +99,8 @@ struct SimTiming{ Milliseconds fade{1000}; // from the step's end to the new map Milliseconds trainer_notice{1000}; // "!" over the trainer, before they walk up Milliseconds trainer_battle{2000}; // after the trainer's message closes + // From a battle's end on, the game ignores taps this long. + Milliseconds battle_exit_lockout = MovementMechanics::BATTLE_EXIT_LOCKOUT; }; // What a test sets up beyond the maps. @@ -225,7 +227,9 @@ class OverworldSim{ // LONGEST_TAP), then `release`, as the console measured it: a player // facing another way only turns; one facing that way steps once, // unless the tap starts inside the lockout after the last step tap - // (STEP_TAP_LOCKOUT), which the game ignores. A tap that starts as + // (STEP_TAP_LOCKOUT), which the game ignores, as it does any tap + // inside the lockout after a battle (BATTLE_EXIT_LOCKOUT); holds + // aren't held up by that lockout yet. A tap that starts as // the last one ends, with no release between, holds it on. A turn may // be dropped by fault injection (SimScript::dropped_turn_taps). void tap( @@ -330,6 +334,8 @@ class OverworldSim{ std::optional m_last_tap; // When the last tap that stepped started. std::optional m_last_step_tap; + // The end of the lockout after the last battle. + Milliseconds m_battle_lockout_end{0}; Milliseconds m_wild_battle_from{0}; int m_holds = 0; SimState m_state; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp index 72386fb022..94a86456c2 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.cpp @@ -33,6 +33,7 @@ #include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreen.h" #include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_StartMenuNavigation.h" #include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryStepInterrupts.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -598,6 +599,17 @@ std::optional step_until_seen(int max_tiles, const std::function& s return std::nullopt; } +void wait_out_battle_exit(ConsoleHandle& console, ProControllerContext& context){ + context.wait_for_all_requests(); + ConsoleScreenLook eyes(console, context); + const Pokemon::ScreenSettle settle = wait_for_quiet_overworld( + [&eyes](bool fresh){ return eyes.look(fresh); }, + MovementMechanics::AFTER_BATTLE_QUIET, BATTLE_EXIT_TIMEOUT + ); + const bool quiet = quiet_overworld(settle, MovementMechanics::AFTER_BATTLE_QUIET); + console.log("Story: after the battle, " + Pokemon::describe(settle), quiet ? COLOR_BLACK : COLOR_RED); +} + std::optional step_into_line( ConsoleHandle& console, ProControllerContext& context, Direction direction, std::optional facing, int max_tiles, Milliseconds watch @@ -615,6 +627,7 @@ std::optional step_into_line( if (seen == 1){ console.log("Story: a wild battle on the step into a trainer's line; running from it, then stepping on.", COLOR_ORANGE); flee_battle(console, context); + wait_out_battle_exit(console, context); return false; } return seen == 0; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h index efbd5b8679..07e37e35c9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryActions.h @@ -148,6 +148,16 @@ inline constexpr Milliseconds TRAINER_LINE_WATCH(2500); // 2026-11-09). inline constexpr Milliseconds WILD_BATTLE_IN_LINE_WATCH(5000); +// The longest wait_out_battle_exit() waits for the overworld. +inline constexpr Milliseconds BATTLE_EXIT_TIMEOUT(10000); + +// After a battle run from or won: waits until the overworld has shown +// nothing (wait_for_quiet_overworld()) for MovementMechanics:: +// AFTER_BATTLE_QUIET, at most BATTLE_EXIT_TIMEOUT, and logs how the screen +// ended. A tap sent as the battle's black ends is lost (console B, +// 2026-11-09, 00.28 winston_line). +void wait_out_battle_exit(ConsoleHandle& console, ProControllerContext& context); + // How long a step into the line of a trainer who looks around waits for // them to turn to the player (TRAINER_WAIT_VARIANT). inline constexpr Milliseconds TRAINER_WAIT_WATCH(30000); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.cpp index c99038983f..f292e12fd2 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture.cpp @@ -557,6 +557,9 @@ EncounterSeen ConsoleCaptureActions::read_encounter(){ bool ConsoleCaptureActions::flee(){ try{ flee_battle(m_console, m_context); + // The pacing counts its taps: one lost to the battle's exit + // would put it a tile off. + wait_out_battle_exit(m_console, m_context); return true; }catch (OperationFailedException& e){ m_console.log("Capture: " + e.message(), COLOR_RED); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.cpp index 58d2d9e891..bd2a0112bb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryFaultSweep_Tests.cpp @@ -17,11 +17,15 @@ * battle there ends on the dark cave's overworld, with no wild * battles and with them at the game's odds (00.28 hiker_lenny, lab-B * 2026-11-09). + * - LOST_TAP: a wild battle on each tile of each step into a trainer's + * line before its last, so the next tap comes as the overworld comes + * back, inside the lockout after a battle (00.28 winston_line, console + * B, 2026-11-09 15:50). The step alone, from where the clean run took + * it, on its map made a wild floor. * * Not swept here: a missed fade, which needs a knob in OverworldSim; a * battle's opening at a step's start, which needs one in OverworldStepSim; - * and lost taps from the input lockout (FaultClass::LOST_TAP), for the - * measured movement table. + * and the step tap lockout between two taps, which step_once() waits out. * * The sim plays walks, steps, cuts and trainers' battles; after a step it * does not play, the player is put on the table's pose. Each row runs @@ -65,7 +69,6 @@ enum class FaultClass{ WILD_BATTLES, LATE_FADE, DARK_CAVE, - // Not swept yet: the measured movement table's lost taps. LOST_TAP, }; const char* fault_class_name(FaultClass fault){ @@ -79,7 +82,7 @@ const char* fault_class_name(FaultClass fault){ case FaultClass::DARK_CAVE: return "dark cave without Flash"; case FaultClass::LOST_TAP: - return "lost tap"; + return "lost tap after a battle in a trainer's line"; } return "?"; } @@ -147,6 +150,7 @@ struct RowRun{ std::set scripted; // Where the player stood before each step, by index. std::map before; + std::map facing_before; MapPosition end; Milliseconds time{0}; int steps = 0; @@ -187,6 +191,7 @@ RowRun run_row( for (size_t c = 0; c < row.steps.size() && out.failure.empty(); c++){ const StoryStep& step = row.steps[c]; out.before.emplace(c, sim->state().position); + out.facing_before.emplace(c, sim->state().facing); out.failure = row_step_on_sim(*sim, at, step, row.id); const bool let_pass = unscripted(out.failure) && (!scripted || scripted->contains(c)); if (let_pass){ @@ -376,6 +381,66 @@ UnitTestResult sweep_dark_cave(Logger& logger, const StoryCheckpoint& row, const return sweep_result(logger, FaultClass::DARK_CAVE, row.id, DARK_CAVE_SEEDS + 1, failures); } +// How many tiles row `row`'s step `c`, into a trainer's line, steps onto +// before its last, in the clean run `clean`. +int line_tiles_before_last(const StoryCheckpoint& row, const RowRun& clean, size_t c){ + const auto from = clean.before.find(c); + const auto next = clean.before.find(c + 1); + if (from == clean.before.end()){ + return 0; + } + const MapPosition last = next == clean.before.end() ? clean.end : next->second; + TilePos tile = from->second.point.next(row.steps[c].direction); + int out = 0; + for (; out + 1 < TRAINER_LINE_TILES && last.map == from->second.map && !(tile == last.point); out++){ + tile = tile.next(row.steps[c].direction); + } + return out; +} + +// Row `row`'s step `c`, into a trainer's line, alone from where the clean +// run `clean` took it, with a wild battle on its `battle_step`th step: why +// it fails or ends off the clean run's tile, or "". +std::string line_with_battle(const StoryCheckpoint& row, const RowRun& clean, size_t c, int battle_step){ + const MapPosition from = clean.before.at(c); + const auto next = clean.before.find(c + 1); + const MapPosition last = next == clean.before.end() ? clean.end : next->second; + SimScript script; + script.wild_floor_maps = {from.map}; + script.encounters = {SimEncounter{.grass_step = battle_step}}; + OverworldSim sim(sweep_maps(), from, clean.facing_before.at(c), script); + StoryPose at{from.map, from.point, clean.facing_before.at(c)}; + const std::string failure = row_step_on_sim(sim, at, row.steps[c], row.id); + if (!failure.empty()){ + return failure; + } + if (!(sim.state().position == last)){ + return std::format("ended on {}, not {}.", to_string(sim.state().position), to_string(last)); + } + return ""; +} + +// Row `row` with a wild battle on each tile of each step into a trainer's +// line before its last, one at a time: the tap after it must not be lost. +UnitTestResult sweep_lost_tap(Logger& logger, const StoryCheckpoint& row, const RowRun& clean){ + std::vector failures; + size_t variants = 0; + for (size_t c = 0; c < row.steps.size(); c++){ + const StoryStep& step = row.steps[c]; + if (step.kind != StoryStepKind::STEP || step.variant != TRAINER_LINE_VARIANT || clean.scripted.contains(c)){ + continue; + } + const int tiles = line_tiles_before_last(row, clean, c); + for (int battle_step = 1; battle_step <= tiles; battle_step++){ + variants++; + if (const std::string stopped = line_with_battle(row, clean, c, battle_step); !stopped.empty()){ + failures.push_back({step.name, std::format("a wild battle on step {}", battle_step), stopped}); + } + } + } + return sweep_result(logger, FaultClass::LOST_TAP, row.id, variants, failures); +} + // A fault class swept over row `row` (empty in FAULT_SWEEP_CASES: each // row with a start). struct FaultSweepInput{ @@ -442,7 +507,7 @@ class Test_AutoStoryFaultSweep : public UnitTest{ case FaultClass::DARK_CAVE: return sweep_dark_cave(logger, m_row, clean); case FaultClass::LOST_TAP: - break; + return sweep_lost_tap(logger, m_row, clean); } return true; } @@ -459,6 +524,7 @@ const FaultSweepCase FAULT_SWEEP_CASES[] = { {.input = {.fault = FaultClass::WILD_BATTLES}, .expectation = {}}, {.input = {.fault = FaultClass::LATE_FADE}, .expectation = {}}, {.input = {.fault = FaultClass::DARK_CAVE}, .expectation = {}}, + {.input = {.fault = FaultClass::LOST_TAP}, .expectation = {}}, }; void add_tests_AutoStoryFaultSweep(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp index 73b5f010be..28a8a12bb1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryLavender_Tests.cpp @@ -242,6 +242,33 @@ UnitTestResult test_b1f_martha_after_row38_battle(Logger&){ return true; } +// Regression: console B, 2026-11-09 15:50, 00.28 winston_line, dark: from +// (32, 37) west into Winston's line, a wild battle on the 2nd tap's tile +// (30, 37), run from; the 3rd tap, sent as the battle's black ended, was +// lost, and the step failed no_trainer. After the battle the next tap +// waits for the overworld (wait_out_battle_exit()): Winston sees the +// player on (29, 37). +UnitTestResult test_winston_line_battle_on_tap_2(Logger&){ + const StoryCheckpoint& row = checkpoint("00.28"); + SimScript script; + script.dark_maps = {StoryTable::ROCK_TUNNEL_1F, StoryTable::ROCK_TUNNEL_B1F}; + script.wild_floor_maps = {StoryTable::ROCK_TUNNEL_B1F}; + script.encounters = {SimEncounter{.grass_step = 2}}; + StoryPose at{StoryTable::ROCK_TUNNEL_B1F, {32, 37}, Direction::WEST}; + OverworldSim sim(maps_after_route10(), MapPosition{at.map, at.tile}, Direction::WEST, script); + const std::string failure = row_step_on_sim(sim, at, row.steps[step_index(row, "winston_line")], row.id); + const auto lost = std::find_if(sim.state().log.begin(), sim.state().log.end(), [](const std::string& line){ + return line.find("in the lockout after a battle") != std::string::npos; + }); + if (!failure.empty() || lost != sim.state().log.end() || sim.state().wild_battles != 1){ + return std::format( + "winston_line: ended on {}, {} wild battle(s), {}; {}", to_string(sim.state().position), + sim.state().wild_battles, lost == sim.state().log.end() ? "no tap lost" : *lost, failure + ); + } + return true; +} + // Rock Tunnel has no Flash: both floors are dark. const std::set ROCK_TUNNEL_DARK{StoryTable::ROCK_TUNNEL_1F, StoryTable::ROCK_TUNNEL_B1F}; @@ -559,6 +586,7 @@ const AutoStoryLavenderCase AUTO_STORY_LAVENDER_CASES[] = { {.input = {"00.28 B1F a wild battle into row 38, then a step short: Martha still sees the player", test_b1f_martha_after_row38_battle}, .expectation = {}}, {.input = {"00.28 B1F dark, the 13:35 legs: a battle at the end of the walk back along row 38", test_b1f_dark_row38_battle_old_legs}, .expectation = {}}, {.input = {"00.28 B1F dark, a wild battle on any step to Martha's line", test_b1f_dark_martha_battle_anywhere}, .expectation = {}}, + {.input = {"00.28 B1F dark, winston_line: a wild battle on the 2nd tap, the 3rd after it", test_winston_line_battle_on_tap_2}, .expectation = {}}, {.input = {"00.29 Route 10 south, the ledge, Lavender Town's Pokemon Center", test_lavender_row}, .expectation = {}}, {.input = {"00.29 a tile off after each open leg", test_lavender_tile_off}, .expectation = {}}, {.input = {"00.28 and 00.29 save on Route 10 and in Lavender Town", test_save_places}, .expectation = {}}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp index c39aac361c..ff86b55359 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp @@ -433,6 +433,23 @@ std::string battle_end_on_sim(const OverworldSim& sim){ return "fight_battle(): START never looked for the overworld."; } +// wait_out_battle_exit() on `sim`: each look shows the sim's screens for +// BETWEEN_STEPS_LOOK. +void sim_wait_out_battle_exit(OverworldSim& sim){ + Milliseconds from = sim.state().time; + const auto look = [&sim, &from](bool fresh){ + if (fresh){ + from = sim.state().time; + } + sim.watch({}, BETWEEN_STEPS_LOOK); + return Pokemon::ScreenLook{ + .log = screen_event_log(sim.state(), from), + .window = {.start = sim_wall_clock(from), .end = sim_wall_clock(sim.state().time)}, + }; + }; + wait_for_quiet_overworld(look, MovementMechanics::AFTER_BATTLE_QUIET, BATTLE_EXIT_TIMEOUT); +} + } // namespace // A ROUTE or LEGS by the sim's walker, fighting a trainer who sees the @@ -469,6 +486,7 @@ std::string OverworldStepSim::step_ahead(const StoryStep& step){ ); if (shown && shown->watcher == 1){ m_sim.handle_battle(SimBattleChoice::RUN); + sim_wait_out_battle_exit(m_sim); return false; } return shown.has_value(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp index e8774ec4af..129905cbbd 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.cpp @@ -98,6 +98,29 @@ Pokemon::ScreenLook ConsoleScreenLook::look(bool fresh){ } +bool quiet_overworld(const Pokemon::ScreenSettle& settle, Milliseconds quiet){ + return settle.seen && settle.showing == Pokemon::ScreenEvents{} && settle.quiet >= quiet; +} + +Pokemon::ScreenSettle wait_for_quiet_overworld( + const Pokemon::ScreenLookFunction& look, Milliseconds quiet, Milliseconds timeout +){ + Pokemon::ScreenLook seen = look(true); + Pokemon::ScreenSettle settle = Pokemon::judge_settle(seen); + // Each look takes about BETWEEN_STEPS_LOOK; the cap also ends a look + // that takes no time. + const size_t max_looks = (size_t)(timeout / BETWEEN_STEPS_LOOK) + 1; + for (size_t looks = 1; looks < max_looks && !quiet_overworld(settle, quiet); looks++){ + if (seen.window.end - seen.window.start >= timeout){ + break; + } + seen = look(false); + settle = Pokemon::judge_settle(seen); + } + return settle; +} + + void InterruptLogGuard::on_interrupt(const Pokemon::StoryStep& step, const Pokemon::InterruptCheck& check){ const bool cleared = check.outcome.succeeded(); m_logger.log(std::format( diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h index d1d3e5d32a..454ad88000 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryStepInterrupts.h @@ -94,6 +94,20 @@ class ConsoleScreenLook{ WallClock m_start; }; +// Whether a look ended on FRLG's overworld at rest: nothing showing (no +// box, fade or battle; FrlgScreenObserver reports no PLAYER_CAN_MOVE, so +// Pokemon::is_settled() never holds) for at least `quiet`. +bool quiet_overworld(const Pokemon::ScreenSettle& settle, Milliseconds quiet); + +// Looks with `look`, fresh and then on from it, until it ends on +// quiet_overworld() for `quiet`, or has looked for `timeout`. Returns how +// the last look ended. After a battle, the next tap waits for this +// (MovementMechanics::AFTER_BATTLE_QUIET): one sent at its black's end +// is lost (BATTLE_EXIT_LOCKOUT). +Pokemon::ScreenSettle wait_for_quiet_overworld( + const Pokemon::ScreenLookFunction& look, Milliseconds quiet, Milliseconds timeout +); + // The console's guard: a failed step fails it, as before; each interrupt // found between steps is logged, cleared or not, and how the screen looked // before every step. From 10f05830b315765e44b58087d68c3a5015e31b6d Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 18:19:02 -0800 Subject: [PATCH 30/64] AutoStory: story types and engine, split out of #122 The story step vocabulary, the checkpoint builder and executor interface, the variant parser, the shared story-step JSON codec and authored checkpoint envelope, the story run options, and the StoryEvents/ StorySegments additions (changed_nothing, game_not_running), taken as they are at nav/story-steps fd603cac2. Screen state and interrupt tracking follow in their own layer. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .github/workflows/story-data.yml | 34 + .../ComputerPrograms_UnitTestRunner.cpp | 3 + .../Pokemon_AuthoredCheckpointJson.cpp | 67 ++ .../Pokemon_AuthoredCheckpointJson.h | 53 ++ .../Pokemon_AuthoredCheckpointJson_Tests.cpp | 139 +++ .../AutoStory/Pokemon_AutoStory_Tests.h | 8 + .../Pokemon/AutoStory/Pokemon_StoryEvents.cpp | 16 + .../Pokemon/AutoStory/Pokemon_StoryEvents.h | 15 + .../AutoStory/Pokemon_StorySegments.cpp | 70 +- .../Pokemon/AutoStory/Pokemon_StorySegments.h | 35 +- .../AutoStory/Pokemon_StoryStepJson.cpp | 355 ++++++++ .../Pokemon/AutoStory/Pokemon_StoryStepJson.h | 26 + .../AutoStory/Pokemon_StoryStepJson_Tests.cpp | 150 +++ .../Pokemon/AutoStory/Pokemon_StorySteps.cpp | 325 +++++++ .../Pokemon/AutoStory/Pokemon_StorySteps.h | 261 ++++++ .../AutoStory/Pokemon_StorySteps_Tests.cpp | 854 ++++++++++++++++++ .../AutoStory/Pokemon_StoryVariant.cpp | 72 ++ .../Pokemon/AutoStory/Pokemon_StoryVariant.h | 51 ++ .../Options/Pokemon_StoryRunOptions.cpp | 161 ++++ .../Pokemon/Options/Pokemon_StoryRunOptions.h | 119 +++ SerialPrograms/cmake/SourceFiles.cmake | 13 + devtools/story-data-tests/CMakeLists.txt | 43 + devtools/story-data-tests/README.md | 37 + 23 files changed, 2902 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/story-data.yml create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.h create mode 100644 SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp create mode 100644 SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h create mode 100644 devtools/story-data-tests/CMakeLists.txt create mode 100644 devtools/story-data-tests/README.md diff --git a/.github/workflows/story-data.yml b/.github/workflows/story-data.yml new file mode 100644 index 0000000000..545299ac51 --- /dev/null +++ b/.github/workflows/story-data.yml @@ -0,0 +1,34 @@ +name: Story data codec +on: + pull_request: + workflow_dispatch: +jobs: + native-codec: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v7 + - uses: actions/checkout@v7 + with: + repository: dayfine/PokemonSimulation + # Synthetic contract cases, not an approved map/resource pin. + ref: 866613fa03e5c4a5eb7e57c91b59fafb44fc7ee3 + path: publisher + - uses: actions/setup-python@v6 + with: + python-version: '3.12' + - name: Check the Python reader against the same cases + working-directory: publisher + env: + PYTHONPATH: src + run: python -m unittest pokesim.story.test_checkpoint_wire + - run: cmake -S devtools/story-data-tests -B build-story-data -DCMAKE_BUILD_TYPE=Debug + - run: cmake --build build-story-data --config Debug -j4 + - run: ctest --test-dir build-story-data -C Debug --output-on-failure + - if: runner.os != 'Windows' + run: ./build-story-data/StoryDataTests publisher/data/story/wire-conformance.json + - if: runner.os == 'Windows' + run: ./build-story-data/Debug/StoryDataTests.exe publisher/data/story/wire-conformance.json diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 71e86b9f48..df98fc4df2 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -80,6 +80,9 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_RouteLog(ret); Pokemon::add_tests_StoryEvents(ret); Pokemon::add_tests_StorySegments(ret); + Pokemon::add_tests_StorySteps(ret); + Pokemon::add_tests_StoryStepJson(ret); + Pokemon::add_tests_AuthoredCheckpointJson(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); NintendoSwitch::add_tests_UpdatePopupDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.cpp new file mode 100644 index 0000000000..699ece6df1 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.cpp @@ -0,0 +1,67 @@ +/* Shared Authored Checkpoint JSON + * From: https://github.com/PokemonAutomation/ + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_StoryStepJson.h" +#include "Pokemon_AuthoredCheckpointJson.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +void require_story_json_fields( + const JsonObject& object, std::initializer_list fields, std::string_view source +){ + if (object.size() != fields.size()){ + throw ParseException(std::format("{}: missing or extra authored checkpoint fields.", source)); + } + for (std::string_view field : fields){ + object.get_value_throw(std::string(field), std::string(source)); + } +} + +AuthoredCheckpoint read_authored_checkpoint( + const JsonValue& value, std::string_view expected_game, std::string_view source +){ + const JsonObject& root = value.to_object_throw(std::string(source)); + require_story_json_fields(root, {"format", "game", "checkpoint", "execution"}, source); + if (expected_game.empty() || root.get_string_throw("format") != "pokesim-authored-checkpoint/1" + || root.get_string_throw("game") != expected_game + ){ + throw ParseException(std::format("{}: unsupported authored checkpoint format/game.", source)); + } + return { + .checkpoint = read_story_checkpoint(root.get_value_throw("checkpoint"), source), + .execution = root.get_object_throw("execution", std::string(source)).clone(), + }; +} + +JsonValue authored_checkpoint_json(const StoryCheckpoint& checkpoint, std::string_view game, JsonObject execution){ + if (game.empty()){ + throw ParseException("Authored checkpoint game must not be empty."); + } + JsonObject result; + result["format"] = "pokesim-authored-checkpoint/1"; + result["game"] = std::string(game); + result["checkpoint"] = story_checkpoint_json(checkpoint); + result["execution"] = std::move(execution); + return result; +} + +AuthoredCheckpoint load_authored_checkpoint( + std::span> files, std::string_view file, std::string_view expected_game +){ + for (const auto& [name, text] : files){ + if (name == file){ + return read_authored_checkpoint(parse_json(text), expected_game, file); + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Authored checkpoint is not embedded: " + std::string(file)); +} + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.h new file mode 100644 index 0000000000..1b1be213dd --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.h @@ -0,0 +1,53 @@ +/* Shared Authored Checkpoint JSON + * From: https://github.com/PokemonAutomation/ + */ + +#ifndef PokemonAutomation_AuthoredCheckpointJson_H +#define PokemonAutomation_AuthoredCheckpointJson_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon_StorySteps.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Common story data and an owned execution object for the game adapter to validate. +// Parsing this document does not validate game policies or bind/execute actions. +struct AuthoredCheckpoint{ + StoryCheckpoint checkpoint; + JsonObject execution; +}; + +// Require exactly these fields, including fields whose value is null/zero/false. +// Missing/unknown fields throw ParseException with the document source. +void require_story_json_fields( + const JsonObject& object, std::initializer_list fields, std::string_view source +); + +// Read the strict authored envelope and common checkpoint for expected_game. +// The game adapter must still validate execution fields and values before use. +AuthoredCheckpoint read_authored_checkpoint( + const JsonValue& value, std::string_view expected_game, std::string_view source +); + +// Encode the authored envelope; execution is supplied by the game adapter. +// This does not encode game bookkeeping or the legacy native-export envelope. +JsonValue authored_checkpoint_json(const StoryCheckpoint& checkpoint, std::string_view game, JsonObject execution); + +// Find and parse an embedded (filename without .json, text) resource for this game. +// Missing resources throw InternalProgramError; malformed documents throw ParseException. +AuthoredCheckpoint load_authored_checkpoint( + std::span> files, std::string_view file, std::string_view expected_game +); + + +} // namespace Pokemon +} // namespace PokemonAutomation + +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson_Tests.cpp new file mode 100644 index 0000000000..7aba0e12f4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson_Tests.cpp @@ -0,0 +1,139 @@ +/* Shared Authored Checkpoint JSON Tests + * From: https://github.com/PokemonAutomation/ + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_AuthoredCheckpointJson.h" +#include "Pokemon_StoryStepJson.h" +#ifndef PA_STORY_DATA_STANDALONE +#include "Pokemon_AutoStory_Tests.h" +#endif + +namespace PokemonAutomation{ +namespace Pokemon{ +namespace{ + +// Documents intentionally contain no game headers or native bookkeeping. +const std::string FRLG = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{"id":"00.05","title":"Parcel","events":[{"id":"first","kind":"route"},{"id":"second","kind":"scene"}]},"execution":{"menu":"before_pokedex"}})"; +const std::string BDSP = R"({"format":"pokesim-authored-checkpoint/1","game":"bdsp","checkpoint":{"id":"01.03","title":"Mine","events":[{"id":"roark","kind":"talk"}]},"execution":{"on_failure":"reload_and_retry","saves_in":"Oreburgh City"}})"; + +enum class Failure{ NONE, PARSE, MISSING_RESOURCE }; + +struct AuthoredInput{ + std::string name; + std::string json; + std::string game = "frlg"; + bool resource = false; + std::string file = "plan"; +}; + +struct AuthoredExpectation{ + std::string checkpoint = "00.05"; + std::string execution = R"({"menu":"before_pokedex"})"; + std::vector events = {"first", "second"}; + Failure failure = Failure::NONE; +}; + +struct AuthoredCase{ + AuthoredInput input; + AuthoredExpectation expectation; +}; + +const AuthoredCase CASES[] = { + {.input = {.name = "FRLG envelope", .json = FRLG}, .expectation = {}}, + {.input = {.name = "BDSP embedded resource", .json = BDSP, .game = "bdsp", .resource = true}, .expectation = { + .checkpoint = "01.03", .execution = R"({"on_failure":"reload_and_retry","saves_in":"Oreburgh City"})", .events = {"roark"}}}, + {.input = {.name = "FRLG embedded resource", .json = FRLG, .resource = true}, .expectation = {}}, + {.input = {.name = "wrong game", .json = BDSP}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "empty expected game", .json = FRLG, .game = ""}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "missing resource", .json = FRLG, .resource = true, .file = "absent"}, .expectation = {.failure = Failure::MISSING_RESOURCE}}, + {.input = {.name = "invalid embedded JSON", .json = "{", .resource = true}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "wrong format", .json = R"({"format":"future","game":"frlg","checkpoint":{},"execution":{}})"}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "missing execution", .json = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{}})"}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "same count wrong field", .json = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{},"extra":{}})"}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "extra envelope field", .json = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{},"execution":{},"extra":0})"}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "execution must be object", .json = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{"id":"x","title":"X","events":[]},"execution":false})"}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "invalid common action", .json = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{"id":"x","title":"X","events":[{"id":"bad","kind":"magic"}]},"execution":{}})"}, .expectation = {.failure = Failure::PARSE}}, + {.input = {.name = "execution stays game owned", .json = R"({"format":"pokesim-authored-checkpoint/1","game":"future","checkpoint":{"id":"x","title":"X","events":[]},"execution":{"zero":0,"false":false,"null":null}})", .game = "future"}, .expectation = { + .checkpoint = "x", .execution = R"({"zero":0,"false":false,"null":null})", .events = {}}}, +}; + +std::string check_loaded(const AuthoredCheckpoint& actual, const AuthoredCase& test){ + if (test.expectation.failure != Failure::NONE){ + return "Expected rejection, read accepted authored checkpoint."; + } + if (actual.checkpoint.id != test.expectation.checkpoint){ + return "Expected checkpoint " + test.expectation.checkpoint + ", read " + actual.checkpoint.id; + } + if (!(JsonValue(actual.execution.clone()) == parse_json(test.expectation.execution))){ + return "Expected execution " + test.expectation.execution + ", read " + actual.execution.dump(); + } + std::vector events; + for (const StoryStep& step : actual.checkpoint.steps){ + events.push_back(step.name); + } + if (events != test.expectation.events){ + return "Expected authored event IDs in their original order."; + } + const JsonValue encoded = authored_checkpoint_json(actual.checkpoint, test.input.game, actual.execution.clone()); + const AuthoredCheckpoint reread = read_authored_checkpoint(encoded, test.input.game, test.input.name); + if (!(story_checkpoint_json(actual.checkpoint) == story_checkpoint_json(reread.checkpoint)) || actual.execution != reread.execution){ + return "Expected checkpoint and execution to survive the shared writer/reader round trip."; + } + return ""; +} + +std::string check_case(const AuthoredCase& test){ + try{ + const std::vector> files = {{"plan", test.input.json}}; + const AuthoredCheckpoint actual = test.input.resource + ? load_authored_checkpoint(files, test.input.file, test.input.game) + : read_authored_checkpoint(parse_json(test.input.json), test.input.game, test.input.name); + return check_loaded(actual, test); + }catch (const ParseException& error){ + return test.expectation.failure == Failure::PARSE ? "" : "Unexpected parse failure: " + error.message(); + }catch (const InternalProgramError& error){ + return test.expectation.failure == Failure::MISSING_RESOURCE ? "" : "Unexpected resource failure: " + error.message(); + } +} + +#ifndef PA_STORY_DATA_STANDALONE +class AuthoredJsonTest : public UnitTest{ +public: + explicit AuthoredJsonTest(AuthoredCase test) + : UnitTest("Pokemon::AuthoredCheckpointJson - " + test.input.name), m_case(std::move(test)){} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string error = check_case(m_case); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } +private: + AuthoredCase m_case; +}; +#endif + +} // namespace + +#ifndef PA_STORY_DATA_STANDALONE +void add_tests_AuthoredCheckpointJson(UnitTestDatabase& database){ + for (const AuthoredCase& test : CASES){ + database.add(test); + } +} +#endif + +} // namespace Pokemon +} // namespace PokemonAutomation + +#ifdef PA_STORY_DATA_STANDALONE +int main(){ + int failed = 0; + for (const auto& test : PokemonAutomation::Pokemon::CASES){ + const std::string error = PokemonAutomation::Pokemon::check_case(test); + std::cout << test.input.name << ": " << (error.empty() ? "PASS" : error) << '\n'; + failed += !error.empty(); + } + return failed != 0; +} +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 0d139a39f4..5d0bbe1172 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -19,9 +19,17 @@ namespace Pokemon{ void add_tests_StoryEvents(UnitTestDatabase& database); // Registers unit tests for story segment running, verification, and branching. void add_tests_StorySegments(UnitTestDatabase& database); +// Registers unit tests for high-level story step dispatching and table conversion. +void add_tests_StorySteps(UnitTestDatabase& database); +// Lossless shared story-data wire contract. +void add_tests_StoryStepJson(UnitTestDatabase& database); + +// Shared authored envelope, game identity and embedded-resource loading. +void add_tests_AuthoredCheckpointJson(UnitTestDatabase& database); + } // namespace Pokemon } // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp index d355460da3..ad22d7a6a7 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp @@ -68,6 +68,11 @@ Outcome outcome_ok(Pose pose){ outcome.pose = std::move(pose); return outcome; } +Outcome outcome_unchanged(){ + Outcome outcome; + outcome.changed_nothing = true; + return outcome; +} Outcome outcome_failed(std::string failure, std::string detail){ Outcome outcome; outcome.failure = std::move(failure); @@ -78,6 +83,10 @@ std::string to_string(const Outcome& outcome){ return outcome.detail.empty() ? outcome.failure : outcome.failure + ": " + outcome.detail; } +Outcome outcome_game_not_running(){ + return outcome_failed(GAME_NOT_RUNNING, "the game is not running: the Switch HOME menu is showing"); +} + Condition condition(std::string name, Check check){ return Condition{std::move(name), std::move(check)}; } @@ -156,6 +165,8 @@ Outcome attempt_event(Event& event, RunState& state){ return check_expects(event, state); } +} // namespace + void apply_interrupt_pose(Pose& pose, InterruptPose effect){ switch (effect){ case InterruptPose::UNCHANGED: @@ -172,6 +183,8 @@ void apply_interrupt_pose(Pose& pose, InterruptPose effect){ } } +namespace{ + // One event being run, with what it has used up. struct EventRun{ @@ -257,6 +270,9 @@ Recovery* next_recovery(EventRun& run, const std::string& failure){ // is answered in turn, so escalation goes on from there. std::optional recover(EventRun& run, Outcome failure){ while (true){ + if (failure.failure == GAME_NOT_RUNNING){ + return failure; + } Recovery* recovery = next_recovery(run, failure.failure); if (recovery == nullptr){ return failure; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h index 0a2673ff38..388ce48b03 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h @@ -97,6 +97,10 @@ struct Outcome{ std::string failure; std::string detail; std::optional pose; + // A succeeded action that left the game as it found it: a read, a + // check, a TM the lead already knows. A reload of the same save undoes + // nothing it did. + bool changed_nothing = false; bool succeeded() const; }; @@ -104,11 +108,20 @@ struct Outcome{ Outcome outcome_ok(); // Constructs a successful event outcome updating the run pose. Outcome outcome_ok(Pose pose); +// outcome_ok() with `changed_nothing`. +Outcome outcome_unchanged(); // Constructs a failed event outcome with reason and optional diagnostic detail. Outcome outcome_failed(std::string failure, std::string detail = ""); // "probe_exhausted: 4 rows": the failure and its detail, if any. std::string to_string(const Outcome& outcome); +// The failure of a step that found the Switch's HOME menu instead of the +// game. Nothing in the story can answer it, as every press goes to the +// console's menus: no recovery runs and no reload, the run stops. +constexpr const char* GAME_NOT_RUNNING = "game_not_running"; +// GAME_NOT_RUNNING, saying so for the run log. +Outcome outcome_game_not_running(); + // Callable action executed for a story event. using Act = MoveOnlyFunction; @@ -189,6 +202,8 @@ struct Interrupt{ InterruptPose pose = InterruptPose::UNCHANGED; ResumePolicy resume = ResumePolicy::RETRY_EVENT; }; +// Writes what an interrupt did (`effect`) into `pose`. +void apply_interrupt_pose(Pose& pose, InterruptPose effect); // Story milestone containing pre/post conditions and a series of events. diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp index 0d112b0170..5653725467 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp @@ -102,22 +102,69 @@ Outcome reload(RunState& state, SegmentHooks& hooks){ return outcome_ok(); } +// The policy's in-place recovery, after each event's own: the game's +// recover hook, if any, then the event again. Counts into `used`. +void add_policy_recoveries(Checkpoint& checkpoint, const SegmentPolicy& policy, SegmentHooks& hooks, size_t& used){ + if (policy.recoveries_per_event == 0){ + return; + } + for (Event& event : checkpoint.events){ + Recovery recovery; + recovery.kind = RecoveryKind::REANCHOR; + recovery.attempts = policy.recoveries_per_event; + recovery.why = "the segment's policy: recover in place before reloading"; + recovery.prepare = [&hooks, &used, name = event.name](RunState& state){ + used++; + return hooks.recover ? hooks.recover(state, name) : outcome_ok(); + }; + event.recoveries.push_back(std::move(recovery)); + } +} + +std::string resets_text(size_t attempts){ + if (attempts == 1){ + return "one-shot"; + } + return std::format("{} reset{}", attempts - 1, attempts == 2 ? "" : "s"); +} + // One row to success, reloading and rebuilding after each failed attempt. -// Returns the last attempt's report, or the reload's failure. +// Returns the last attempt's report, or the reload's failure; `run` says +// how many attempts and recoveries it took. CheckpointReport run_row( RunState& state, const Segment& segment, CheckpointSpec& spec, - const SegmentPolicy& policy, SegmentHooks& hooks, SegmentReport& report + const SegmentPolicy& policy, SegmentHooks& hooks, SegmentReport& report, CheckpointRun& run ){ for (size_t attempt = 1; ; attempt++){ + run.attempts = attempt; Checkpoint checkpoint = spec.build(); if (spec.saves && !checkpoint.save){ checkpoint.save = [&hooks](RunState& state){ return hooks.save ? hooks.save(state) : outcome_failed("no_save_hook"); }; } + add_policy_recoveries(checkpoint, policy, hooks, run.recoveries); EventLogger log = [&hooks](const std::string& line){ say(hooks, line); }; CheckpointReport result = run_checkpoint(state, checkpoint, log); - if (result.completed || attempt >= policy.attempts_per_checkpoint){ + if (result.completed){ + run.passed = true; + say(hooks, std::format( + "[Checkpoint] {}: passed on attempt {} ({}){}", + spec.id, attempt, resets_text(attempt), + run.recoveries == 0 ? "" : std::format(", {} in place", run.recoveries) + )); + return result; + } + const bool not_running = result.failure.failure == GAME_NOT_RUNNING; + if (not_running || policy.stop_at_first_failure){ + say(hooks, std::format("[Segment] {}: {} failed; {}", segment.id, spec.id, not_running + ? "the game is not running, so no reload" + : "stopping at the first failure, the game stays where it failed" + )); + report.stopped_at_first_failure = !not_running; + return result; + } + if (attempt >= policy.attempts_per_checkpoint){ return result; } say(hooks, std::format( @@ -148,6 +195,19 @@ SegmentReport stop_segment(SegmentReport& report, SegmentHooks& hooks, const std } // namespace +bool CheckpointRun::one_shot() const{ + return passed && attempts == 1 && recoveries == 0; +} + +size_t SegmentReport::one_shot_passes() const{ + size_t count = 0; + for (const CheckpointRun& run : runs){ + count += run.one_shot() ? 1 : 0; + } + return count; +} + + SegmentReport run_segment( RunState& state, Segment& segment, const SegmentRange& range, const SegmentPolicy& policy, SegmentHooks& hooks @@ -161,7 +221,8 @@ SegmentReport run_segment( for (size_t c = selected.first; c <= selected.last; c++){ CheckpointSpec& spec = segment.checkpoints[c]; report.checkpoints_run++; - CheckpointReport result = run_row(state, segment, spec, policy, hooks, report); + report.runs.push_back(CheckpointRun{.id = spec.id}); + CheckpointReport result = run_row(state, segment, spec, policy, hooks, report, report.runs.back()); if (!result.completed){ report.failed_checkpoint = spec.id; report.failed_event = result.failed_name; @@ -169,6 +230,7 @@ SegmentReport run_segment( } } report.completed = true; + say(hooks, std::format("[Segment] {}: {} of {} checkpoints one-shot", segment.id, report.one_shot_passes(), report.checkpoints_run)); say(hooks, std::format("[Segment] {}: done, {} checkpoints", segment.id, report.checkpoints_run)); return report; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h index a63b8b4be9..8e2426aee8 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.h @@ -47,10 +47,14 @@ struct Segment{ // What the game lends the runner: how to save, how to reload the last save // (the run state is emptied first; the reload's Outcome says where the // player stands), and where to log. +// `recover`, if set, is the game's way of recovering in place from a failed +// event (re-anchor on a landmark, close a stray dialogue) before the event +// is tried again; see SegmentPolicy::recoveries_per_event. struct SegmentHooks{ Act save; Act reload; EventLogger log; + MoveOnlyFunction recover; // Optional: each [Segment], [Checkpoint] and [Event] line again, // without its tag ("00.03/2 below_oaks_trigger: start"), for the video // overlay, so whoever watches the stream sees the step under way; and, @@ -60,8 +64,16 @@ struct SegmentHooks{ // Retry and timeout configuration for story segment execution. struct SegmentPolicy{ - // Runs of one checkpoint, reloading between them, before the segment stops. + // Runs of one checkpoint, reloading its save between them, before the + // segment stops. size_t attempts_per_checkpoint = 3; + // Lab: stop at the first failed attempt without reloading, leaving the + // game where it failed for a look. + bool stop_at_first_failure = false; + // Times each event may recover in place (SegmentHooks::recover, then + // the event again) once its own recoveries are used up, before its + // checkpoint fails and is reloaded. 0 keeps a failure a reload. + size_t recoveries_per_event = 0; }; // The checkpoints to run, by id, both inclusive. An unset end is the @@ -72,9 +84,22 @@ struct SegmentRange{ }; +// Summary of checkpoint attempts, recoveries, and pass status. +struct CheckpointRun{ + std::string id; + bool passed = false; + size_t attempts = 0; + // In-place recoveries (SegmentPolicy::recoveries_per_event) used, in all attempts. + size_t recoveries = 0; + + bool one_shot() const; +}; + // Execution results and failure diagnostics for a story segment run. struct SegmentReport{ bool completed = false; + // The run stopped at its first failure (SegmentPolicy::stop_at_first_failure). + bool stopped_at_first_failure = false; // Both empty when nothing failed; the event is empty when a start // check, an end check, a save or a reload failed. std::string failed_checkpoint; @@ -83,13 +108,21 @@ struct SegmentReport{ size_t checkpoints_run = 0; // Reloads after failed attempts. size_t reloads = 0; + // Each checkpoint run, in order, the failed one last. + std::vector runs; + + size_t one_shot_passes() const; }; // Runs the checkpoints in `range`, in order. Logs through `hooks.log`, // around the checkpoint lines: // [Segment] 00: start, 3 checkpoints // [Segment] 00: 00.02 failed, reloading for attempt 2/3 +// [Checkpoint] 00.02: passed on attempt 2 (1 reset) +// [Checkpoint] 00.03: passed on attempt 1 (one-shot) +// [Segment] 00: 2 of 3 checkpoints one-shot // [Segment] 00: done, 3 checkpoints +// [Segment] 00: 00.02 failed; stopping at the first failure, the game stays where it failed // [Segment] 00: failed at 00.02 talk_mom: expect_failed: dialogue opened SegmentReport run_segment( RunState& state, Segment& segment, const SegmentRange& range, diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp new file mode 100644 index 0000000000..3ee2f51f6d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp @@ -0,0 +1,355 @@ +/* Story Step JSON + * From: https://github.com/PokemonAutomation/ + */ +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon_StoryStepJson.h" +namespace PokemonAutomation{ +namespace Pokemon{ +namespace{ +constexpr std::array, 15> KINDS{{ + {StoryStepKind::NEW_GAME, "new_game"}, + {StoryStepKind::OPTIONS, "options"}, + {StoryStepKind::ROUTE, "route"}, + {StoryStepKind::LEGS, "legs"}, + {StoryStepKind::STEP, "step"}, + {StoryStepKind::TALK, "talk"}, + {StoryStepKind::ANSWER, "answer"}, + {StoryStepKind::MASH, "scene"}, + {StoryStepKind::BATTLE, "battle"}, + {StoryStepKind::TRAIN, "train"}, + {StoryStepKind::HEAL, "heal"}, + {StoryStepKind::SHOP, "shop"}, + {StoryStepKind::SAVE, "save"}, + {StoryStepKind::READY, "ready"}, + {StoryStepKind::GAME, "game_action"}, +}}; +constexpr std::array, 5> CERTAINTIES{{ + {PoseCertainty::TILE, "tile"}, + {PoseCertainty::COLUMN, "column"}, + {PoseCertainty::ROW, "row"}, + {PoseCertainty::SET, "set"}, + {PoseCertainty::UNKNOWN, "unknown"}, +}}; +constexpr std::array, 4> DIRECTIONS{{ + {Direction::NORTH, "north"}, + {Direction::EAST, "east"}, + {Direction::SOUTH, "south"}, + {Direction::WEST, "west"}, +}}; + +const JsonObject& fields(const JsonValue& value, std::initializer_list keys, std::string_view source){ + const JsonObject& object = value.to_object_throw(std::string(source)); + for (const auto& [key, unused] : object){ + bool known = false; + for (std::string_view allowed : keys){ + known |= key == allowed; + } + if (!known){ + throw ParseException(std::format("{}: unsupported field {}", source, key)); + } + } + return object; +} + +template +Enum read_enum(const std::array, N>& names, const std::string& name, std::string_view source){ + for (const auto& [value, label] : names){ + if (label == name){ + return value; + } + } + throw ParseException(std::format("{}: unsupported value {}", source, name)); +} + +template +std::string enum_name(const std::array, N>& names, Enum value){ + for (const auto& [candidate, label] : names){ + if (candidate == value){ + return std::string(label); + } + } + throw ParseException("Unsupported story enum value."); +} + +int integer(const JsonValue& value, std::string_view source){ + const int64_t number = value.to_integer_throw(std::string(source)); + if (number < std::numeric_limits::min() || number > std::numeric_limits::max()){ + throw ParseException(std::format("{}: coordinate exceeds native int", source)); + } + return (int)number; +} + +size_t count(const JsonValue& value, std::string_view source){ + const int64_t number = value.to_integer_throw(std::string(source)); + if (number < 0 || (uint64_t)number > std::numeric_limits::max()){ + throw ParseException(std::format("{}: count is out of range", source)); + } + return (size_t)number; +} + +JsonValue count_json(size_t value){ + if ((uint64_t)value > (uint64_t)std::numeric_limits::max()){ + throw ParseException("Story count exceeds the wire integer range."); + } + return (uint64_t)value; +} + +JsonArray strings_json(const std::vector& strings){ + JsonArray result; + for (const std::string& value : strings){ + result.push_back(value); + } + return result; +} + +std::vector read_strings(const JsonValue& value, std::string_view source){ + std::vector result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + result.push_back(item.to_string_throw(std::string(source))); + } + return result; +} + +JsonArray legs_json(const std::vector& legs){ + JsonArray result; + for (const StoryLeg& leg : legs){ + JsonObject item; + item["direction"] = enum_name(DIRECTIONS, leg.direction); + item["tiles"] = leg.tiles; + result.push_back(std::move(item)); + } + return result; +} + +std::vector read_legs(const JsonValue& value, std::string_view source){ + std::vector result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + const JsonObject& row = fields(item, {"direction", "tiles"}, source); + result.push_back({.direction = read_enum(DIRECTIONS, row.get_string_throw("direction"), source), + .tiles = integer(row.get_value_throw("tiles"), source)}); + } + return result; +} + +JsonArray items_json(const std::vector& items){ + JsonArray result; + for (const StoryItem& item : items){ + JsonObject row; + row["item"] = item.item; + row["quantity"] = count_json(item.quantity); + result.push_back(std::move(row)); + } + return result; +} + +std::vector read_items(const JsonValue& value, std::string_view source){ + std::vector result; + for (const JsonValue& item : value.to_array_throw(std::string(source))){ + const JsonObject& row = fields(item, {"item", "quantity"}, source); + result.push_back({.item = row.get_string_throw("item"), .quantity = count(row.get_value_throw("quantity"), source)}); + } + return result; +} +StoryStep read_step_options(StoryStep result, const JsonObject& root, std::string_view source){ + if (const JsonValue* field = root.get_value("fight_wild")){ + result.fight_wild = field->to_boolean_throw(); + } + if (const JsonValue* field = root.get_value("yes")){ + result.yes = field->to_boolean_throw(); + } + if (const JsonValue* field = root.get_value("may_lose")){ + result.may_lose = field->to_boolean_throw(); + } + if (const JsonValue* field = root.get_value("battles")){ + result.battles = count(*field, source); + } + return result; +} + +} // namespace + +JsonValue story_pose_json(const Pose& pose){ + JsonObject result; + result["map"] = pose.map; + result["certainty"] = enum_name(CERTAINTIES, pose.certainty); + JsonObject where; + where["kind"] = "unknown"; + if (pose.where){ + const auto* tiles = dynamic_cast(pose.where.get()); + if (!tiles){ + throw ParseException("Unsupported story Position subtype."); + } + where["kind"] = "tiles"; + JsonArray positions; + for (const TilePos& tile : tiles->tiles){ + JsonArray pair; + pair.push_back(tile.x); pair.push_back(tile.y); + positions.push_back(std::move(pair)); + } + where["tiles"] = std::move(positions); + if (tiles->facing){ + where["facing"] = enum_name(DIRECTIONS, *tiles->facing); + } + } + result["where"] = std::move(where); + return result; +} + +Pose read_story_pose(const JsonValue& value, std::string_view source){ + const JsonObject& root = fields(value, {"map", "certainty", "where"}, source); + Pose result; + result.map = root.get_string_throw("map"); + result.certainty = read_enum(CERTAINTIES, root.get_string_throw("certainty"), source); + const JsonObject& where = fields(root.get_value_throw("where"), {"kind", "tiles", "facing"}, source); + const std::string& kind = where.get_string_throw("kind"); + if (kind == "unknown"){ + if (where.size() != 1){ + throw ParseException("Unknown story position has extra fields."); + } + return result; + } + if (kind != "tiles"){ + throw ParseException("Unsupported story position kind."); + } + std::vector tiles; + for (const JsonValue& item : where.get_array_throw("tiles")){ + const JsonArray& pair = item.to_array_throw(std::string(source)); + if (pair.size() != 2){ + throw ParseException("Story tile needs two coordinates."); + } + tiles.push_back({integer(pair[0], source), integer(pair[1], source)}); + } + std::optional facing; + if (const JsonValue* field = where.get_value("facing")){ + facing = read_enum(DIRECTIONS, field->to_string_throw(), source); + } + result.where = std::make_shared(std::move(tiles), facing); + return result; +} + +JsonValue story_step_json(const StoryStep& step){ + JsonObject result; + result["id"] = step.name; + result["kind"] = enum_name(KINDS, step.kind); + if (!step.why.empty()){ + result["why"] = step.why; + } + if (step.target){ + result["target"] = story_pose_json(*step.target); + } + if (step.direction != Direction::NORTH){ + result["direction"] = enum_name(DIRECTIONS, step.direction); + } + if (!step.legs.empty()){ + result["legs"] = legs_json(step.legs); + } + if (step.fight_wild){ + result["fight_wild"] = true; + } + if (!step.yes){ + result["yes"] = false; + } + if (step.may_lose){ + result["may_lose"] = true; + } + if (step.battles){ + result["battles"] = count_json(step.battles); + } + if (!step.items.empty()){ + result["items"] = items_json(step.items); + } + if (!step.variant.empty()){ + result["variant"] = step.variant; + } + if (!step.skip_if.empty()){ + result["skip_if"] = strings_json(step.skip_if); + } + if (step.pose_after){ + result["declared_after"] = story_pose_json(*step.pose_after); + } + return result; +} + +StoryStep read_story_step(const JsonValue& value, std::string_view source){ + const JsonObject& root = fields(value, {"id", "kind", "why", "target", "direction", "legs", "fight_wild", "yes", + "may_lose", "battles", "items", "variant", "skip_if", "declared_after"}, source); + StoryStep result; + result.name = root.get_string_throw("id"); + if (result.name.empty()){ + throw ParseException("Empty story step id."); + } + result.kind = read_enum(KINDS, root.get_string_throw("kind"), source); + if (const JsonValue* field = root.get_value("why")){ + result.why = field->to_string_throw(); + } + if (const JsonValue* field = root.get_value("target")){ + result.target = read_story_pose(*field, source); + } + if (const JsonValue* field = root.get_value("direction")){ + result.direction = read_enum(DIRECTIONS, field->to_string_throw(), source); + } + if (const JsonValue* field = root.get_value("legs")){ + result.legs = read_legs(*field, source); + } + result = read_step_options(std::move(result), root, source); + if (const JsonValue* field = root.get_value("items")){ + result.items = read_items(*field, source); + } + if (const JsonValue* field = root.get_value("variant")){ + result.variant = field->to_string_throw(); + } + if (const JsonValue* field = root.get_value("skip_if")){ + result.skip_if = read_strings(*field, source); + } + if (const JsonValue* field = root.get_value("declared_after")){ + result.pose_after = read_story_pose(*field, source); + } + return result; +} + +JsonValue story_checkpoint_json(const StoryCheckpoint& checkpoint){ + JsonObject result; + result["id"] = checkpoint.id; + result["title"] = checkpoint.title; + if (checkpoint.start){ + result["start"] = story_pose_json(*checkpoint.start); + } + JsonArray events; + for (const StoryStep& step : checkpoint.steps){ + events.push_back(story_step_json(step)); + } + result["events"] = std::move(events); + return result; +} + +StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view source){ + const JsonObject& root = fields(value, {"id", "title", "start", "events"}, source); + StoryCheckpoint result; + result.id = root.get_string_throw("id"); + if (result.id.empty()){ + throw ParseException("Empty story checkpoint id."); + } + result.title = root.get_string_throw("title"); + if (const JsonValue* start = root.get_value("start")){ + result.start = read_story_pose(*start, source); + } + std::set names; + for (const JsonValue& event : root.get_array_throw("events")){ + StoryStep step = read_story_step(event, source); + if (step.name.empty() || !names.insert(step.name).second){ + throw ParseException("Empty or duplicate story event id."); + } + result.steps.push_back(std::move(step)); + } + return result; +} +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.h new file mode 100644 index 0000000000..d58fd9828c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.h @@ -0,0 +1,26 @@ +/* Story Step JSON + * From: https://github.com/PokemonAutomation/ + */ +#ifndef PokemonAutomation_StoryStepJson_H +#define PokemonAutomation_StoryStepJson_H +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon_StorySteps.h" +namespace PokemonAutomation{ +namespace Pokemon{ +// Lossless tile-game pose data, including uncertainty and absent position/facing. +// An unsupported Position subtype fails instead of being converted to unknown. +JsonValue story_pose_json(const Pose& pose); +// Read a tile-game pose; malformed fields and unsupported position tags fail. +Pose read_story_pose(const JsonValue& value, std::string_view source); +// Encode every shared step field. This does not bind or execute an action. +JsonValue story_step_json(const StoryStep& step); +// Read the shared step record; unknown fields/kinds and invalid values fail. +StoryStep read_story_step(const JsonValue& value, std::string_view source); +// Encode the common checkpoint; game adapters supply the shared policy/state envelope. +JsonValue story_checkpoint_json(const StoryCheckpoint& checkpoint); +// Read only the common checkpoint record, retaining ordered steps and start belief. +StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view source); +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp new file mode 100644 index 0000000000..021b18f508 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp @@ -0,0 +1,150 @@ +/* Story Step JSON Tests + * From: https://github.com/PokemonAutomation/ + */ +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Pokemon_StoryStepJson.h" +#ifndef PA_STORY_DATA_STANDALONE +#include "Pokemon_AutoStory_Tests.h" +#endif +namespace PokemonAutomation{ +namespace Pokemon{ +namespace{ +enum class Record{ POSE, STEP, CHECKPOINT }; +struct WireInput{ + std::string_view name; + Record record = Record::STEP; + std::string_view json; +}; +struct WireExpectation{ + std::string_view canonical = {}; + bool rejected = false; +}; +struct WireCase{ + WireInput input; + WireExpectation expectation; +}; +const WireCase CASES[] = { + {.input = {.name = "default fields", .json = R"({"id":"talk","kind":"talk"})"}, .expectation = {.canonical = R"({"id":"talk","kind":"talk"})"}}, + {.input = {.name = "all shared fields", .json = R"({"id":"all","kind":"game_action","why":"source reason","direction":"west","legs":[{"direction":"south","tiles":0}],"fight_wild":true,"yes":false,"may_lose":true,"battles":3,"items":[{"item":"potion","quantity":0}],"variant":"profile","skip_if":["flag"],"target":{"map":"A","certainty":"unknown","where":{"kind":"unknown"}},"declared_after":{"map":"B","certainty":"set","where":{"kind":"tiles","tiles":[[0,0],[1,0]],"facing":"east"}}})"}, .expectation = {.canonical = R"({"id":"all","kind":"game_action","why":"source reason","direction":"west","legs":[{"direction":"south","tiles":0}],"fight_wild":true,"yes":false,"may_lose":true,"battles":3,"items":[{"item":"potion","quantity":0}],"variant":"profile","skip_if":["flag"],"target":{"map":"A","certainty":"unknown","where":{"kind":"unknown"}},"declared_after":{"map":"B","certainty":"set","where":{"kind":"tiles","tiles":[[0,0],[1,0]],"facing":"east"}}})"}}, + {.input = {.name = "unknown facing stays absent", .record = Record::POSE, .json = R"({"map":"M","certainty":"tile","where":{"kind":"tiles","tiles":[[0,0]]}})"}, .expectation = {.canonical = R"({"map":"M","certainty":"tile","where":{"kind":"tiles","tiles":[[0,0]]}})"}}, + {.input = {.name = "empty position differs from no position", .record = Record::POSE, .json = R"({"map":"M","certainty":"unknown","where":{"kind":"tiles","tiles":[]}})"}, .expectation = {.canonical = R"({"map":"M","certainty":"unknown","where":{"kind":"tiles","tiles":[]}})"}}, + {.input = {.name = "ordered checkpoint", .record = Record::CHECKPOINT, .json = R"({"id":"00.05","title":"Parcel","events":[{"id":"first","kind":"route"},{"id":"second","kind":"scene"}]})"}, .expectation = {.canonical = R"({"id":"00.05","title":"Parcel","events":[{"id":"first","kind":"route"},{"id":"second","kind":"scene"}]})"}}, + {.input = {.name = "unknown field", .json = R"({"id":"a","kind":"talk","mystery":0})"}, .expectation = {.rejected = true}}, + {.input = {.name = "unknown action", .json = R"({"id":"a","kind":"magic"})"}, .expectation = {.rejected = true}}, + {.input = {.name = "negative count", .json = R"({"id":"a","kind":"train","battles":-1})"}, .expectation = {.rejected = true}}, + {.input = {.name = "boolean count", .json = R"({"id":"a","kind":"train","battles":false})"}, .expectation = {.rejected = true}}, + {.input = {.name = "wrong bool", .json = R"({"id":"a","kind":"answer","yes":0})"}, .expectation = {.rejected = true}}, + {.input = {.name = "unknown position", .record = Record::POSE, .json = R"({"map":"M","certainty":"unknown","where":{"kind":"gps"}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "bad coordinate", .record = Record::POSE, .json = R"({"map":"M","certainty":"tile","where":{"kind":"tiles","tiles":[[0,true]]}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "duplicate events", .record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[{"id":"a","kind":"talk"},{"id":"a","kind":"talk"}]})"}, .expectation = {.rejected = true}}, +}; + +JsonValue round_trip(const WireInput& input){ + const JsonValue value = parse_json(std::string(input.json)); + switch (input.record){ + case Record::POSE: return story_pose_json(read_story_pose(value, input.name)); + case Record::STEP: return story_step_json(read_story_step(value, input.name)); + case Record::CHECKPOINT: return story_checkpoint_json(read_story_checkpoint(value, input.name)); + } + throw ParseException("Unknown test record."); +} + +std::string check_case(const WireCase& test){ + try{ + const JsonValue actual = round_trip(test.input); + if (test.expectation.rejected){ + return "Expected rejection, read accepted record."; + } + const JsonValue expected = parse_json(std::string(test.expectation.canonical)); + if (!(actual == expected)){ + return "Expected " + expected.dump() + ", read " + actual.dump(); + } + }catch (const ParseException& error){ + return test.expectation.rejected ? "" : "Unexpected parse failure: " + error.message(); + } + return ""; +} +#ifdef PA_STORY_DATA_STANDALONE +Record record_kind(const std::string& name){ + if (name == "pose"){ + return Record::POSE; + } + if (name == "step"){ + return Record::STEP; + } + if (name == "checkpoint"){ + return Record::CHECKPOINT; + } + throw ParseException("Unsupported shared case record kind."); +} + +int check_shared_file(const std::string& filename){ + const JsonValue document = load_json_file(filename); + const JsonObject& root = document.to_object_throw(filename); + if (root.get_string_throw("format") != "pokesim-story-wire-cases/1"){ + throw ParseException("Unsupported story wire case format."); + } + int failed = 0; + for (const JsonValue& value : root.get_array_throw("cases")){ + const JsonObject& row = value.to_object_throw(filename); + const JsonObject& input = row.get_object_throw("input"); + const JsonObject& expected = row.get_object_throw("expectation"); + const std::string source = input.get_value_throw("value").dump(); + const JsonValue* normalized = expected.get_value("canonical"); + const std::string canonical = normalized ? normalized->dump() : ""; + const JsonValue* rejected = expected.get_value("rejected"); + const WireCase test{ + .input = {.name = input.get_string_throw("name"), .record = record_kind(input.get_string_throw("record")), .json = source}, + .expectation = {.canonical = canonical, .rejected = rejected && rejected->to_boolean_throw()}, + }; + const std::string error = check_case(test); + if (!error.empty()){ + std::cerr << test.input.name << ": " << error << '\n'; + failed++; + } + } + std::cout << "Checked " << root.get_array_throw("cases").size() << " shared story records.\n"; + return failed != 0; +} +#endif + +#ifndef PA_STORY_DATA_STANDALONE +class StoryJsonTest : public UnitTest{ +public: + explicit StoryJsonTest(WireCase test) + : UnitTest("Pokemon::StoryStepJson - " + std::string(test.input.name)), m_case(test){} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string error = check_case(m_case); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } +private: + WireCase m_case; +}; +#endif +} // namespace +#ifndef PA_STORY_DATA_STANDALONE +void add_tests_StoryStepJson(UnitTestDatabase& database){ + for (const WireCase& test : CASES){ + database.add(test); + } +} +#endif +} // namespace Pokemon +} // namespace PokemonAutomation +#ifdef PA_STORY_DATA_STANDALONE +int main(int argc, char** argv){ + if (argc == 2){ + return PokemonAutomation::Pokemon::check_shared_file(argv[1]); + } + int failed = 0; + for (const auto& test : PokemonAutomation::Pokemon::CASES){ + const std::string error = PokemonAutomation::Pokemon::check_case(test); + std::cout << test.input.name << ": " << (error.empty() ? "PASS" : error) << '\n'; + failed += !error.empty(); + } + return failed != 0; +} +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp new file mode 100644 index 0000000000..3004ba6013 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp @@ -0,0 +1,325 @@ +/* Story Steps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Pokemon_StorySteps.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const char* story_step_kind_name(StoryStepKind kind){ + switch (kind){ + case StoryStepKind::NEW_GAME: + return "NEW_GAME"; + case StoryStepKind::OPTIONS: + return "OPTIONS"; + case StoryStepKind::ROUTE: + return "ROUTE"; + case StoryStepKind::LEGS: + return "LEGS"; + case StoryStepKind::STEP: + return "STEP"; + case StoryStepKind::TALK: + return "TALK"; + case StoryStepKind::ANSWER: + return "ANSWER"; + case StoryStepKind::MASH: + return "MASH"; + case StoryStepKind::BATTLE: + return "BATTLE"; + case StoryStepKind::TRAIN: + return "TRAIN"; + case StoryStepKind::HEAL: + return "HEAL"; + case StoryStepKind::SHOP: + return "SHOP"; + case StoryStepKind::SAVE: + return "SAVE"; + case StoryStepKind::READY: + return "READY"; + case StoryStepKind::GAME: + return "GAME"; + } + return "?"; +} + + +const char* story_checks_name(StoryChecks checks){ + switch (checks){ + case StoryChecks::THOROUGH: + return "thorough"; + case StoryChecks::FAST: + return "fast"; + } + return "?"; +} + + +Outcome unsupported_step(const StoryStep& step){ + return outcome_failed("unsupported_step", std::format("{} {}", story_step_kind_name(step.kind), step.name)); +} + +Outcome StoryStepExecutor::run(RunState& state, const StoryStep& step){ + return dispatch_story_step(*this, state, step); +} + +void StoryStepExecutor::begin_attempt(const StoryCheckpoint&){} + +bool StoryStepExecutor::holds(const std::string& condition, RunState& state){ + return state.flags.contains(condition); +} + +Outcome StoryStepExecutor::new_game(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::options(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::route(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::legs(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::step(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::talk(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::answer(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::mash(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::battle(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::train(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::heal(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::shop(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::save(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::ready(RunState&, const StoryStep& step){ + return unsupported_step(step); +} +Outcome StoryStepExecutor::game(RunState&, const StoryStep& step){ + return unsupported_step(step); +} + +Outcome dispatch_story_step(StoryStepExecutor& executor, RunState& state, const StoryStep& step){ + switch (step.kind){ + case StoryStepKind::NEW_GAME: + return executor.new_game(state, step); + case StoryStepKind::OPTIONS: + return executor.options(state, step); + case StoryStepKind::ROUTE: + return executor.route(state, step); + case StoryStepKind::LEGS: + return executor.legs(state, step); + case StoryStepKind::STEP: + return executor.step(state, step); + case StoryStepKind::TALK: + return executor.talk(state, step); + case StoryStepKind::ANSWER: + return executor.answer(state, step); + case StoryStepKind::MASH: + return executor.mash(state, step); + case StoryStepKind::BATTLE: + return executor.battle(state, step); + case StoryStepKind::TRAIN: + return executor.train(state, step); + case StoryStepKind::HEAL: + return executor.heal(state, step); + case StoryStepKind::SHOP: + return executor.shop(state, step); + case StoryStepKind::SAVE: + return executor.save(state, step); + case StoryStepKind::READY: + return executor.ready(state, step); + case StoryStepKind::GAME: + return executor.game(state, step); + } + return unsupported_step(step); +} + + +Event story_event(const StoryStep& step, StoryStepExecutor& executor){ + Event event; + event.name = step.name; + event.why = step.why; + for (const std::string& name : step.skip_if){ + event.skip_if.push_back(condition(name, [&executor, name](RunState& state){ + return executor.holds(name, state); + })); + } + event.act = [&executor, &step](RunState& state){ + return executor.run(state, step); + }; + event.pose_learned = step.pose_after; + return event; +} + +namespace{ + +// The first event of a checkpoint that starts from a save: where the save +// leaves the player, for a run that reloaded it. +Event from_save_event(const Pose& start){ + Event event; + event.name = "from_save"; + event.why = "where the checkpoint's save leaves the player"; + event.act = [](RunState&){ return outcome_ok(); }; + event.pose_learned = start; + return event; +} + +} // namespace + +Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor& executor){ + executor.begin_attempt(data); + Checkpoint checkpoint; + checkpoint.id = data.id; + if (data.start){ + checkpoint.events.push_back(from_save_event(*data.start)); + } + for (const StoryStep& step : data.steps){ + checkpoint.events.push_back(story_event(step, executor)); + } + return checkpoint; +} + +namespace{ + +// `event`, for a once_per_save step known in `prepared` as `key`: skipped +// while `prepared` has it, and added to it when it succeeds changing +// nothing. +void run_once_per_save(Event& event, std::string key, PreparedSteps& prepared){ + event.skip_if.push_back(condition("done_from_this_save", [&prepared, key](RunState&){ + return prepared.contains(key); + })); + event.act = [act = std::move(event.act), &prepared, key](RunState& state) mutable{ + Outcome outcome = act(state); + if (outcome.succeeded() && outcome.changed_nothing){ + prepared.insert(key); + } + return outcome; + }; +} + +} // namespace + +Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor& executor, PreparedSteps& prepared){ + Checkpoint checkpoint = build_story_checkpoint(data, executor); + // After "from_save", the events are the steps in order. + const size_t first = data.start ? 1 : 0; + for (size_t c = 0; c < data.steps.size(); c++){ + if (data.steps[c].once_per_save){ + run_once_per_save(checkpoint.events[first + c], data.id + "/" + data.steps[c].name, prepared); + } + } + return checkpoint; +} + + +namespace{ + +// What a step of its kind must have, or "" if it has it. +std::string missing_field(const StoryStep& step){ + switch (step.kind){ + case StoryStepKind::ROUTE: + case StoryStepKind::READY: + return step.target ? "" : "no target"; + case StoryStepKind::LEGS: + if (step.legs.empty()){ + return "no legs"; + } + for (const StoryLeg& leg : step.legs){ + if (leg.tiles <= 0){ + return "a leg of no tiles"; + } + } + return ""; + case StoryStepKind::TRAIN: + return step.battles > 0 ? "" : "no battles"; + case StoryStepKind::SHOP: + return step.items.empty() ? "no items" : ""; + case StoryStepKind::GAME: + return step.variant.empty() ? "no variant" : ""; + default: + return ""; + } +} + +} // namespace + +std::vector lint_story_checkpoint(const StoryCheckpoint& data){ + std::vector problems; + if (data.id.empty()){ + problems.emplace_back("a checkpoint has no id"); + } + std::set names; + for (size_t c = 0; c < data.steps.size(); c++){ + const StoryStep& step = data.steps[c]; + const std::string where = std::format("{} step {}", data.id, c + 1); + if (step.name.empty()){ + problems.emplace_back(where + ": no name"); + }else if (!names.insert(step.name).second){ + problems.emplace_back(std::format("{}: a second step named {}", where, step.name)); + } + const std::string missing = missing_field(step); + if (!missing.empty()){ + problems.emplace_back(std::format("{} {}: {} {}", where, step.name, story_step_kind_name(step.kind), missing)); + } + // skip_if's conditions must all hold; once per save is one more. + if (step.once_per_save && !step.skip_if.empty()){ + problems.emplace_back(std::format("{} {}: once per save with skip_if", where, step.name)); + } + } + return problems; +} + + +void record_story_stats(AutoStoryStats& stats, const SegmentReport& report){ + stats.m_segment++; + for (const CheckpointRun& run : report.runs){ + if (run.passed){ + stats.m_checkpoint++; + } + } + stats.m_reset += report.reloads; +} + + +Pose tile_pose(std::string map, std::vector tiles, std::optional facing){ + Pose pose; + pose.map = std::move(map); + pose.certainty = tiles.empty() ? PoseCertainty::UNKNOWN + : tiles.size() == 1 ? PoseCertainty::TILE : PoseCertainty::SET; + pose.where = std::make_shared(std::move(tiles), facing); + return pose; +} + +std::optional facing_of(const Pose& pose){ + const TilePose* tile_pose = dynamic_cast(pose.where.get()); + return tile_pose ? tile_pose->facing : std::nullopt; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h new file mode 100644 index 0000000000..27aaabad8a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h @@ -0,0 +1,261 @@ +/* Story Steps + * + * From: https://github.com/PokemonAutomation/ + * + * One vocabulary of story steps for the tile games (FRLG, BDSP): a route, + * a fixed walk, a step onto a trigger, a talk, a YES/NO, a scene, a + * battle, the nurse, a shop, a save, and so on. A checkpoint is a list of + * such steps, plain data, so a game's story is a table its unit tests can + * plan without a console. + * + * build_story_checkpoint() turns a table row into engine events + * (Pokemon_StoryEvents.h). Each event's action asks the game's + * StoryStepExecutor to do its step: one virtual per kind, so a game + * implements the kinds it uses, and a step the game has no way of doing + * fails by name instead of doing something else. + * + * Steps never match dialogue or menu text: they look for screen state (a + * dialogue box, an arrow, a fade, a battle menu, colours, positions). The + * few reads that need text (item names in a shop or the Bag) take the + * game's language from the executor, and with no reader for it fall back + * to checks that need none (a row's position, digits, a changed screen), + * so a run never fails because its language is not supported. + * + * Poses are the game's own (Pose, with a TilePose for these games): a + * checkpoint's start, a scene's end and a route's target are poses, and + * an executor that knows where a step left the player says so in its + * Outcome, which the engine writes into the run. + * + */ + +#ifndef PokemonAutomation_Pokemon_StorySteps_H +#define PokemonAutomation_Pokemon_StorySteps_H + +#include +#include +#include +#include +#include +#include "CommonFramework/Language.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "Pokemon_AutoStoryStats.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_StorySegments.h" +#include "Pokemon_TilePose.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Action category classification for individual story steps. +enum class StoryStepKind{ + NEW_GAME, // title screen (no save) to the first room + OPTIONS, // the game's options as the story needs them + ROUTE, // plan and walk to `target` + LEGS, // walk `legs` as given + STEP, // one step `direction`: onto a trigger, into a door + TALK, // A at what the player faces + ANSWER, // text to a YES/NO, then `yes` + MASH, // text until the overworld is back: a scene + BATTLE, // text into a battle, fight it, text to the overworld + TRAIN, // fight `battles` wild battles where the player stands + HEAL, // the nurse, from in front of her or of the Center's door + SHOP, // `items` from a shop + SAVE, // save the game where the player stands + READY, // before a big battle: items, and the nurse at `target` if they can't + GAME, // a step only this game has, named by `variant` +}; +// Returns the readable string representation of a story step kind. +const char* story_step_kind_name(StoryStepKind kind); + +// How much a step reads the screen to confirm what it did. Each game +// decides what its steps check at each level. +enum class StoryChecks{ + // Confirm on screen: purchases, the Bag, status after battles, position. + THOROUGH, + // In a rush: trust counts and timings. + FAST, +}; +// Returns the readable string representation of a story check level. +const char* story_checks_name(StoryChecks checks); + + +// A straight leg of a fixed walk. +struct StoryLeg{ + Direction direction = Direction::NORTH; + int tiles = 0; +}; + +// An item and how many to get. +struct StoryItem{ + std::string item; + size_t quantity = 0; +}; + +// Specification of an atomic story task with actions and postconditions. +struct StoryStep{ + StoryStepKind kind = StoryStepKind::TALK; + std::string name; + std::string why; + + // ROUTE: where to go; with several tiles, any of them. READY: the nurse. + std::optional target; + // STEP + Direction direction = Direction::NORTH; + // LEGS + std::vector legs; + // ROUTE, LEGS: fight wild battles on the way instead of running. + bool fight_wild = false; + // ANSWER + bool yes = true; + // BATTLE: losing goes on (a rival's first battle). + bool may_lose = false; + // TRAIN + size_t battles = 0; + // SHOP + std::vector items; + // How this game does the kind, when it has more than one way: a + // route's plan costs, a door lined up by sight, the Mart lady instead + // of the clerk. Empty is the game's usual way. GAME: the step's name + // in the game's executor. + std::string variant; + + // Skipped when all of these hold (and there is at least one): names + // the game's executor answers (StoryStepExecutor::holds()), run flags + // unless the game reads them off the screen. + std::vector skip_if; + // Preparation for what follows, done once per save: a TEACH, a check, + // a read. Once it has succeeded and changed nothing + // (Outcome::changed_nothing), the attempts after a reload of the same + // save skip it, so a retry goes from the reload straight to the + // battle. One that changed the game (a TM taught) runs again, as the + // reload undid it. Only with build_story_checkpoint()'s PreparedSteps. + bool once_per_save = false; + // Where the step leaves the player, when its action does not say: the + // end of a scene that moves the player. + std::optional pose_after; +}; + +// Milestone row in the story table grouping related steps and starting pose. +struct StoryCheckpoint{ + std::string id; + std::string title; + // Where its starting save leaves the player; none for a new game. + std::optional start; + std::vector steps; +}; + + +// How a game does each kind of step. Every kind fails as unsupported +// unless the game overrides it. +class StoryStepExecutor{ +public: + virtual ~StoryStepExecutor() = default; + + // A checkpoint is being built for a new attempt: build_story_checkpoint() + // calls this first, so a game can start the attempt afresh (trainers + // who can see us again, the row's own settings). Does nothing by default. + virtual void begin_attempt(const StoryCheckpoint& data); + + // The checks level the program's options chose (StoryRunOptions); + // THOROUGH unless set. Steps read it to decide what to confirm. + StoryChecks checks() const{ + return m_checks; + } + void set_checks(StoryChecks checks){ + m_checks = checks; + } + // The game's language (StoryRunOptions), for the reads that need text; + // English unless set. A game with no reader for it uses language-free + // checks instead. + Language language() const{ + return m_language; + } + void set_language(Language language){ + m_language = language; + } + + // Runs `step`: dispatch_story_step() by default. A game overrides it + // to wrap every step, e.g. to turn a failed console step into a failed + // Outcome. + virtual Outcome run(RunState& state, const StoryStep& step); + + // Whether the condition named in a step's skip_if holds: by default, + // whether the run has the flag (set by an earlier step's action). + virtual bool holds(const std::string& condition, RunState& state); + +protected: + // One per step kind, called by dispatch_story_step(); each fails as + // unsupported unless the game overrides it. + friend Outcome dispatch_story_step(StoryStepExecutor& executor, RunState& state, const StoryStep& step); + virtual Outcome new_game(RunState& state, const StoryStep& step); + virtual Outcome options(RunState& state, const StoryStep& step); + virtual Outcome route(RunState& state, const StoryStep& step); + virtual Outcome legs(RunState& state, const StoryStep& step); + virtual Outcome step(RunState& state, const StoryStep& step); + virtual Outcome talk(RunState& state, const StoryStep& step); + virtual Outcome answer(RunState& state, const StoryStep& step); + virtual Outcome mash(RunState& state, const StoryStep& step); + virtual Outcome battle(RunState& state, const StoryStep& step); + virtual Outcome train(RunState& state, const StoryStep& step); + virtual Outcome heal(RunState& state, const StoryStep& step); + virtual Outcome shop(RunState& state, const StoryStep& step); + virtual Outcome save(RunState& state, const StoryStep& step); + virtual Outcome ready(RunState& state, const StoryStep& step); + virtual Outcome game(RunState& state, const StoryStep& step); + +private: + StoryChecks m_checks = StoryChecks::THOROUGH; + Language m_language = Language::English; +}; + +// Calls the executor's method for the step's kind. +Outcome dispatch_story_step(StoryStepExecutor& executor, RunState& state, const StoryStep& step); + +// "unsupported_step: TRAIN train_in_grass": what an executor without the kind returns. +Outcome unsupported_step(const StoryStep& step); + + +// The step as an event that runs it with `executor`. Both must outlive +// the event. +Event story_event(const StoryStep& step, StoryStepExecutor& executor); + +// The checkpoint `data` as events: "from_save" first when it has a start +// (the start pose, for a run that reloaded its save), then one event per +// step. `data` and `executor` must outlive the checkpoint. Saving is the +// game's: it sets the checkpoint's save, or adds a SAVE step. +Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor& executor); + +// The once_per_save steps done from the save the game is on that changed +// nothing, as "/". The game keeps it across reloads and +// empties it when it saves or loads another save. +using PreparedSteps = std::set; + +// As above, and each once_per_save step is skipped while `prepared` has +// it, and added to it when it succeeds changing nothing. `prepared` must +// outlive the checkpoint. +Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor& executor, PreparedSteps& prepared); + +// Problems an author should fix before running: an empty id, unnamed or +// repeated steps, a route or READY without a target, empty legs, a GAME +// step without a variant, TRAIN without battles, SHOP without items. +std::vector lint_story_checkpoint(const StoryCheckpoint& data); + + +// Adds a segment's run to the program's stats: the segment, each checkpoint +// that passed, each reload. +void record_story_stats(AutoStoryStats& stats, const SegmentReport& report); + + +// A pose on one of `tiles` of `map`, facing `facing` if set: TILE for one +// tile, SET for several, UNKNOWN for none. +Pose tile_pose(std::string map, std::vector tiles, std::optional facing = std::nullopt); + +// The facing of a tile pose; nothing for another pose or none. +std::optional facing_of(const Pose& pose); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp new file mode 100644 index 0000000000..e61a1eeb95 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp @@ -0,0 +1,854 @@ +/* Story Steps Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Story tables built into checkpoints and run against a fake executor + * that writes down each step it is asked to do: the order of the events, + * skipped steps, the pose each step leaves, and how a failure is named. + * Nothing here belongs to one game. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/Options/Pokemon_StoryRunOptions.h" +#include "Pokemon_StoryEvents.h" +#include "Pokemon_StorySegments.h" +#include "Pokemon_StorySteps.h" +#include "Pokemon_TilePose.h" +#include "Pokemon_AutoStory_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// A world of two maps. Routes arrive on their target; a step moves a tile +// from the run's pose. Each step it does is written down as "KIND name", +// with the pose it started from when that is known. +class FakeExecutor : public StoryStepExecutor{ +public: + std::vector trace; + std::set conditions; + // Steps by name that always fail, and how. + std::set failing; + // Steps by name that fail this many more times, then pass. + std::map failures_left; + // The pose each step started from, by name. + std::vector> poses_seen; + // The checkpoints begun, one per attempt. + std::vector attempts; + // Game steps by name that change nothing in the game. + std::set unchanged; + + virtual void begin_attempt(const StoryCheckpoint& data) override{ + attempts.push_back(data.id); + } + + virtual Outcome run(RunState& state, const StoryStep& step) override{ + poses_seen.emplace_back(step.name, to_string(state.pose)); + trace.push_back(std::string(story_step_kind_name(step.kind)) + " " + step.name); + if (failing.contains(step.name)){ + return outcome_failed("blocked", step.name + " was blocked"); + } + size_t& left = failures_left[step.name]; + if (left > 0){ + left--; + return outcome_failed("blocked", step.name + " was blocked"); + } + return StoryStepExecutor::run(state, step); + } + virtual bool holds(const std::string& condition, RunState& state) override{ + return conditions.contains(condition) || StoryStepExecutor::holds(condition, state); + } + +protected: + virtual Outcome route(RunState&, const StoryStep& step) override{ + return outcome_ok(*step.target); + } + virtual Outcome step(RunState& state, const StoryStep& step) override{ + const std::vector tiles = tiles_of(state.pose); + if (tiles.size() != 1){ + return outcome_failed("no_pose", to_string(state.pose)); + } + return outcome_ok(tile_pose(state.pose.map, {tiles[0].next(step.direction)}, step.direction)); + } + virtual Outcome talk(RunState&, const StoryStep&) override{ + return outcome_ok(); + } + virtual Outcome mash(RunState&, const StoryStep&) override{ + return outcome_ok(); + } + virtual Outcome battle(RunState&, const StoryStep& step) override{ + // The first battle is lost; a step that may lose goes on. + return step.may_lose ? outcome_ok() : outcome_failed("blackout"); + } + virtual Outcome shop(RunState&, const StoryStep& step) override{ + for (const StoryItem& item : step.items){ + trace.push_back(" bought " + std::to_string(item.quantity) + " " + item.item); + } + return outcome_ok(); + } + // A game step sets a run flag named for its variant. + virtual Outcome game(RunState& state, const StoryStep& step) override{ + trace.push_back(" game " + step.variant); + state.flags.insert(step.variant); + return unchanged.contains(step.name) ? outcome_unchanged() : outcome_ok(); + } +}; + +StoryStep make(StoryStepKind kind, std::string name){ + StoryStep step; + step.kind = kind; + step.name = std::move(name); + return step; +} + +StoryStep route_to(std::string name, Pose target){ + StoryStep step = make(StoryStepKind::ROUTE, std::move(name)); + step.target = std::move(target); + return step; +} + +StoryStep step_into(std::string name, Direction direction){ + StoryStep step = make(StoryStepKind::STEP, std::move(name)); + step.direction = direction; + return step; +} + +StoryStep scene(std::string name, std::optional pose_after){ + StoryStep step = make(StoryStepKind::MASH, std::move(name)); + step.pose_after = std::move(pose_after); + return step; +} + +// A lab checkpoint: to the table, a trigger, the scene into the lab, a +// talk, a shop, a game step. +StoryCheckpoint lab_checkpoint(){ + StoryStep shop = make(StoryStepKind::SHOP, "potions"); + shop.items = {{.item = "potion", .quantity = 5}, {.item = "antidote", .quantity = 3}}; + StoryStep game = make(StoryStepKind::GAME, "dance"); + game.variant = "dance"; + return StoryCheckpoint{ + .id = "00.03", + .title = "to the lab", + .start = tile_pose("Town", {{6, 8}}, Direction::SOUTH), + .steps = { + route_to("below_trigger", tile_pose("Town", {{12, 2}}, Direction::NORTH)), + step_into("trigger", Direction::NORTH), + scene("to_the_lab", tile_pose("Lab", {{6, 4}}, Direction::NORTH)), + make(StoryStepKind::TALK, "talk_oak"), + shop, + game, + }, + }; +} + +struct Run{ + CheckpointReport report; + RunState state; + std::vector lines; +}; + +Run run(const StoryCheckpoint& data, StoryStepExecutor& executor){ + Run ret; + Checkpoint checkpoint = build_story_checkpoint(data, executor); + EventLogger log = [&ret](const std::string& line){ ret.lines.push_back(line); }; + ret.report = run_checkpoint(ret.state, checkpoint, log); + return ret; +} + +std::string joined(const std::vector& lines){ + std::string text; + for (const std::string& line : lines){ + text += "\n " + line; + } + return text; +} + + +UnitTestResult test_events_in_table_order(){ + const StoryCheckpoint data = lab_checkpoint(); + FakeExecutor executor; + const Run result = run(data, executor); + const std::vector expected{ + "ROUTE below_trigger", + "STEP trigger", + "MASH to_the_lab", + "TALK talk_oak", + "SHOP potions", + " bought 5 potion", + " bought 3 antidote", + "GAME dance", + " game dance", + }; + if (!result.report.completed || executor.trace != expected){ + return "Expected the steps in table order:" + joined(expected) + "\nbut ran:" + joined(executor.trace); + } + // "from_save" is the engine's own event: the executor is not asked. + const std::string first = event_log_line("00.03", 1, "from_save", "start"); + if (result.lines.empty() || std::find(result.lines.begin(), result.lines.end(), first) == result.lines.end()){ + return "Expected the from_save event first:" + joined(result.lines); + } + return true; +} + +UnitTestResult test_skip_if(){ + StoryCheckpoint data = lab_checkpoint(); + data.steps[0].skip_if = {"has_parcel"}; + data.steps[3].skip_if = {"has_parcel", "talked"}; + FakeExecutor executor; + executor.conditions = {"has_parcel"}; + // The route is skipped; the talk needs both conditions, so it runs. + const Run result = run(data, executor); + if (!result.report.completed || result.report.events_skipped != 1){ + return "Expected one step skipped, got " + std::to_string(result.report.events_skipped) + ":" + joined(result.lines); + } + if (std::find(executor.trace.begin(), executor.trace.end(), "ROUTE below_trigger") != executor.trace.end()){ + return "Expected the route skipped:" + joined(executor.trace); + } + if (std::find(executor.trace.begin(), executor.trace.end(), "TALK talk_oak") == executor.trace.end()){ + return "Expected the talk run, one of its conditions not holding:" + joined(executor.trace); + } + + // By default a condition is a run flag: the game step "dance" sets + // one, and a talk after it that needs it is skipped. + StoryStep after = make(StoryStepKind::TALK, "talk_after_dance"); + after.skip_if = {"dance"}; + data = lab_checkpoint(); + data.steps.push_back(after); + FakeExecutor plain; + const Run flagged = run(data, plain); + if (!flagged.report.completed || flagged.report.events_skipped != 1 || plain.trace.back() != " game dance"){ + return "Expected the talk after the dance skipped on its flag:" + joined(plain.trace); + } + return true; +} + +UnitTestResult test_pose_propagation(){ + const StoryCheckpoint data = lab_checkpoint(); + FakeExecutor executor; + const Run result = run(data, executor); + // Each step starts where the one before left the player: the save, the + // route's target, a tile north of it, the scene's end, and the scene's + // end again after a talk that says nothing of where it leaves us. + const std::vector> expected{ + {"below_trigger", "Town (6, 8) facing south (tile)"}, + {"trigger", "Town (12, 2) facing north (tile)"}, + {"to_the_lab", "Town (12, 1) facing north (tile)"}, + {"talk_oak", "Lab (6, 4) facing north (tile)"}, + {"potions", "Lab (6, 4) facing north (tile)"}, + {"dance", "Lab (6, 4) facing north (tile)"}, + }; + if (!result.report.completed || executor.poses_seen != expected){ + std::string text; + for (const auto& item : executor.poses_seen){ + text += "\n " + item.first + ": " + item.second; + } + return "Unexpected poses at the steps' starts:" + text; + } + if (to_string(result.state.pose) != "Lab (6, 4) facing north (tile)"){ + return "Expected the run to end at the scene's end, got " + to_string(result.state.pose); + } + return true; +} + +UnitTestResult test_failure_names_the_step(){ + const StoryCheckpoint data = lab_checkpoint(); + FakeExecutor executor; + executor.failing = {"trigger"}; + const Run result = run(data, executor); + // Event 3: from_save is event 1. + if (result.report.completed || result.report.failed_event != 3 || result.report.failed_name != "trigger" + || result.report.failure.failure != "blocked" + ){ + return "Expected a failure at event 3 trigger, blocked:" + joined(result.lines); + } + if (executor.trace.size() != 2){ + return "Expected nothing run after the failed step:" + joined(executor.trace); + } + return true; +} + +UnitTestResult test_unsupported_and_lost_battles(){ + // The fake has no TRAIN, and loses battles a step may not lose. + StoryStep train = make(StoryStepKind::TRAIN, "train"); + train.battles = 3; + FakeExecutor executor; + Run result = run(StoryCheckpoint{.id = "01", .title = "", .start = std::nullopt, .steps = {train}}, executor); + if (result.report.completed || result.report.failure.failure != "unsupported_step" || result.report.failure.detail != "TRAIN train"){ + return "Expected TRAIN unsupported:" + joined(result.lines); + } + StoryStep rival = make(StoryStepKind::BATTLE, "rival"); + rival.may_lose = true; + StoryStep brock = make(StoryStepKind::BATTLE, "brock"); + result = run(StoryCheckpoint{.id = "02", .title = "", .start = std::nullopt, .steps = {rival, brock}}, executor); + if (result.report.completed || result.report.failed_name != "brock" || result.report.failure.failure != "blackout"){ + return "Expected the rival's battle passed and Brock's lost:" + joined(result.lines); + } + return true; +} + +// Runs `tables` as one segment whose saves and reloads go into the +// executor's trace and whose log lines go into `lines`. Whatever blocked a +// step has gone by the reload. +SegmentReport run_tables(const std::vector& tables, FakeExecutor& executor, std::vector& lines){ + Segment segment; + segment.id = "00"; + for (const StoryCheckpoint& data : tables){ + segment.checkpoints.push_back(CheckpointSpec{ + .id = data.id, .title = data.title, .saves = true, + .build = [&data, &executor]{ return build_story_checkpoint(data, executor); }, + }); + } + SegmentHooks hooks; + hooks.save = [&executor](RunState&){ + executor.trace.push_back("save"); + return outcome_ok(); + }; + hooks.reload = [&executor](RunState&){ + executor.trace.push_back("reload"); + executor.failing.clear(); + return outcome_ok(); + }; + hooks.log = [&lines](const std::string& line){ lines.push_back(line); }; + RunState state; + return run_segment(state, segment, SegmentRange{}, SegmentPolicy{}, hooks); +} + +UnitTestResult test_segment_of_tables(){ + // Two rows built into a segment, run with saves and a reload from the + // game's hooks: the second row's first attempt fails, its retry starts + // over from its start pose. + const std::vector tables{ + lab_checkpoint(), + StoryCheckpoint{ + .id = "00.04", + .title = "the parcel", + .start = tile_pose("Lab", {{6, 4}}, Direction::NORTH), + .steps = {make(StoryStepKind::TALK, "give_parcel")}, + }, + }; + FakeExecutor executor; + executor.failing = {"give_parcel"}; + std::vector lines; + const SegmentReport report = run_tables(tables, executor, lines); + const std::vector tail{"save", "TALK give_parcel", "reload", "TALK give_parcel", "save"}; + const bool tail_matches = executor.trace.size() >= tail.size() + && std::equal(tail.begin(), tail.end(), executor.trace.end() - (std::ptrdiff_t)tail.size()); + if (!report.completed || report.reloads != 1 || !tail_matches){ + return "Expected 00.04 reloaded once and passed:" + joined(executor.trace) + joined(lines); + } + // Each attempt is begun anew: 00.03 once, 00.04 twice. + if (executor.attempts != std::vector{"00.03", "00.04", "00.04"}){ + return "Expected the executor told of each attempt:" + joined(executor.attempts); + } + // The report and the log tell a one-shot pass from a retried one. + const bool runs_ok = report.runs.size() == 2 + && report.runs[0].one_shot() && report.runs[0].attempts == 1 + && !report.runs[1].one_shot() && report.runs[1].attempts == 2 && report.runs[1].passed + && report.one_shot_passes() == 1; + const auto has = [&lines](const std::string& line){ + return std::find(lines.begin(), lines.end(), line) != lines.end(); + }; + if (!runs_ok + || !has("[Checkpoint] 00.03: passed on attempt 1 (one-shot)") + || !has("[Checkpoint] 00.04: passed on attempt 2 (1 reset)") + || !has("[Segment] 00: 1 of 2 checkpoints one-shot") + ){ + return "Expected 00.03 one-shot and 00.04 passed on attempt 2:" + joined(lines); + } + return true; +} + + +// The two tables of test_segment_of_tables() as a segment run by `executor`, +// with hooks that write saves, reloads and recoveries into its trace. +struct PolicyLab{ + std::vector tables{ + lab_checkpoint(), + StoryCheckpoint{ + .id = "00.04", + .title = "the parcel", + .start = tile_pose("Lab", {{6, 4}}, Direction::NORTH), + .steps = {make(StoryStepKind::TALK, "give_parcel")}, + }, + }; + FakeExecutor executor; + std::vector lines; + + SegmentReport run(const SegmentPolicy& policy){ + Segment segment; + segment.id = "00"; + for (const StoryCheckpoint& data : tables){ + segment.checkpoints.push_back(CheckpointSpec{ + .id = data.id, .title = data.title, .saves = true, + .build = [&data, this]{ return build_story_checkpoint(data, executor); }, + }); + } + SegmentHooks hooks; + hooks.save = [this](RunState&){ + executor.trace.push_back("save"); + return outcome_ok(); + }; + hooks.reload = [this](RunState&){ + executor.trace.push_back("reload"); + return outcome_ok(); + }; + hooks.recover = [this](RunState&, const std::string& event){ + executor.trace.push_back("recover " + event); + return outcome_ok(); + }; + hooks.log = [this](const std::string& line){ lines.push_back(line); }; + RunState state; + return run_segment(state, segment, SegmentRange{}, policy, hooks); + } + bool has(const std::string& line) const{ + return std::find(lines.begin(), lines.end(), line) != lines.end(); + } + size_t count(const std::string& item) const{ + return (size_t)std::count(executor.trace.begin(), executor.trace.end(), item); + } +}; + +UnitTestResult test_policy_attempts_then_fail(){ + // Three attempts by default, then the segment stops on the last one's failure. + PolicyLab lab; + lab.executor.failing = {"give_parcel"}; + const SegmentReport report = lab.run(SegmentPolicy{}); + if (report.completed || report.reloads != 2 || lab.count("TALK give_parcel") != 3 + || report.runs.size() != 2 || report.runs[1].passed || report.runs[1].attempts != 3 + || report.failed_checkpoint != "00.04" || report.failure.failure != "blocked" + ){ + return "Expected 00.04 tried 3 times, then failed:" + joined(lab.executor.trace) + joined(lab.lines); + } + return true; +} + +UnitTestResult test_policy_stop_at_first_failure(){ + PolicyLab lab; + lab.executor.failing = {"give_parcel"}; + const SegmentReport report = lab.run(SegmentPolicy{.stop_at_first_failure = true}); + if (report.completed || !report.stopped_at_first_failure || report.reloads != 0 || lab.count("reload") != 0 + || lab.count("TALK give_parcel") != 1 + || !lab.has("[Segment] 00: 00.04 failed; stopping at the first failure, the game stays where it failed") + ){ + return "Expected a stop at the first failure, with no reload:" + joined(lab.executor.trace) + joined(lab.lines); + } + return true; +} + +UnitTestResult test_policy_recovers_in_place(){ + // The talk fails twice; two recoveries in place get it through + // without a reload, but not one-shot. + PolicyLab lab; + lab.executor.failures_left = {{"give_parcel", 2}}; + const SegmentReport report = lab.run(SegmentPolicy{.recoveries_per_event = 2}); + if (!report.completed || report.reloads != 0 || lab.count("recover give_parcel") != 2 + || report.runs.size() != 2 || report.runs[1].recoveries != 2 || report.runs[1].one_shot() + || !lab.has("[Checkpoint] 00.04: passed on attempt 1 (one-shot), 2 in place") + ){ + return "Expected 00.04 recovered in place twice:" + joined(lab.executor.trace) + joined(lab.lines); + } + // Past the budget, the checkpoint is reloaded as before. + PolicyLab reloaded; + reloaded.executor.failures_left = {{"give_parcel", 2}}; + const SegmentReport second = reloaded.run(SegmentPolicy{.recoveries_per_event = 1}); + if (!second.completed || second.reloads != 1 || second.runs[1].attempts != 2){ + return "Expected a reload once the in-place budget was used:" + joined(reloaded.executor.trace) + joined(reloaded.lines); + } + return true; +} + +// A boss's checkpoint: a TEACH of a move the lead knows (changes +// nothing), a TEACH that teaches, both once per save, then the battle, +// lost on the first attempt. The segment's saves empty `prepared`. +struct BossLab{ + StoryCheckpoint table{ + .id = "00.15b", + .title = "the rival", + .start = tile_pose("Cerulean", {{23, 7}}, Direction::NORTH), + .steps = {once("teach_known"), once("teach_new"), make(StoryStepKind::BATTLE, "rival")}, + }; + FakeExecutor executor; + PreparedSteps prepared; + std::vector lines; + + static StoryStep once(std::string name){ + StoryStep step = make(StoryStepKind::GAME, name); + step.variant = name; + step.once_per_save = true; + return step; + } + BossLab(){ + executor.unchanged = {"teach_known"}; + } + Segment segment(){ + Segment segment; + segment.id = "00"; + segment.checkpoints.push_back(CheckpointSpec{ + .id = table.id, .title = table.title, .saves = true, + .build = [this]{ return build_story_checkpoint(table, executor, prepared); }, + }); + return segment; + } + SegmentHooks hooks(){ + SegmentHooks hooks; + hooks.save = [this](RunState&){ + executor.trace.push_back("save"); + prepared.clear(); + return outcome_ok(); + }; + hooks.reload = [this](RunState&){ + executor.trace.push_back("reload"); + return outcome_ok(); + }; + hooks.log = [this](const std::string& line){ lines.push_back(line); }; + return hooks; + } + size_t count(const std::string& item) const{ + return (size_t)std::count(executor.trace.begin(), executor.trace.end(), item); + } +}; + +// A retry after a reload of the same save skips the preparation that +// changed nothing and goes to the battle; the TEACH that taught runs +// again, as the reload undid it. The save at the end empties the memory. +UnitTestResult test_once_per_save_retry(){ + BossLab lab; + StoryStep battle = make(StoryStepKind::BATTLE, "rival"); + battle.may_lose = true; + lab.table.steps.back() = battle; + lab.executor.failures_left = {{"rival", 1}}; + Segment segment = lab.segment(); + SegmentHooks hooks = lab.hooks(); + RunState state; + const SegmentReport report = run_segment(state, segment, SegmentRange{}, SegmentPolicy{}, hooks); + if (!report.completed || report.reloads != 1 || lab.count("GAME teach_known") != 1 + || lab.count("GAME teach_new") != 2 || lab.count("BATTLE rival") != 2 + ){ + return "Expected the known TEACH once, the new one twice, the battle twice:" + joined(lab.executor.trace) + joined(lab.lines); + } + if (!lab.prepared.empty()){ + return "Expected the save to empty the prepared steps."; + } + return true; +} + +// Verify mode: three runs from one save; the preparation that changed +// nothing runs in the first only. +UnitTestResult test_once_per_save_verify(){ + BossLab lab; + StoryStep battle = make(StoryStepKind::BATTLE, "rival"); + battle.may_lose = true; + lab.table.steps.back() = battle; + Segment segment = lab.segment(); + SegmentHooks hooks = lab.hooks(); + RunState state; + const VerifyReport report = verify_checkpoint(state, segment, "00.15b", VerifyPolicy{}, hooks); + if (!report.verified || report.runs != 3 || lab.count("GAME teach_known") != 1 + || lab.count("GAME teach_new") != 3 || lab.count("BATTLE rival") != 3 + ){ + return "Expected the known TEACH once in 3 runs, the new one each run:" + joined(lab.executor.trace) + joined(lab.lines); + } + // Without the memory, every run prepares. + FakeExecutor plain; + plain.unchanged = {"teach_known"}; + Segment without; + without.id = "00"; + without.checkpoints.push_back(CheckpointSpec{ + .id = lab.table.id, .title = "", .saves = true, + .build = [&]{ return build_story_checkpoint(lab.table, plain); }, + }); + RunState again; + verify_checkpoint(again, without, "00.15b", VerifyPolicy{}, hooks); + if (std::count(plain.trace.begin(), plain.trace.end(), "GAME teach_known") != 3){ + return "Expected every run to prepare without PreparedSteps:" + joined(plain.trace); + } + return true; +} + + +// The checks level: THOROUGH by default, and what the program sets is +// what a step reads. +UnitTestResult test_checks_level(){ + class CheckingExecutor : public FakeExecutor{ + public: + std::vector seen; + virtual Outcome talk(RunState&, const StoryStep& step) override{ + seen.push_back(step.name + " " + story_checks_name(checks())); + return outcome_ok(); + } + }; + StoryCheckpoint data = lab_checkpoint(); + CheckingExecutor executor; + run(data, executor); + executor.set_checks(StoryChecks::FAST); + executor.set_language(Language::Korean); + run(data, executor); + if (executor.language() != Language::Korean){ + return "Expected the language set on the executor."; + } + if (executor.seen != std::vector{"talk_oak thorough", "talk_oak fast"}){ + return "Expected the talk to read thorough, then fast:" + joined(executor.seen); + } + return true; +} + +// Two sections of a story, as BDSP has segments 00 and 01. +const std::vector& two_sections(){ + static const std::vector rows{ + StoryCheckpoint{.id = "00.01", .title = "Leave the house", .start = std::nullopt, .steps = {}}, + StoryCheckpoint{.id = "00.02", .title = "Walk to Sandgem Town", .start = std::nullopt, .steps = {}}, + StoryCheckpoint{.id = "01.01", .title = "Jubilife to Barry", .start = std::nullopt, .steps = {}}, + }; + return rows; +} +const StringSelectDatabase& two_sections_database(){ + static const StringSelectDatabase database = story_checkpoint_database(two_sections()); + return database; +} + +// The dropdowns list the checkpoints as "id title", slugged by their index +// in the whole story, which is story_index() of a section's own index. +UnitTestResult test_checkpoint_dropdowns(){ + const StringSelectDatabase& database = two_sections_database(); + const std::vector expected{"00.01 Leave the house", "00.02 Walk to Sandgem Town", "01.01 Jubilife to Barry"}; + if (database.size() != expected.size()){ + return "Expected 3 entries, got " + std::to_string(database.size()); + } + for (size_t c = 0; c < expected.size(); c++){ + if (database[c].display_name != expected[c] || database[c].slug != std::to_string(c)){ + return "Unexpected entry " + std::to_string(c) + ": " + database[c].slug + " " + database[c].display_name; + } + } + if (database[story_index(true, 0, 2)].display_name != "01.01 Jubilife to Barry"){ + return "Expected the second section's first entry at story_index(true, 0, 2)."; + } + if (story_checkpoint_label(StoryCheckpoint{.id = "00.09", .title = "Pewter Gym: Camper Liam, then Brock", .start = std::nullopt, .steps = {}}) + != "00.09 Pewter Gym: Camper Liam, then Brock" + ){ + return "Unexpected label."; + } + StoryRunOptions options(database); + if (options.start_index() != 0 || options.end_index() != 2 || !options.check_validity().empty()){ + return "Expected the whole story by default."; + } + options.START_CHECKPOINT.set_by_index(2); + options.END_CHECKPOINT.set_by_index(1); + if (options.check_validity().empty()){ + return "Expected a start after the end to be refused."; + } + return true; +} + +// A segment's report in the shared AutoStory stats. +UnitTestResult test_story_stats(){ + SegmentReport report; + report.reloads = 2; + report.runs = { + CheckpointRun{.id = "00.03", .passed = true, .attempts = 1, .recoveries = 0}, + CheckpointRun{.id = "00.04", .passed = true, .attempts = 3, .recoveries = 0}, + CheckpointRun{.id = "00.05", .passed = false, .attempts = 1, .recoveries = 0}, + }; + AutoStoryStats stats; + record_story_stats(stats, report); + if (stats.m_segment != 1 || stats.m_checkpoint != 2 || stats.m_reset != 2){ + return "Expected 1 segment, 2 checkpoints and 2 resets."; + } + return true; +} + +// The program's option group: 3 attempts, no stop, Thorough, by default; +// Fast when chosen. +UnitTestResult test_run_options(){ + StoryRunOptions options(two_sections_database()); + const SegmentPolicy policy = options.policy(); + if (policy.attempts_per_checkpoint != 3 || policy.stop_at_first_failure || options.checks() != StoryChecks::THOROUGH){ + return "Expected 3 attempts, no stop at the first failure, and Thorough checks by default."; + } + options.CHECKS.set(StoryChecks::FAST); + if (options.checks() != StoryChecks::FAST){ + return "Expected Fast checks once chosen."; + } + // Every game language can be chosen, read or not. + if (options.language() != Language::English){ + return "Expected English by default."; + } + options.LANGUAGE.set(Language::Japanese); + if (options.language() != Language::Japanese || !options.check_validity().empty()){ + return "Expected Japanese to be chosen and valid, reader or not."; + } + return true; +} + +// Verify mode: off by default; 3 runs and 2 passes when on, for one +// checkpoint only, never needing more passes than runs. +UnitTestResult test_verify_options(){ + StoryRunOptions options(two_sections_database()); + if (options.VERIFY.policy()){ + return "Expected verify mode off by default."; + } + options.VERIFY.set_enabled(true); + if (options.check_validity().empty()){ + return "Expected verify mode refused over more than one checkpoint."; + } + options.END_CHECKPOINT.set_by_index(options.start_index()); + const std::optional policy = options.VERIFY.policy(); + if (!options.check_validity().empty() || !policy || policy->runs != 3 || policy->passes_needed != 2){ + return "Expected 3 runs and 2 passes on one checkpoint: " + options.check_validity(); + } + options.VERIFY.RUNS.set(2); + options.VERIFY.PASSES.set(3); + if (options.check_validity().empty()){ + return "Expected more passes than runs refused."; + } + return true; +} + +UnitTestResult test_lint(){ + StoryStep no_target = make(StoryStepKind::ROUTE, "walk"); + StoryStep again = make(StoryStepKind::TALK, "walk"); + StoryStep bad_legs = make(StoryStepKind::LEGS, "legs"); + bad_legs.legs = {{.direction = Direction::NORTH, .tiles = 0}}; + StoryStep no_variant = make(StoryStepKind::GAME, ""); + const StoryCheckpoint data{.id = "", .title = "", .start = std::nullopt, .steps = {no_target, again, bad_legs, no_variant}}; + const std::vector expected{ + "a checkpoint has no id", + " step 1 walk: ROUTE no target", + " step 2: a second step named walk", + " step 3 legs: LEGS a leg of no tiles", + " step 4: no name", + " step 4 : GAME no variant", + }; + const std::vector problems = lint_story_checkpoint(data); + if (problems != expected){ + return "Unexpected lint:" + joined(problems); + } + if (!lint_story_checkpoint(lab_checkpoint()).empty()){ + return "Expected the lab checkpoint to lint clean:" + joined(lint_story_checkpoint(lab_checkpoint())); + } + return true; +} + + +struct StoryStepInput{ + std::string name; + UnitTestResult (*test)(); +}; + +struct StoryStepExpectation{ + const char* description; +}; + +struct StoryStepTestCase{ + StoryStepInput input; + StoryStepExpectation expectation; +}; + +class Test_StorySteps : public UnitTest{ +public: + explicit Test_StorySteps(StoryStepTestCase scenario) + : UnitTest("Pokemon::StorySteps - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.input.test(); + } + +private: + StoryStepTestCase m_scenario; +}; + +const StoryStepTestCase STORY_STEP_CASES[] = { + { + .input = {.name = "steps run in table order", .test = test_events_in_table_order}, + .expectation = {.description = "executes story steps sequentially as defined in table"}, + }, + { + .input = {.name = "skip_if asks the executor", .test = test_skip_if}, + .expectation = {.description = "delegates skip condition check to executor"}, + }, + { + .input = {.name = "each step starts where the last left the player", .test = test_pose_propagation}, + .expectation = {.description = "propagates player pose across sequential step executions"}, + }, + { + .input = {.name = "a failure names its step", .test = test_failure_names_the_step}, + .expectation = {.description = "records failing step identifier on error"}, + }, + { + .input = {.name = "unsupported kinds and lost battles", .test = test_unsupported_and_lost_battles}, + .expectation = {.description = "flags unsupported step types and handles battle defeat"}, + }, + { + .input = {.name = "tables as a segment, with a reload", .test = test_segment_of_tables}, + .expectation = {.description = "converts step tables into segment with checkpoint reload support"}, + }, + { + .input = {.name = "lint", .test = test_lint}, + .expectation = {.description = "verifies lint validation rules on story checkpoints"}, + }, + { + .input = {.name = "the checks level reaches the steps", .test = test_checks_level}, + .expectation = {.description = "transfers checks granularity option to step execution"}, + }, + { + .input = {.name = "the run options' defaults", .test = test_run_options}, + .expectation = {.description = "validates initial default story run option values"}, + }, + { + .input = {.name = "the run options' verify mode", .test = test_verify_options}, + .expectation = {.description = "configures verification mode options and passes count"}, + }, + { + .input = {.name = "start and end checkpoint dropdowns", .test = test_checkpoint_dropdowns}, + .expectation = {.description = "populates start and end dropdown selections correctly"}, + }, + { + .input = {.name = "a segment's run in the AutoStory stats", .test = test_story_stats}, + .expectation = {.description = "updates story run statistics following segment completion"}, + }, + { + .input = {.name = "policy: attempts per checkpoint, then fail", .test = test_policy_attempts_then_fail}, + .expectation = {.description = "enforces max checkpoint attempt policy before terminal failure"}, + }, + { + .input = {.name = "policy: stop at the first failure", .test = test_policy_stop_at_first_failure}, + .expectation = {.description = "halts execution immediately when stop_at_first_failure is enabled"}, + }, + { + .input = {.name = "policy: recover in place before reloading", .test = test_policy_recovers_in_place}, + .expectation = {.description = "applies in-place recovery handler prior to reloading save"}, + }, + { + .input = {.name = "once per save: a retry skips what changed nothing", .test = test_once_per_save_retry}, + .expectation = {.description = "skips steps that changed nothing during once per save retry"}, + }, + { + .input = {.name = "once per save: verify runs prepare once", .test = test_once_per_save_verify}, + .expectation = {.description = "executes once per save prepare step only once during verification"}, + }, +}; + +} // namespace + + +void add_tests_StorySteps(UnitTestDatabase& database){ + for (const auto& scenario : STORY_STEP_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.cpp new file mode 100644 index 0000000000..6df0e9df31 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.cpp @@ -0,0 +1,72 @@ +/* Story Variant + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryVariant.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::vector variant_words(std::string_view text){ + std::vector words; + while (!text.empty()){ + const size_t space = text.find(' '); + const std::string_view word = text.substr(0, space); + if (!word.empty()){ + words.push_back(word); + } + if (space == std::string_view::npos){ + break; + } + text.remove_prefix(space + 1); + } + return words; +} + +std::optional variant_pair(std::string_view word){ + const size_t equals = word.find('='); + if (equals == std::string_view::npos || equals == 0){ + return std::nullopt; + } + return VariantPair{word.substr(0, equals), word.substr(equals + 1)}; +} + +std::string_view variant_name(std::string_view variant){ + const std::vector words = variant_words(variant); + if (words.empty() || variant_pair(words[0])){ + return {}; + } + return words[0]; +} + +std::optional variant_value(std::string_view variant, std::string_view key){ + for (std::string_view word : variant_words(variant)){ + const std::optional pair = variant_pair(word); + if (pair && pair->key == key){ + return pair->value; + } + } + return std::nullopt; +} + +std::optional variant_number(std::string_view text, size_t max_digits){ + if (text.empty() || text.size() > max_digits){ + return std::nullopt; + } + size_t value = 0; + for (char c : text){ + if (c < '0' || c > '9'){ + return std::nullopt; + } + value = value * 10 + size_t(c - '0'); + } + return value; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.h new file mode 100644 index 0000000000..f136fa147b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.h @@ -0,0 +1,51 @@ +/* Story Variant + * + * From: https://github.com/PokemonAutomation/ + * + * Reading a step's variant (StoryStep::variant): a name, then words split + * on spaces, some of them "key=value" pairs and small numbers. A table + * writes "mart PewterCity_Mart budget=2000 potion=5"; the name ("mart") + * picks the step's action (Pokemon_StoryActions.h) and the action reads + * the rest. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryVariant_H +#define PokemonAutomation_Pokemon_StoryVariant_H + +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// `text`'s words, split on spaces, empty words dropped. +std::vector variant_words(std::string_view text); + +// A word "key=value" as its two halves. +struct VariantPair{ + std::string_view key; + std::string_view value; +}; +// `word` split at its first '='; nothing without one or with an empty key. +std::optional variant_pair(std::string_view word); + +// The variant's name: its first word, unless that is a "key=value" pair. +// Empty for an empty variant or one of pairs only. +std::string_view variant_name(std::string_view variant); + +// The value of the first "key=value" word with `key`; nothing if none. +std::optional variant_value(std::string_view variant, std::string_view key); + +// `text` as a number of up to `max_digits` decimal digits; nothing if it +// isn't one. +std::optional variant_number(std::string_view text, size_t max_digits = 6); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp new file mode 100644 index 0000000000..5ce0fb7ab0 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp @@ -0,0 +1,161 @@ +/* Story Run Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryRunOptions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const EnumDropdownDatabase& StoryChecks_Database(){ + static const EnumDropdownDatabase database({ + {StoryChecks::THOROUGH, "thorough", "Thorough: confirm purchases, the Bag, status and position on screen"}, + {StoryChecks::FAST, "fast", "Fast: trust counts and timings"}, + }); + return database; +} + +const EnumDropdownDatabase& StoryLanguage_Database(){ + static const EnumDropdownDatabase database({ + {Language::English, "en", "English"}, + {Language::Japanese, "ja", "Japanese"}, + {Language::Spanish, "es", "Spanish"}, + {Language::French, "fr", "French"}, + {Language::German, "de", "German"}, + {Language::Italian, "it", "Italian"}, + {Language::Korean, "ko", "Korean"}, + {Language::ChineseSimplified, "zh-Hans", "Chinese (Simplified)"}, + {Language::ChineseTraditional, "zh-Hant", "Chinese (Traditional)"}, + }); + return database; +} + + +std::string story_checkpoint_label(const StoryCheckpoint& checkpoint){ + return checkpoint.title.empty() ? checkpoint.id : checkpoint.id + " " + checkpoint.title; +} + + +StoryVerifyOptions::StoryVerifyOptions() + : GroupOption( + "Verify Mode: run the start checkpoint (also the end) from its save several times, never saving at its end", + LockMode::LOCK_WHILE_RUNNING, + EnableMode::DEFAULT_DISABLED + ) + , RUNS( + "Runs:
Runs of the checkpoint, each from its save.", + LockMode::LOCK_WHILE_RUNNING, + 3, 1, 20 + ) + , PASSES( + "Passes needed:
Runs that must pass for the checkpoint to be verified.", + LockMode::LOCK_WHILE_RUNNING, + 2, 1, 20 + ) +{ + PA_ADD_OPTION(RUNS); + PA_ADD_OPTION(PASSES); +} + +std::optional StoryVerifyOptions::policy() const{ + if (!enabled()){ + return std::nullopt; + } + return VerifyPolicy{.runs = RUNS, .passes_needed = PASSES}; +} + +std::string StoryVerifyOptions::check_validity() const{ + if (enabled() && PASSES > RUNS){ + return "Verify mode can't need more passes than it has runs."; + } + return GroupOption::check_validity(); +} + + +StoryRunOptions::StoryRunOptions(const StringSelectDatabase& checkpoints) + : GroupOption("Story Run", LockMode::LOCK_WHILE_RUNNING) + , START_CHECKPOINT( + "Start checkpoint:
The program starts from this checkpoint's save.", + checkpoints, + LockMode::LOCK_WHILE_RUNNING, + 0 + ) + , END_CHECKPOINT( + "End checkpoint:
The program stops after this checkpoint.", + checkpoints, + LockMode::LOCK_WHILE_RUNNING, + checkpoints.size() == 0 ? 0 : checkpoints.size() - 1 + ) + , ATTEMPTS_PER_CHECKPOINT( + "Attempts per checkpoint:
A failed checkpoint reloads its save and runs again, up to this many times in all.", + LockMode::LOCK_WHILE_RUNNING, + 3, 1, 20 + ) + , STOP_AT_FIRST_FAILURE( + "Stop at the first failure:
Stop without reloading, leaving the game where it failed for a look.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , CHECKS( + "Checks:
Thorough reads the screen to confirm what each step did; Fast trusts counts and timings, for a run in a rush.", + StoryChecks_Database(), + LockMode::LOCK_WHILE_RUNNING, + StoryChecks::THOROUGH + ) + , LANGUAGE( + "Game language:
For the few reads that need text (item names in a shop or the Bag). " + "Story steps never match dialogue text; with no reader for this language they check positions, digits and the screen instead.", + StoryLanguage_Database(), + LockMode::LOCK_WHILE_RUNNING, + Language::English + ) +{ + PA_ADD_OPTION(START_CHECKPOINT); + PA_ADD_OPTION(END_CHECKPOINT); + PA_ADD_OPTION(ATTEMPTS_PER_CHECKPOINT); + PA_ADD_OPTION(STOP_AT_FIRST_FAILURE); + PA_ADD_OPTION(CHECKS); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(VERIFY); +} + +size_t StoryRunOptions::start_index() const{ + return START_CHECKPOINT.index(); +} + +size_t StoryRunOptions::end_index() const{ + return END_CHECKPOINT.index(); +} + +std::string StoryRunOptions::check_validity() const{ + if (start_index() > end_index()){ + return "The start checkpoint comes after the end checkpoint."; + } + if (VERIFY.enabled() && start_index() != end_index()){ + return "Verify mode runs one checkpoint: set the end checkpoint to the start checkpoint."; + } + return GroupOption::check_validity(); +} + +SegmentPolicy StoryRunOptions::policy() const{ + SegmentPolicy policy; + policy.attempts_per_checkpoint = ATTEMPTS_PER_CHECKPOINT; + policy.stop_at_first_failure = STOP_AT_FIRST_FAILURE; + return policy; +} + +StoryChecks StoryRunOptions::checks() const{ + return CHECKS; +} + +Language StoryRunOptions::language() const{ + return LANGUAGE; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h new file mode 100644 index 0000000000..c54482cc52 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h @@ -0,0 +1,119 @@ +/* Story Run Options + * + * From: https://github.com/PokemonAutomation/ + * + * The options every AutoStory program shows for where to start and end, how + * hard to try and how much to check: the same group in each game, read into the shared + * SegmentPolicy (Pokemon/AutoStory/Pokemon_StorySegments.h) and the + * executor's checks level (Pokemon_StorySteps.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRunOptions_H +#define PokemonAutomation_Pokemon_StoryRunOptions_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonTools/Options/StringSelectOption.h" +#include "Pokemon/AutoStory/Pokemon_AutoStorySelect.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "Pokemon/AutoStory/Pokemon_StorySteps.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A checkpoint's entry in the start and end dropdowns, as SV labels its +// segments: "00.09 Pewter Gym: Camper Liam, then Brock". +struct StoryCheckpointEntry{ + std::string label; + const std::string& name() const{ + return label; + } +}; +// Formats a checkpoint identifier and description into a dropdown label. +std::string story_checkpoint_label(const StoryCheckpoint& checkpoint); + +// The start/end dropdown database of a story's checkpoints, `rows` in +// order, slugged by their index in it (make_story_select_database()). A +// game whose story is in sections (BDSP's segments 00 and 01) passes them +// joined: a section's entry i is then story_index(true, i, first of the +// section). The program keeps it in a function-local static: the options +// hold a reference. +template +StringSelectDatabase story_checkpoint_database(const std::vector& rows); + +template +StringSelectDatabase story_checkpoint_database(const std::vector& rows){ + std::vector> entries; + for (const StoryCheckpoint& row : rows){ + entries.emplace_back(std::make_unique(StoryCheckpointEntry{.label = story_checkpoint_label(row)})); + } + return make_story_select_database(entries, 0, entries.size()); +} + + +// Verify mode, off by default (verify_checkpoint()): the start checkpoint +// RUNS times from its save, never saving at its end; verified when at +// least PASSES pass. For a battle that has lost twice or more, given its +// own checkpoint saved right before it. +class StoryVerifyOptions : public GroupOption{ +public: + StoryVerifyOptions(); + + // The runs and passes, unset when verify mode is off. + std::optional policy() const; + virtual std::string check_validity() const override; + +public: + SimpleIntegerOption RUNS; + SimpleIntegerOption PASSES; +}; + + +// Configuration options panel for selecting story checkpoints and execution mode. +class StoryRunOptions : public GroupOption{ +public: + // `checkpoints`: story_checkpoint_database() of the game's story, kept + // alive by the caller; the dropdowns start on its first and last. + explicit StoryRunOptions(const StringSelectDatabase& checkpoints); + + // The checkpoints to run, by index in the database, both inclusive. + size_t start_index() const; + size_t end_index() const; + // "The start checkpoint comes after the end checkpoint." if it does. + virtual std::string check_validity() const override; + + // The policy these options set. In-place recoveries are the game's to + // set, not the user's. + SegmentPolicy policy() const; + // The checks level for the game's story step executor (set_checks()). + StoryChecks checks() const; + // The game's language, for the executor (set_language()). + Language language() const; + +public: + StringSelectOption START_CHECKPOINT; + StringSelectOption END_CHECKPOINT; + SimpleIntegerOption ATTEMPTS_PER_CHECKPOINT; + BooleanCheckBoxOption STOP_AT_FIRST_FAILURE; + EnumDropdownOption CHECKS; + // Any language the game has, whether or not a reader supports it: + // steps without one use language-free checks, so none is refused. + EnumDropdownOption LANGUAGE; + // On, it runs one checkpoint: the start, which must also be the end. + StoryVerifyOptions VERIFY; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index ba4906e546..69e99c18a7 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1491,6 +1491,8 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Options/Pokemon_NameSelectWidget.h Source/Pokemon/Options/Pokemon_StatsHuntFilter.cpp Source/Pokemon/Options/Pokemon_StatsHuntFilter.h + Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp + Source/Pokemon/Options/Pokemon_StoryRunOptions.h Source/Pokemon/AutoStory/Pokemon_AutoStorySelect.h Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.cpp Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h @@ -1502,6 +1504,17 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp Source/Pokemon/AutoStory/Pokemon_StorySegments.h Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.cpp + Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.h + Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryVariant.cpp + Source/Pokemon/AutoStory/Pokemon_StoryVariant.h + Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp + Source/Pokemon/AutoStory/Pokemon_StoryStepJson.h + Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp + Source/Pokemon/AutoStory/Pokemon_StorySteps.h + Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp Source/Pokemon/AutoStory/Pokemon_TilePose.cpp Source/Pokemon/AutoStory/Pokemon_TilePose.h Source/Pokemon/Pokemon_AdvRng.cpp diff --git a/devtools/story-data-tests/CMakeLists.txt b/devtools/story-data-tests/CMakeLists.txt new file mode 100644 index 0000000000..978db4f6d0 --- /dev/null +++ b/devtools/story-data-tests/CMakeLists.txt @@ -0,0 +1,43 @@ +# Offline codec checks, no Qt application or controller initialization: +# cmake -S devtools/story-data-tests -B build/story-data-tests +# cmake --build build/story-data-tests -j4 +# ctest --test-dir build/story-data-tests --output-on-failure +cmake_minimum_required(VERSION 3.24) +project(StoryDataTests LANGUAGES CXX) +enable_testing() +get_filename_component(ROOT "../.." ABSOLUTE) +set(STORY "${ROOT}/SerialPrograms/Source/Pokemon/AutoStory") +add_executable(StoryDataTests + "${STORY}/Pokemon_StoryStepJson.cpp" + "${STORY}/Pokemon_StoryStepJson_Tests.cpp" + "${STORY}/Pokemon_TilePose.cpp" + "${ROOT}/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.cpp" + "${ROOT}/Common/Cpp/Exceptions.cpp" + "${ROOT}/Common/Cpp/Json/JsonValue.cpp" + "${ROOT}/Common/Cpp/Json/JsonObject.cpp" + "${ROOT}/Common/Cpp/Json/JsonArray.cpp" + "${ROOT}/Common/Cpp/Json/JsonTools.cpp" + "${ROOT}/Common/Cpp/Filesystem/FileIO.cpp" + "${ROOT}/Common/Cpp/Filesystem/FilePath.cpp" + "${ROOT}/Common/Cpp/Strings/Unicode.cpp") +# Reuse the Qt/controller-free support sources; each codec has its own test main. +get_target_property(STORY_DATA_SOURCES StoryDataTests SOURCES) +list(REMOVE_ITEM STORY_DATA_SOURCES "${STORY}/Pokemon_StoryStepJson_Tests.cpp") +add_executable(AuthoredCheckpointTests ${STORY_DATA_SOURCES} + "${STORY}/Pokemon_AuthoredCheckpointJson.cpp" + "${STORY}/Pokemon_AuthoredCheckpointJson_Tests.cpp") + +foreach(TEST_TARGET IN ITEMS StoryDataTests AuthoredCheckpointTests) +target_include_directories(${TEST_TARGET} PRIVATE "${ROOT}" "${ROOT}/SerialPrograms/Source") +target_compile_features(${TEST_TARGET} PRIVATE cxx_std_23) +target_compile_definitions(${TEST_TARGET} PRIVATE PA_STORY_DATA_STANDALONE) +if(MSVC) + target_compile_definitions(${TEST_TARGET} PRIVATE _CRT_SECURE_NO_WARNINGS) + target_compile_options(${TEST_TARGET} PRIVATE /W4 /WX) + set_property(SOURCE "${ROOT}/Common/Cpp/Filesystem/FileIO.cpp" APPEND PROPERTY COMPILE_OPTIONS /wd4505) +else() + target_compile_options(${TEST_TARGET} PRIVATE -Wall -Wextra -Werror) +endif() +endforeach() +add_test(NAME StoryData COMMAND StoryDataTests) +add_test(NAME AuthoredCheckpoint COMMAND AuthoredCheckpointTests) diff --git a/devtools/story-data-tests/README.md b/devtools/story-data-tests/README.md new file mode 100644 index 0000000000..310cea3ea3 --- /dev/null +++ b/devtools/story-data-tests/README.md @@ -0,0 +1,37 @@ +# Shared story-record codec tests + +Run without Qt, controllers, profiles or game saves: + +```sh +cmake -S devtools/story-data-tests -B build/story-data-tests +cmake --build build/story-data-tests -j4 +ctest --test-dir build/story-data-tests --output-on-failure +build/story-data-tests/StoryDataTests /path/to/PokemonSimulation/data/story/wire-conformance.json +``` + +For a multi-configuration generator, add `--config Debug` to the build, +`-C Debug` to CTest and use `build/story-data-tests/Debug/StoryDataTests.exe`. +The same native cases are registered in the application's unit-test runner. + +`Pokemon_StoryStepJson` encodes and reads the common `StoryCheckpoint`, +`StoryStep` and tile-based `Pose` records. It retains action order, alternative +tiles, certainty, absent facing and explicit false/zero values. Unknown fields, +action/position tags and invalid primitive types fail. Native default values +are omitted canonically; encoding does not establish semantic route validity. + +The portable workflow also reads the 31 synthetic conformance cases at +[PokemonSimulation revision 866613f](https://github.com/dayfine/PokemonSimulation/tree/866613fa03e5c4a5eb7e57c91b59fafb44fc7ee3/data/story). +Python reads the same input/expectation records. This fixture revision is a +contract-test dependency, not an approved map-resource revision. + +See the [shared checkpoint contract](https://github.com/dayfine/PokemonSimulation/blob/866613fa03e5c4a5eb7e57c91b59fafb44fc7ee3/docs/story/CHECKPOINT_CONTRACT.md) +for the field boundary and proposed common requirements, state, save/retry and +handoff envelope. Both games can use those policies; their menu/detector/action +bindings remain game specific. + +These are synthetic codec tests, not exports of either game's authored story +tables or captured controller replay. Evaluated FRLG/BDSP table exporters, +policy/state envelope binding and execution parity remain subsequent work. +No gameplay behavior changes here. + +The same CTest command also runs `AuthoredCheckpointTests`: shared authored-envelope parsing/writing and embedded-resource lookup for FRLG, BDSP, and opaque future game settings. Game adapters must validate their own execution object before running anything. The shared codec does not interpret FRLG menus, BDSP save-card policy, native bookkeeping, or controller evidence. From e9f0efe30a1f6a1e33f31cd08cfecae1e53829e4 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 18:19:31 -0800 Subject: [PATCH 31/64] AutoStory: screen state and interrupt tracking, split out of #122 Shared screen events and their timed log, the Switch HOME check in front of a game's observer, the transition tracker with per-game fade profiles, the scene judges and the interrupt classifier, taken as they are at nav/story-steps fd603cac2. None of it uses a story type. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../ComputerPrograms_UnitTestRunner.cpp | 3 + .../AutoStory/Pokemon_AutoStory_Tests.h | 6 + .../Pokemon/AutoStory/Pokemon_Interrupts.cpp | 278 +++++++++++ .../Pokemon/AutoStory/Pokemon_Interrupts.h | 157 +++++++ .../AutoStory/Pokemon_Interrupts_Tests.cpp | 435 ++++++++++++++++++ .../Pokemon/AutoStory/Pokemon_SceneJudges.cpp | 93 ++++ .../Pokemon/AutoStory/Pokemon_SceneJudges.h | 104 +++++ .../AutoStory/Pokemon_ScreenEvents.cpp | 203 ++++++++ .../Pokemon/AutoStory/Pokemon_ScreenEvents.h | 262 +++++++++++ .../AutoStory/Pokemon_ScreenEvents_Tests.cpp | 280 +++++++++++ .../Pokemon/AutoStory/Pokemon_Transitions.cpp | 272 +++++++++++ .../Pokemon/AutoStory/Pokemon_Transitions.h | 197 ++++++++ .../AutoStory/Pokemon_Transitions_Tests.cpp | 378 +++++++++++++++ SerialPrograms/cmake/SourceFiles.cmake | 11 + 14 files changed, 2679 insertions(+) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index df98fc4df2..6e89edfd13 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -78,6 +78,9 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_MapData(ret); Pokemon::add_tests_RuntimeMap(ret); Pokemon::add_tests_RouteLog(ret); + Pokemon::add_tests_ScreenEvents(ret); + Pokemon::add_tests_Interrupts(ret); + Pokemon::add_tests_Transitions(ret); Pokemon::add_tests_StoryEvents(ret); Pokemon::add_tests_StorySegments(ret); Pokemon::add_tests_StorySteps(ret); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 5d0bbe1172..6f07d254d9 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -15,6 +15,12 @@ namespace PokemonAutomation{ namespace Pokemon{ +// Registers unit tests for the shared screen events and the judgements over them. +void add_tests_ScreenEvents(UnitTestDatabase& database); +// The timed screen-event log, the warp judge and the interrupt classifier. +void add_tests_Interrupts(UnitTestDatabase& database); +// The transition tracker and the games' fade profiles. +void add_tests_Transitions(UnitTestDatabase& database); // Registers unit tests for story event sequencing and execution. void add_tests_StoryEvents(UnitTestDatabase& database); // Registers unit tests for story segment running, verification, and branching. diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp new file mode 100644 index 0000000000..e93ce9f5c9 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp @@ -0,0 +1,278 @@ +/* Interrupts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon_Interrupts.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const char* warp_judgement_name(WarpJudgement judgement){ + switch (judgement){ + case WarpJudgement::NO_FADE: return "no fade"; + case WarpJudgement::FADE_SHOWING: return "fade still showing"; + case WarpJudgement::TOO_SHORT: return "fade too short"; + case WarpJudgement::SAME_SCENE: return "same scene after the fade"; + case WarpJudgement::WARPED: return "warped"; + case WarpJudgement::FLASH: return "an encounter's flash"; + case WarpJudgement::WHITE_UNSURE: return "a white, flash or fade"; + } + return "?"; +} + +const char* interrupt_kind_name(InterruptKind kind){ + switch (kind){ + case InterruptKind::NONE: return "none"; + case InterruptKind::WILD_ENCOUNTER: return "wild encounter"; + case InterruptKind::TRAINER_SIGHT: return "trainer sight"; + case InterruptKind::DIALOG: return "dialog"; + case InterruptKind::WARP: return "warp"; + case InterruptKind::UNSETTLED: return "unsettled"; + } + return "?"; +} + + +namespace{ + +using Changes = std::vector; + +Changes changes_in(const ScreenEventLog& log, InterruptWindow window){ + Changes out; + for (const ScreenEventChange& change : log.changes()){ + if (window.start <= change.time && change.time <= window.end){ + out.push_back(change); + } + } + return out; +} + +bool rose(const ScreenEventChange& change, ScreenEvent event){ + return change.event == event && change.edge == ScreenEventEdge::ROSE; +} +bool fade_rose(const ScreenEventChange& change){ + return rose(change, ScreenEvent::FADE_BLACK) || rose(change, ScreenEvent::FADE_WHITE); +} + +// The first rise of `event`, if any. +std::optional first_rise(const Changes& changes, ScreenEvent event){ + for (const ScreenEventChange& change : changes){ + if (rose(change, event)){ + return change; + } + } + return std::nullopt; +} + +// The last fade that went down, and when it came back up. +std::optional last_fade(const Changes& changes){ + std::optional out; + for (const ScreenEventChange& change : changes){ + if (fade_rose(change)){ + out = FadeSpan{fade_in({change.event}), change.time, std::nullopt}; + }else if (out && !out->up && change.edge == ScreenEventEdge::FELL && fade_events(out->fade).has(change.event)){ + out->up = change.time; + } + } + return out; +} + +ScreenEvent fade_event(WarpFade fade){ + return fade == WarpFade::WHITE ? ScreenEvent::FADE_WHITE : ScreenEvent::FADE_BLACK; +} +void add_fade_evidence(Changes& evidence, const FadeSpan& fade){ + evidence.push_back({fade.down, fade_event(fade.fade), ScreenEventEdge::ROSE}); + if (fade.up){ + evidence.push_back({*fade.up, fade_event(fade.fade), ScreenEventEdge::FELL}); + } +} + + +// A battle, and whose. The battle's fade is the last one that went down +// no more than battle_after_fade before it; a box that rose before that +// fade (or before the battle, with no fade) is a trainer's lines. A box +// after the fade is the battle's own opening text. +std::optional battle_verdict(const Changes& changes, const InterruptKnobs& knobs){ + const std::optional battle = first_rise(changes, ScreenEvent::BATTLE_STARTED); + if (!battle){ + return std::nullopt; + } + std::optional fade; + for (const ScreenEventChange& change : changes){ + if (change.time > battle->time){ + break; + } + if (fade_rose(change) && battle->time - change.time <= knobs.battle_after_fade){ + fade = change; + } + } + const WallClock cut = fade ? fade->time : battle->time; + std::optional lines; + for (const ScreenEventChange& change : changes){ + if (change.time >= cut){ + break; + } + if (rose(change, ScreenEvent::DIALOG_BOX) && cut - change.time <= knobs.sight_lines_lead){ + lines = change; + break; + } + } + InterruptVerdict out{lines ? InterruptKind::TRAINER_SIGHT : InterruptKind::WILD_ENCOUNTER, {}, false}; + for (const std::optional& change : {lines, fade, battle}){ + if (change){ + out.evidence.push_back(*change); + } + } + return out; +} + +// A warp: a banner, or a fade back up with no battle after it for +// battle_after_fade. A fade still showing, or back up too recently, may +// yet be an encounter's flash. +std::optional warp_verdict( + const ScreenEventLog& log, InterruptWindow window, const Changes& changes, const InterruptKnobs& knobs +){ + const WarpVerdict warp = judge_warp(log, window, knobs, SceneChange::UNKNOWN); + const std::optional banner = first_rise(changes, ScreenEvent::LOCATION_BANNER); + InterruptVerdict out{InterruptKind::WARP, {}, false}; + if (warp.fade && warp.judgement != WarpJudgement::TOO_SHORT){ + add_fade_evidence(out.evidence, *warp.fade); + } + if (banner){ + out.evidence.push_back(*banner); + std::stable_sort(out.evidence.begin(), out.evidence.end(), [](const auto& a, const auto& b){ + return a.time < b.time; + }); + return out; + } + switch (warp.judgement){ + case WarpJudgement::FADE_SHOWING: + out.kind = InterruptKind::UNSETTLED; + return out; + case WarpJudgement::WARPED:{ + const WallClock seen_until = std::min(window.end, log.last_frame().value_or(window.end)); + if (seen_until - *warp.fade->up < knobs.battle_after_fade){ + out.kind = InterruptKind::UNSETTLED; + } + return out; + } + case WarpJudgement::NO_FADE: + case WarpJudgement::TOO_SHORT: + case WarpJudgement::SAME_SCENE: + case WarpJudgement::FLASH: + case WarpJudgement::WHITE_UNSURE: + break; + } + return std::nullopt; +} + +std::optional dialog_verdict(const Changes& changes){ + const std::optional box = first_rise(changes, ScreenEvent::DIALOG_BOX); + if (!box){ + return std::nullopt; + } + return InterruptVerdict{InterruptKind::DIALOG, {*box}, false}; +} + +} // namespace + + +WarpVerdict judge_warp( + const ScreenEventLog& log, InterruptWindow window, + const InterruptKnobs& knobs, SceneChange change +){ + WarpVerdict out{WarpJudgement::NO_FADE, last_fade(changes_in(log, window))}; + if (!out.fade){ + return out; + } + if (!out.fade->up){ + out.judgement = WarpJudgement::FADE_SHOWING; + }else if (*out.fade->up - out.fade->down < knobs.min_fade_hold){ + out.judgement = WarpJudgement::TOO_SHORT; + }else if (change == SceneChange::SAME){ + out.judgement = WarpJudgement::SAME_SCENE; + }else{ + out.judgement = WarpJudgement::WARPED; + } + return out; +} + +WarpVerdict judge_warp(const Transition& transition, const InterruptKnobs& knobs){ + const WarpFade fade = transition.kind == TransitionKind::FADE_BLACK ? WarpFade::BLACK : WarpFade::WHITE; + WarpVerdict out{WarpJudgement::WARPED, FadeSpan{fade, transition.start, transition.end}}; + if (!transition.end){ + out.judgement = WarpJudgement::FADE_SHOWING; + }else if (transition.kind == TransitionKind::FLASH){ + out.judgement = WarpJudgement::FLASH; + }else if (transition.change == SceneChange::SAME){ + out.judgement = WarpJudgement::SAME_SCENE; + }else if (transition.kind == TransitionKind::WHITE_UNSURE){ + out.judgement = WarpJudgement::WHITE_UNSURE; + }else if (transition.peak && transition.change != SceneChange::DIFFERENT && transition.hold() < knobs.min_fade_hold){ + out.judgement = WarpJudgement::TOO_SHORT; + } + return out; +} + + +std::string describe(const InterruptVerdict& verdict, WallClock origin){ + std::string out = interrupt_kind_name(verdict.kind); + const char* separator = ": "; + for (const ScreenEventChange& change : verdict.evidence){ + out += std::format( + "{}{:+} ms {} {}", + separator, + std::chrono::duration_cast(change.time - origin).count(), + screen_event_name(change.event), + change.edge == ScreenEventEdge::ROSE ? "rose" : "fell" + ); + separator = ", "; + } + if (verdict.log_truncated){ + out += " (log truncated)"; + } + return out; +} + + +InterruptVerdict classify_interrupt( + const ScreenEventLog& log, InterruptWindow window, const InterruptKnobs& knobs +){ + const Changes changes = changes_in(log, window); + std::optional verdict = battle_verdict(changes, knobs); + if (!verdict){ + verdict = warp_verdict(log, window, changes, knobs); + } + if (!verdict){ + verdict = dialog_verdict(changes); + } + InterruptVerdict out = verdict.value_or(InterruptVerdict{}); + out.log_truncated = log.dropped() > 0 && + (log.changes().empty() || window.start <= log.changes().front().time); + return out; +} + + +std::optional interrupt_step_time(const InterruptVerdict& verdict, const std::vector& lags){ + for (const ScreenEventChange& change : verdict.evidence){ + if (change.edge != ScreenEventEdge::ROSE){ + continue; + } + for (const EventLag& lag : lags){ + if (lag.event == change.event){ + return change.time - lag.lag; + } + } + } + return std::nullopt; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.h new file mode 100644 index 0000000000..52d23c811c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.h @@ -0,0 +1,157 @@ +/* Interrupts + * + * From: https://github.com/PokemonAutomation/ + * + * What stopped the player, judged from the order of screen events + * (ScreenEventLog), the same way for every game: a wild encounter, a + * trainer's sight, a dialog, a warp. One frame cannot tell them apart; the + * order can. A white flash then a battle is an encounter, a white fade with + * no battle after it a cave exit (BDSP's walk fled one as a battle, #268); + * a box then a flash then a battle is a trainer's lines; a flash then a box + * then a battle is a wild battle's opening text. + * + * Games differ in timing only, so they pass their numbers (InterruptKnobs) + * rather than their own classifier. + * + */ + +#ifndef PokemonAutomation_Pokemon_Interrupts_H +#define PokemonAutomation_Pokemon_Interrupts_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Pokemon_ScreenEvents.h" +#include "Pokemon_Transitions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A game's timing, as data. +struct InterruptKnobs{ + // A fade must hold this long to be a warp's. One uniform frame is enough + // by default: a 50 ms fade can show on one frame only. + Milliseconds min_fade_hold = Milliseconds(0); + // A battle that shows this soon after a fade ends is that fade's + // encounter, and a fade is no warp before this has passed with no + // battle. BDSP's encounter flash shows its battle within 8 s + // (WHITE_FLASH_BATTLE_WAIT in its walk). + Milliseconds battle_after_fade = Milliseconds(8000); + // A dialog box that rose this long or less before a battle's fade is a + // trainer's lines. A trainer's lines can pause more than 4 s before the + // battle (BDSP r210d), and a trainer may say several boxes. + Milliseconds sight_lines_lead = Milliseconds(20000); +}; + +// The span of the log to judge: changes at `start` or later, and no later +// than `end`. +struct InterruptWindow{ + WallClock start = {}; + WallClock end = {}; +}; + + +// How a fade looked, for the warp judge. +struct FadeSpan{ + WarpFade fade = WarpFade::NONE; + WallClock down = {}; + // When the screen came back; none while it still shows the fade. + std::optional up = {}; +}; + +// What the warp judge made of a fade. +enum class WarpJudgement{ + NO_FADE, // No fade went down in the window. + FADE_SHOWING, // It went down and has not come back up. + TOO_SHORT, // It came back up before min_fade_hold. + SAME_SCENE, // It came back up on the scene it left. + WARPED, // Down, held, back up; not on the same scene. + FLASH, // An encounter's flash (a tracked transition only). + WHITE_UNSURE, // A white that may be a flash or a cave exit (a + // tracked transition only): wait for a battle. +}; +// "fade too short", for the log. +const char* warp_judgement_name(WarpJudgement judgement); + +// The warp judge's verdict and the fade it judged. +struct WarpVerdict{ + WarpJudgement judgement = WarpJudgement::NO_FADE; + // The last fade that went down in the window, if any. + std::optional fade = {}; +}; + +// A warp is a fade going down, holding uniform, and coming back up on +// another scene. The last fade that went down in `window` is judged; a +// LOCATION_BANNER does not count here (WarpSeen does). `change` is what +// the caller saw of the scene before and after: UNKNOWN does not rule the +// warp out. This judges the fade only: a battle after it is +// classify_interrupt()'s question. +WarpVerdict judge_warp( + const ScreenEventLog& log, InterruptWindow window, + const InterruptKnobs& knobs, SceneChange change +); +// The same judge over a TransitionTracker's transition, which has its own +// scene comparison. A transition whose hold went unseen onto another scene +// is a warp whatever min_fade_hold says: the scene change is the evidence. +WarpVerdict judge_warp(const Transition& transition, const InterruptKnobs& knobs); + + +// What stopped the player. +enum class InterruptKind{ + NONE, + WILD_ENCOUNTER, // A battle with no trainer's lines before it. + TRAINER_SIGHT, // A dialog box, then a battle. + DIALOG, // A dialog box and no battle. + WARP, // A fade back up with no battle after it, or a banner. + UNSETTLED, // A fade, too recent to know if a battle follows. +}; +// "trainer sight", for the log. +const char* interrupt_kind_name(InterruptKind kind); + +// What stopped the player, and the evidence for it. +struct InterruptVerdict{ + InterruptKind kind = InterruptKind::NONE; + // The changes it was judged on, in order. + std::vector evidence = {}; + // The log dropped changes the window reaches back to: the verdict may + // miss what came first. + bool log_truncated = false; +}; +// "wild encounter: +0 ms white fade rose, +3400 ms battle started rose", +// times from `origin`. +std::string describe(const InterruptVerdict& verdict, WallClock origin); + +// What interrupted the player in `window` of `log`. Order of precedence: a +// battle, then a warp, then a dialog. Only events that rose in the window +// count: a box already up when it starts is not this interrupt's. +InterruptVerdict classify_interrupt( + const ScreenEventLog& log, InterruptWindow window, const InterruptKnobs& knobs +); + + +// How long after the step that set an interrupt off one of its events +// shows, as a game measured it on its console. +struct EventLag{ + ScreenEvent event = ScreenEvent::BATTLE_STARTED; + Milliseconds lag = Milliseconds(0); +}; + +// When the step that set `verdict`'s interrupt off was taken: the first +// rise in its evidence that `lags` times, less that lag. The first, as it +// shows nearest the step. Nothing if `lags` times none of them, as for a +// game that hasn't measured its events, or for no verdict. Lags are one +// kind of interrupt's (a wild battle's box, not a trainer's): the caller +// checks the verdict's kind first. +// +// This places an interrupt seen only after a walk's hold has ended, by +// what the log saw of it during the hold, instead of by when the watcher +// that stopped for it fired. +std::optional interrupt_step_time(const InterruptVerdict& verdict, const std::vector& lags); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp new file mode 100644 index 0000000000..aecc5cbbd8 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp @@ -0,0 +1,435 @@ +/* Interrupts Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The timed screen-event log, the warp judge and the interrupt classifier, + * driven by synthetic scenes: a frame's events at a time. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "Pokemon_AutoStory_Tests.h" +#include "Pokemon_Interrupts.h" +#include "Pokemon_ScreenEvents.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +using namespace std::chrono_literals; + +const WallClock T0 = WallClock() + std::chrono::hours(1); + +UnitTestResult expect_equal(const std::string& what, const std::string& got, const std::string& expected){ + if (got == expected){ + return true; + } + return std::format("{}: expected \"{}\", got \"{}\"", what, expected, got); +} + +// One frame of a synthetic scene: its events, at `ms` after T0. +struct Frame{ + int ms; + ScreenEvents events; +}; + +// A log of `frames`, then the same as the last one every 500 ms until +// `until_ms` (a walk's screen, looked at while nothing changes). +ScreenEventLog log_of(const std::vector& frames, int until_ms, size_t capacity = SCREEN_EVENT_LOG_CAPACITY){ + ScreenEventLog log(capacity); + for (const Frame& frame : frames){ + log.record(frame.events, T0 + Milliseconds(frame.ms)); + } + const ScreenEvents last = frames.empty() ? ScreenEvents() : frames.back().events; + for (int ms = frames.empty() ? 0 : frames.back().ms + 500; ms <= until_ms; ms += 500){ + log.record(last, T0 + Milliseconds(ms)); + } + return log; +} + +const ScreenEvents WALK{ScreenEvent::PLAYER_CAN_MOVE}; +const ScreenEvents BLACK{ScreenEvent::FADE_BLACK}; +const ScreenEvents WHITE{ScreenEvent::FADE_WHITE}; +const ScreenEvents BOX{ScreenEvent::DIALOG_BOX, ScreenEvent::PLAYER_CAN_MOVE}; +const ScreenEvents BATTLE{ScreenEvent::BATTLE_STARTED}; +const ScreenEvents BATTLE_TEXT{ScreenEvent::DIALOG_BOX}; +const ScreenEvents BANNER{ScreenEvent::LOCATION_BANNER, ScreenEvent::PLAYER_CAN_MOVE}; + +InterruptWindow whole(int until_ms){ + return {T0, T0 + Milliseconds(until_ms)}; +} + + +UnitTestResult test_log_records_rises_and_falls(){ + const ScreenEventLog log = log_of({ + {0, WALK}, + {100, WALK}, + {200, BLACK}, + {450, ScreenEvents{ScreenEvent::LOCATION_BANNER, ScreenEvent::PLAYER_CAN_MOVE}}, + }, 450); + if (log.showing() != BANNER || log.last_frame() != T0 + 450ms || log.dropped() != 0){ + return "the log's last frame is not the banner frame at +450 ms"; + } + return expect_equal("describe(log)", describe(log, T0), + "+0 ms player can move rose\n" + "+200 ms black fade rose\n" + "+200 ms player can move fell\n" + "+450 ms black fade fell\n" + "+450 ms location banner rose\n" + "+450 ms player can move rose\n" + ); +} + +UnitTestResult test_log_overflow_and_clear(){ + ScreenEventLog log = log_of({{0, WALK}, {100, BOX}, {200, WALK}, {300, BOX}, {400, WALK}}, 400, 3); + if (log.changes().size() != 3 || log.dropped() != 2){ + return std::format("expected 3 kept and 2 dropped, got {} and {}", log.changes().size(), log.dropped()); + } + if (log.changes().front() != ScreenEventChange{T0 + 200ms, ScreenEvent::DIALOG_BOX, ScreenEventEdge::FELL}){ + return "the oldest change kept is not the box falling at +200 ms"; + } + const InterruptVerdict early = classify_interrupt(log, whole(400), {}); + const InterruptVerdict late = classify_interrupt(log, {T0 + 250ms, T0 + 400ms}, {}); + if (!early.log_truncated || late.log_truncated){ + return "only a window reaching back past the kept changes is truncated"; + } + UnitTestResult result = expect_equal("truncated verdict", describe(early, T0), "dialog: +300 ms dialog box rose (log truncated)"); + if (result.result != UnitTestResult::PASSED){ + return result; + } + log.clear(); + if (!log.changes().empty() || log.dropped() != 0 || log.last_frame() || log.showing() != ScreenEvents()){ + return "clear() did not empty the log"; + } + return true; +} + +UnitTestResult test_empty_log(){ + const ScreenEventLog log; + const InterruptVerdict verdict = classify_interrupt(log, whole(1000), {}); + if (judge_warp(log, whole(1000), {}, SceneChange::DIFFERENT).judgement != WarpJudgement::NO_FADE){ + return "an empty log has a fade"; + } + return expect_equal("empty log", describe(verdict, T0), "none"); +} + + +UnitTestResult test_judge_warp(){ + struct Row{ + const char* name; + std::vector frames; + SceneChange change; + WarpJudgement expected; + }; + const std::vector rows = { + {"down, held, back up on another scene", {{0, WALK}, {1000, BLACK}, {1400, WALK}}, SceneChange::DIFFERENT, WarpJudgement::WARPED}, + {"no frame compare does not rule it out", {{0, WALK}, {1000, BLACK}, {1400, WALK}}, SceneChange::UNKNOWN, WarpJudgement::WARPED}, + {"back on the same scene", {{0, WALK}, {1000, BLACK}, {1400, WALK}}, SceneChange::SAME, WarpJudgement::SAME_SCENE}, + {"a flicker", {{0, WALK}, {1000, BLACK}, {1050, WALK}}, SceneChange::DIFFERENT, WarpJudgement::TOO_SHORT}, + {"still dark", {{0, WALK}, {1000, BLACK}}, SceneChange::UNKNOWN, WarpJudgement::FADE_SHOWING}, + {"no fade", {{0, WALK}, {1000, BOX}}, SceneChange::DIFFERENT, WarpJudgement::NO_FADE}, + }; + const InterruptKnobs knobs{.min_fade_hold = 200ms}; + for (const Row& row : rows){ + const ScreenEventLog log = log_of(row.frames, 3000); + const WarpJudgement got = judge_warp(log, whole(3000), knobs, row.change).judgement; + if (got != row.expected){ + return std::format("{}: expected {}, got {}", row.name, warp_judgement_name(row.expected), warp_judgement_name(got)); + } + } + return true; +} + + +// Replays a fixed list of event sets, one per frame. +class ScriptedObserver : public ScreenEventObserver{ +public: + explicit ScriptedObserver(std::vector frames) + : m_frames(std::move(frames)) + {} + virtual ScreenEvents observe(const VideoSnapshot&, WallClock) override{ + return m_next < m_frames.size() ? m_frames[m_next++] : ScreenEvents(); + } + virtual void make_overlays(VideoOverlaySet&) const override{} + +private: + std::vector m_frames; + size_t m_next = 0; +}; + +UnitTestResult test_watcher_log(){ + ScriptedObserver observer({WALK, WHITE, WALK}); + ScreenEventWatcher watcher(observer); + for (int c = 0; c < 3; c++){ + watcher.process_frame(VideoSnapshot(ImageRGB32(4, 4), T0 + Milliseconds(100 * c))); + } + UnitTestResult result = expect_equal("watcher log", describe(watcher.log(), T0), + "+0 ms player can move rose\n" + "+100 ms white fade rose\n" + "+100 ms player can move fell\n" + "+200 ms white fade fell\n" + "+200 ms player can move rose\n" + ); + if (result.result != UnitTestResult::PASSED){ + return result; + } + watcher.reset(); + return expect_equal("watcher log after reset()", describe(watcher.log(), T0), "no changes"); +} + + +struct InterruptsInput{ + std::string name; + std::function body; +}; + +struct InterruptsExpectation{ +}; + +struct InterruptsCase{ + InterruptsInput input; + InterruptsExpectation expectation; +}; + +class Test_Interrupts : public UnitTest{ +public: + explicit Test_Interrupts(InterruptsCase test_case) + : UnitTest("Pokemon::Interrupts - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_case.input.body(); + } + +private: + InterruptsCase m_case; +}; + + +// A synthetic scene, and the window of it to judge. +struct ClassifyInput{ + std::string name; + std::vector frames; + int until_ms = 0; + InterruptKnobs knobs = {}; + int window_from_ms = 0; +}; + +struct ClassifyExpectation{ + // describe(verdict, T0). + std::string verdict; +}; + +struct ClassifyCase{ + ClassifyInput input; + ClassifyExpectation expectation; +}; + +class Test_InterruptClassify : public UnitTest{ +public: + explicit Test_InterruptClassify(ClassifyCase test_case) + : UnitTest("Pokemon::Interrupts - classify: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const ClassifyInput& input = m_case.input; + const ScreenEventLog log = log_of(input.frames, input.until_ms); + const InterruptWindow window{T0 + Milliseconds(input.window_from_ms), T0 + Milliseconds(input.until_ms)}; + const InterruptVerdict verdict = classify_interrupt(log, window, input.knobs); + return expect_equal("verdict", describe(verdict, T0), m_case.expectation.verdict); + } + +private: + ClassifyCase m_case; +}; + + +// A synthetic scene, classified over all of it, and the lags to time it. +struct StepTimeInput{ + std::string name; + std::vector frames; + int until_ms = 0; + std::vector lags; +}; + +struct StepTimeExpectation{ + // "+700 ms" from T0, or "none". + std::string step; +}; + +struct StepTimeCase{ + StepTimeInput input; + StepTimeExpectation expectation; +}; + +class Test_InterruptStepTime : public UnitTest{ +public: + explicit Test_InterruptStepTime(StepTimeCase test_case) + : UnitTest("Pokemon::Interrupts - step time: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const StepTimeInput& input = m_case.input; + const InterruptVerdict verdict = classify_interrupt(log_of(input.frames, input.until_ms), whole(input.until_ms), {}); + const std::optional step = interrupt_step_time(verdict, input.lags); + const std::string got = step + ? std::format("{:+} ms", std::chrono::duration_cast(*step - T0).count()) + : "none"; + return expect_equal("step time of " + describe(verdict, T0), got, m_case.expectation.step); + } + +private: + StepTimeCase m_case; +}; + +} // namespace + + +const InterruptsCase INTERRUPTS_CASES[] = { + { + .input = {"the log keeps rises and falls in order, timed", test_log_records_rises_and_falls}, + .expectation = {}, + }, + { + .input = {"a full log drops its oldest changes and says so", test_log_overflow_and_clear}, + .expectation = {}, + }, + { + .input = {"an empty log is no interrupt and no fade", test_empty_log}, + .expectation = {}, + }, + { + .input = {"a warp is down, held, back up, not the same scene", test_judge_warp}, + .expectation = {}, + }, + { + .input = {"a watcher keeps a timed log", test_watcher_log}, + .expectation = {}, + }, +}; + +const ClassifyCase CLASSIFY_CASES[] = { + { + .input = {"an encounter's white flash, then the battle", + {{0, WALK}, {1000, WHITE}, {1300, ScreenEvents()}, {3000, BATTLE}}, 3000}, + .expectation = {"wild encounter: +1000 ms white fade rose, +3000 ms battle started rose"}, + }, + { + .input = {"a wild battle's opening text comes after its flash", + {{0, WALK}, {1000, WHITE}, {1300, BATTLE_TEXT}, {2500, BATTLE}}, 2500}, + .expectation = {"wild encounter: +1000 ms white fade rose, +2500 ms battle started rose"}, + }, + { + .input = {"a trainer's lines, a pause, the battle's fade", + {{0, WALK}, {1000, BOX}, {2000, WALK}, {6000, BLACK}, {6400, BATTLE}}, 6400}, + .expectation = {"trainer sight: +1000 ms dialog box rose, +6000 ms black fade rose, +6400 ms battle started rose"}, + }, + { + .input = {"a trainer's lines, then the battle with no fade seen", + {{0, WALK}, {1000, BOX}, {2000, BATTLE}}, 2000}, + .expectation = {"trainer sight: +1000 ms dialog box rose, +2000 ms battle started rose"}, + }, + { + .input = {"a box and no battle", {{0, WALK}, {1000, BOX}}, 20000}, + .expectation = {"dialog: +1000 ms dialog box rose"}, + }, + { + .input = {"a cave exit's white fade, and no battle for 8 s", + {{0, WALK}, {1000, WHITE}, {1600, WALK}}, 12000}, + .expectation = {"warp: +1000 ms white fade rose, +1600 ms white fade fell"}, + }, + { + .input = {"a white fade too recent to rule out a battle", + {{0, WALK}, {1000, WHITE}, {1600, WALK}}, 4000}, + .expectation = {"unsettled: +1000 ms white fade rose, +1600 ms white fade fell"}, + }, + { + .input = {"a fade still showing", {{0, WALK}, {1000, BLACK}}, 3000}, + .expectation = {"unsettled: +1000 ms black fade rose"}, + }, + { + .input = {"a banner after the white settles it at once", + {{0, WALK}, {1000, WHITE}, {1600, WALK}, {2000, BANNER}}, 2500}, + .expectation = {"warp: +1000 ms white fade rose, +1600 ms white fade fell, +2000 ms location banner rose"}, + }, + { + .input = {"a box during a fade is the scene cut's", + {{0, WALK}, {1000, BLACK}, {1300, ScreenEvents{ScreenEvent::FADE_BLACK, ScreenEvent::DIALOG_BOX}}, + {1800, BOX}, {3000, WALK}}, 12000}, + .expectation = {"warp: +1000 ms black fade rose, +1800 ms black fade fell"}, + }, + { + .input = {"a door's fade long before a battle is not the battle's", + {{0, WALK}, {500, BLACK}, {900, WALK}, {20000, BATTLE}}, 20000}, + .expectation = {"wild encounter: +20000 ms battle started rose"}, + }, + { + .input = {"a box up before the window is not this interrupt's", + {{0, BOX}, {1000, WALK}, {3000, WHITE}, {3300, WALK}, {5000, BATTLE}}, 5000, {}, 500}, + .expectation = {"wild encounter: +3000 ms white fade rose, +5000 ms battle started rose"}, + }, + { + .input = {"a one-frame flicker is no fade with a hold to meet", + {{0, WALK}, {1000, BLACK}, {1050, WALK}}, 12000, {.min_fade_hold = 200ms}}, + .expectation = {"none"}, + }, + { + .input = {"a one-frame fade is a warp by default", + {{0, WALK}, {1000, BLACK}, {1050, WALK}}, 12000}, + .expectation = {"warp: +1000 ms black fade rose, +1050 ms black fade fell"}, + }, + { + .input = {"a walk with nothing in it", {{0, WALK}}, 5000}, + .expectation = {"none"}, + }, +}; + +const StepTimeCase STEP_TIME_CASES[] = { + { + .input = {"a wild battle's box, its fade untimed", + {{0, WALK}, {1500, BLACK}, {2000, ScreenEvents()}, {4400, BATTLE}}, 6000, + {{ScreenEvent::BATTLE_STARTED, 3700ms}}}, + .expectation = {"+700 ms"}, + }, + { + .input = {"the first timed rise wins", + {{0, WALK}, {1500, BLACK}, {2000, ScreenEvents()}, {4400, BATTLE}}, 6000, + {{ScreenEvent::BATTLE_STARTED, 3700ms}, {ScreenEvent::FADE_BLACK, 1000ms}}}, + .expectation = {"+500 ms"}, + }, + { + .input = {"no lags, no time", + {{0, WALK}, {4400, BATTLE}}, 6000, {}}, + .expectation = {"none"}, + }, + { + .input = {"no interrupt, no time", + {{0, WALK}}, 6000, {{ScreenEvent::BATTLE_STARTED, 3700ms}}}, + .expectation = {"none"}, + }, +}; + +void add_tests_Interrupts(UnitTestDatabase& database){ + for (const auto& item : INTERRUPTS_CASES){ + database.add(item); + } + for (const auto& item : CLASSIFY_CASES){ + database.add(item); + } + for (const auto& item : STEP_TIME_CASES){ + database.add(item); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp new file mode 100644 index 0000000000..b92a63e2a9 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp @@ -0,0 +1,93 @@ +/* Scene Judges + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_SceneJudges.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +WarpSeen note_warp(WarpSeen seen, const ScreenEvents& events, const std::string& banner_read){ + if (seen.fade == WarpFade::NONE){ + seen.fade = fade_in(events); + } + if (seen.banner.empty() && events.has(ScreenEvent::LOCATION_BANNER)){ + seen.banner = banner_read; + } + return seen; +} + +std::string describe(const WarpSeen& seen){ + if (!seen.any()){ + return "nothing"; + } + std::string out = seen.fade == WarpFade::NONE ? "" : warp_fade_name(seen.fade); + if (!seen.banner.empty()){ + out += (out.empty() ? "banner \"" : ", banner \"") + seen.banner + "\""; + } + return out; +} + + +SceneMove TalkOver::look(const ScreenEvents& look, WallClock now){ + if (look.has(ScreenEvent::BATTLE_STARTED)){ + m_quiet_since = WallClock::max(); + m_calm_since = WallClock::max(); + return SceneMove::BATTLE; + } + m_fade_showing = fade_in(look); + if (m_fade_showing != WarpFade::NONE){ + m_fade = m_fade_showing; + } + m_banner |= look.has(ScreenEvent::LOCATION_BANNER); + const bool box = look.has(ScreenEvent::DIALOG_BOX); + // A fade is never calm: BDSP's overworld reads a black frame as no + // box, and black stays still, so a closing fade counted as quiet and + // ended Mom's scene as it went down (lab-B 2026-11-09 14:33). + const bool calm = !box && m_fade_showing == WarpFade::NONE && + look.has(ScreenEvent::PLAYER_CAN_MOVE) && warped(); + const bool quiet = calm && look.has(ScreenEvent::SCREEN_STILL); + if (!calm){ + m_calm_since = WallClock::max(); + }else if (m_calm_since == WallClock::max()){ + m_calm_since = now; + } + if (!quiet){ + m_quiet_since = WallClock::max(); + }else if (m_quiet_since == WallClock::max()){ + m_quiet_since = now; + } + const bool over = + (quiet && now - m_quiet_since >= TALK_OVER_QUIET) || + (calm && now - m_calm_since >= TALK_OVER_CALM); + if (over && m_rule.end_on_quiet){ + return SceneMove::DONE; + } + return box ? SceneMove::NEXT : SceneMove::B; +} + +bool TalkOver::warped() const{ + return !m_rule.warp || m_fade != WarpFade::NONE || m_banner; +} + +std::string TalkOver::describe() const{ + if (m_fade == WarpFade::NONE && !m_banner){ + return "no fade or banner"; + } + std::string out = m_fade == WarpFade::NONE ? "" : warp_fade_name(m_fade); + if (m_fade != WarpFade::NONE){ + out += m_fade_showing == WarpFade::NONE ? " back up" : " still down"; + } + if (m_banner){ + out += out.empty() ? "banner read" : ", banner read"; + } + return out; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h new file mode 100644 index 0000000000..908dcaa39c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h @@ -0,0 +1,104 @@ +/* Scene Judges + * + * From: https://github.com/PokemonAutomation/ + * + * Judgements a story step makes from screen events (Pokemon_ScreenEvents.h) + * over time, not from one look (#268's design note): a warp is a fade or + * the banner of the map arrived on, and a talk or a scene is over when the + * overworld has been quiet for a while. Pure: tests drive them with + * scripted scenes, and every game shares them. + * + */ + +#ifndef PokemonAutomation_Pokemon_SceneJudges_H +#define PokemonAutomation_Pokemon_SceneJudges_H + +#include +#include "Common/Cpp/Time.h" +#include "Pokemon_ScreenEvents.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What a walk or a step saw of a warp (#268): a fade or the location +// banner of the map arrived on. Either one alone is the warp. +struct WarpSeen{ + WarpFade fade = WarpFade::NONE; + // The banner read, "" if none. + std::string banner = {}; + + bool any() const{ + return fade != WarpFade::NONE || !banner.empty(); + } +}; +// `seen` after a frame's events: their fade, and `banner_read` when they +// show LOCATION_BANNER. The first of each counts. +WarpSeen note_warp(WarpSeen seen, const ScreenEvents& events, const std::string& banner_read); +// How it was seen, for the log: a black fade, banner "Route 203". +std::string describe(const WarpSeen& seen); + + +// What to do after a look. +enum class SceneMove{ + NEXT, // A box shows: press the talk's button. + B, // No box: press B. It never starts a talk on the overworld + // (A would, and answers Yes on a prompt). + BATTLE, // A battle started. + DONE, // The talk or scene is over. +}; + +// What ends a talk-over, besides the quiet. +struct TalkOverRule{ + // A map change must come first: a fade or the banner. Only the quiet + // after it counts: r30's scene went quiet for 5 s before the fade home. + bool warp = false; + // False when a battle is to follow (a trainer's lines pause for more + // than 4 s before it, r210d): no quiet ends the talk then. + bool end_on_quiet = true; +}; + +// The overworld with no box and a still screen this long ends it: a scene +// pauses while someone walks off (Dawn and Barry after Rowan leaves, r23), +// a scripted walk-in ran 5 s with no text before Mom spoke (r31), and +// Roark's badge speech pauses for the fanfare (lab-B 2026-10-31 09:45 and +// 2026-11-08 15:06). The clock is the last look that was not quiet. +constexpr Milliseconds TALK_OVER_QUIET = Milliseconds(5000); +// The overworld with no box this long ends it, still or not: wanderers or +// grass can keep the screen from ever being still. +constexpr Milliseconds TALK_OVER_CALM = Milliseconds(15000); + +// When a talk or a scene is over, from looks alone. A look is a frame's +// events: DIALOG_BOX, PLAYER_CAN_MOVE, SCREEN_STILL, a fade, +// LOCATION_BANNER (the expected map's) and BATTLE_STARTED are read. +// It is over only once every fade has come back up, no box shows, and +// the overworld has been quiet (or calm) since: a look that shows a fade +// starts the quiet over, however still it is. +class TalkOver{ +public: + explicit TalkOver(TalkOverRule rule = {}) + : m_rule(rule) + {} + + SceneMove look(const ScreenEvents& look, WallClock now); + + // Whether the warp the rule asks for has shown (true without one). + bool warped() const; + // What it has seen, for the log: "black fade, banner read". + std::string describe() const; + +private: + TalkOverRule m_rule; + // The first fade seen, and the one the last look showed. + WarpFade m_fade = WarpFade::NONE; + WarpFade m_fade_showing = WarpFade::NONE; + bool m_banner = false; + WallClock m_quiet_since = WallClock::max(); + WallClock m_calm_since = WallClock::max(); +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp new file mode 100644 index 0000000000..b58a85cd9a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp @@ -0,0 +1,203 @@ +/* Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "Pokemon_ScreenEvents.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const char* screen_event_name(ScreenEvent event){ + switch (event){ + case ScreenEvent::FADE_BLACK: return "black fade"; + case ScreenEvent::FADE_WHITE: return "white fade"; + case ScreenEvent::LOCATION_BANNER: return "location banner"; + case ScreenEvent::DIALOG_BOX: return "dialog box"; + case ScreenEvent::CHOICE_BOX: return "choice box"; + case ScreenEvent::INTERACT_PROMPT: return "interact prompt"; + case ScreenEvent::BATTLE_STARTED: return "battle started"; + case ScreenEvent::BATTLE_ENDED: return "battle ended"; + case ScreenEvent::PLAYER_CAN_MOVE: return "player can move"; + case ScreenEvent::SCREEN_STILL: return "screen still"; + case ScreenEvent::SWITCH_HOME_MENU: return "Switch HOME menu"; + } + return "?"; +} + +const char* warp_fade_name(WarpFade fade){ + switch (fade){ + case WarpFade::NONE: return "no fade"; + case WarpFade::BLACK: return "black fade"; + case WarpFade::WHITE: return "white fade"; + } + return "?"; +} + + +ScreenEvents::ScreenEvents(std::initializer_list events){ + for (ScreenEvent event : events){ + set(event, true); + } +} +void ScreenEvents::set(ScreenEvent event, bool on){ + if (on){ + m_bits |= bit(event); + }else{ + m_bits &= ~bit(event); + } +} +ScreenEvents ScreenEvents::from_bits(uint32_t bits){ + ScreenEvents out; + out.m_bits = bits & ((uint32_t(1) << SCREEN_EVENT_COUNT) - 1); + return out; +} + +ScreenEvents fade_events(WarpFade fade){ + switch (fade){ + case WarpFade::NONE: + return {}; + case WarpFade::BLACK: + return {ScreenEvent::FADE_BLACK}; + case WarpFade::WHITE: + return {ScreenEvent::FADE_WHITE}; + } + return {}; +} +WarpFade fade_in(const ScreenEvents& events){ + if (events.has(ScreenEvent::FADE_BLACK)){ + return WarpFade::BLACK; + } + if (events.has(ScreenEvent::FADE_WHITE)){ + return WarpFade::WHITE; + } + return WarpFade::NONE; +} +std::string describe(const ScreenEvents& events){ + std::string out; + for (size_t c = 0; c < SCREEN_EVENT_COUNT; c++){ + const ScreenEvent event = (ScreenEvent)c; + if (!events.has(event)){ + continue; + } + if (!out.empty()){ + out += ", "; + } + out += screen_event_name(event); + } + return out.empty() ? "nothing" : out; +} + + +WarpFade fade_of(const ImageStats& middle){ + if (middle.stddev.sum() > FADE_MAX_STDDEV_SUM){ + return WarpFade::NONE; + } + const double sum = middle.average.sum(); + return sum <= FADE_MAX_DARK_SUM ? WarpFade::BLACK : sum >= FADE_MIN_WHITE_SUM ? WarpFade::WHITE : WarpFade::NONE; +} +WarpFade fade_of_screen(const ImageViewRGB32& screen){ + return fade_of(image_stats(extract_box_reference(screen, ImageFloatBox(0.1, 0.1, 0.8, 0.8)))); +} + + +ScreenEventLog::ScreenEventLog(size_t capacity) + : m_capacity(capacity) +{} +void ScreenEventLog::record(const ScreenEvents& frame, WallClock now){ + const uint32_t changed = frame.bits() ^ m_showing.bits(); + for (size_t c = 0; c < SCREEN_EVENT_COUNT; c++){ + if ((changed & (uint32_t(1) << c)) == 0){ + continue; + } + const ScreenEvent event = (ScreenEvent)c; + m_changes.push_back({now, event, frame.has(event) ? ScreenEventEdge::ROSE : ScreenEventEdge::FELL}); + } + while (m_changes.size() > m_capacity){ + m_changes.pop_front(); + m_dropped++; + } + m_showing = frame; + m_last_frame = now; +} +void ScreenEventLog::clear(){ + m_changes.clear(); + m_dropped = 0; + m_showing = ScreenEvents(); + m_last_frame.reset(); +} +std::string describe(const ScreenEventLog& log, WallClock origin){ + std::string out; + if (log.dropped() > 0){ + out += std::format("({} older changes dropped)\n", log.dropped()); + } + for (const ScreenEventChange& change : log.changes()){ + out += std::format( + "{:+} ms {} {}\n", + std::chrono::duration_cast(change.time - origin).count(), + screen_event_name(change.event), + change.edge == ScreenEventEdge::ROSE ? "rose" : "fell" + ); + } + return out.empty() ? "no changes" : out; +} + + +SwitchHomeObserver::SwitchHomeObserver(NintendoSwitch::ConsoleHandle& console, ScreenEventObserver& game) + : m_game(game) + , m_home(console, COLOR_RED) +{} + +ScreenEvents SwitchHomeObserver::observe(const VideoSnapshot& frame, WallClock now){ + if (frame && m_home.detect_only(*frame.frame)){ + return {ScreenEvent::SWITCH_HOME_MENU}; + } + return m_game.observe(frame, now); +} + +void SwitchHomeObserver::make_overlays(VideoOverlaySet& items) const{ + m_game.make_overlays(items); +} + + +ScreenEventWatcher::ScreenEventWatcher(ScreenEventObserver& observer, ScreenEvents stop_on) + : VisualInferenceCallback("ScreenEventWatcher") + , m_observer(observer) + , m_stop_on(stop_on) +{} +void ScreenEventWatcher::make_overlays(VideoOverlaySet& items) const{ + m_observer.make_overlays(items); +} +bool ScreenEventWatcher::process_frame(const VideoSnapshot& frame){ + const ScreenEvents events = m_observer.observe(frame, frame.timestamp); + m_seen.fetch_or(events.bits(), std::memory_order_acq_rel); + { + LockGuard lg(m_log_lock); + m_log.record(events, frame.timestamp); + } + if (!events.any_of(m_stop_on)){ + return false; + } + m_stopped_on.store(events.bits(), std::memory_order_release); + return true; +} +ScreenEventLog ScreenEventWatcher::log() const{ + LockGuard lg(m_log_lock); + return m_log; +} +void ScreenEventWatcher::reset(){ + m_seen.store(0, std::memory_order_release); + m_stopped_on.store(0, std::memory_order_release); + LockGuard lg(m_log_lock); + m_log.clear(); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h new file mode 100644 index 0000000000..800351a306 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h @@ -0,0 +1,262 @@ +/* Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + * What a story step can see on the screen, in words every game shares: a + * fade, a location banner, a dialogue box, a battle starting. Each game + * implements ScreenEventObserver with its own detectors; the judgements + * built on these events (Pokemon_SceneJudges.h) are then the same for all + * of them. + * + * An observer runs during a controller action as a ScreenEventWatcher + * (a VisualInferenceCallback for run_until), or is asked frame by frame. + * + */ + +#ifndef PokemonAutomation_Pokemon_ScreenEvents_H +#define PokemonAutomation_Pokemon_ScreenEvents_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Concurrency/Mutex.h" +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// One thing a frame shows. A game reports the ones its detectors can see. +enum class ScreenEvent : uint8_t{ + FADE_BLACK, // A uniform dark screen: a door, a cave mouth, a scene cut. + FADE_WHITE, // A uniform white screen: a cave exit. + LOCATION_BANNER, // A location banner. An observer given an expected + // map reports only that map's. + DIALOG_BOX, // A dialogue box. + CHOICE_BOX, // A choice (Yes/No, a menu of answers). + INTERACT_PROMPT, // A button prompt to interact ("A Talk"). + BATTLE_STARTED, // A battle shows (its menu, its HUD or its opening). + BATTLE_ENDED, // A battle's closing screen. + PLAYER_CAN_MOVE, // The overworld with the player in control. + SCREEN_STILL, // The screen barely changed since the frame before. + SWITCH_HOME_MENU, // The Switch's HOME menu: the game is not on the screen. +}; +// How many ScreenEvent values there are. +constexpr size_t SCREEN_EVENT_COUNT = 11; +// "dialog box", for the log. +const char* screen_event_name(ScreenEvent event); + + +// How a screen's fade looks: the kind of FADE_BLACK / FADE_WHITE. +enum class WarpFade{ + NONE, + BLACK, // a door's black, or a cave mouth's dim fade + WHITE, // a cave exit's white, with no battle after it +}; +// "black fade", for the log. +const char* warp_fade_name(WarpFade fade); + + +// The events of one frame, or of all the frames a watcher saw. +class ScreenEvents{ +public: + ScreenEvents() = default; + ScreenEvents(std::initializer_list events); + + bool has(ScreenEvent event) const{ + return (m_bits & bit(event)) != 0; + } + // Whether any of `events` is in this set. + bool any_of(const ScreenEvents& events) const{ + return (m_bits & events.m_bits) != 0; + } + // Adds `event`, or removes it when `on` is false (as std::bitset::set). + void set(ScreenEvent event, bool on); + void merge(const ScreenEvents& events){ + m_bits |= events.m_bits; + } + + uint32_t bits() const{ + return m_bits; + } + static ScreenEvents from_bits(uint32_t bits); + + bool operator==(const ScreenEvents& other) const = default; + +private: + static uint32_t bit(ScreenEvent event){ + return uint32_t(1) << (uint32_t)event; + } + + uint32_t m_bits = 0; +}; +// The event of a fade: FADE_BLACK, FADE_WHITE, or none for WarpFade::NONE. +ScreenEvents fade_events(WarpFade fade); +// The fade `events` show: BLACK before WHITE if they have both. +WarpFade fade_in(const ScreenEvents& events); +// "dialog box, player can move"; "nothing" when empty. +std::string describe(const ScreenEvents& events); + + +// A fade is uniform over the middle 80% of the screen, the shared +// Black/WhiteScreenWatcher's stddev test (upstream #1717): a dim cave floor +// is textured, so it is no fade (BDSP's Oreburgh Gate, mean 46, lab-B +// 2026-11-08). Check against the Gate's frames on the console before +// tightening. +constexpr double FADE_MAX_STDDEV_SUM = 10; +// Dark goes to an rgb sum of 225, as a cave mouth's fade is dim, 45 to 64 +// a channel, not black. +constexpr double FADE_MAX_DARK_SUM = 225; +// White from an rgb sum of 500, as the shared WhiteScreenWatcher's. +constexpr double FADE_MIN_WHITE_SUM = 500; +// The fade `middle` (the stats of the screen's middle 80%) shows, if any. +WarpFade fade_of(const ImageStats& middle); +// fade_of() for a screen. +WarpFade fade_of_screen(const ImageViewRGB32& screen); + + +// Whether an event started or stopped showing. +enum class ScreenEventEdge : uint8_t{ + ROSE, + FELL, +}; + +// One event starting or stopping to show, at the frame that showed it. +struct ScreenEventChange{ + WallClock time; + ScreenEvent event; + ScreenEventEdge edge; + + bool operator==(const ScreenEventChange& other) const = default; +}; + +// How many changes a log keeps. A walk's events change a few times a +// second at most (a fade's black, a box, the screen going still), so this +// is a minute or more of a busy scene. +constexpr size_t SCREEN_EVENT_LOG_CAPACITY = 256; + +// The events of a stream of frames, in order and timed: what rose and fell +// when, not only what was seen (ScreenEventWatcher::seen()). The judges that +// care about order read it (Pokemon_Interrupts.h): a flash then a battle is +// an encounter, a box then a battle a trainer's sight. +// +// It keeps the newest `capacity` changes and counts the ones it dropped. +// Not thread-safe; ScreenEventWatcher guards its own. +class ScreenEventLog{ +public: + explicit ScreenEventLog(size_t capacity = SCREEN_EVENT_LOG_CAPACITY); + + // Adds a frame: a change for each event that rose or fell since the + // frame before (the first frame's events all rise). `now` must not go + // back in time. + void record(const ScreenEvents& frame, WallClock now); + + // The changes kept, oldest first. + const std::deque& changes() const{ + return m_changes; + } + // How many changes were dropped, oldest first, to keep the capacity. + size_t dropped() const{ + return m_dropped; + } + // The events of the last frame recorded. + ScreenEvents showing() const{ + return m_showing; + } + // When the last frame was recorded; none before the first. + std::optional last_frame() const{ + return m_last_frame; + } + void clear(); + +private: + size_t m_capacity; + std::deque m_changes; + size_t m_dropped = 0; + ScreenEvents m_showing; + std::optional m_last_frame; +}; +// "+1200 ms dialog box rose", times from `origin`, one change per line. +std::string describe(const ScreenEventLog& log, WallClock origin); + + +// A game's detectors, as events. Observers may keep state between frames +// (the frame before, for SCREEN_STILL; when a banner was last read, to +// gate OCR), so one observer watches one stream at a time. +class ScreenEventObserver{ +public: + virtual ~ScreenEventObserver() = default; + + // What `frame` shows. `now` is the caller's clock, for observers that + // rate-limit expensive reads. A null frame shows nothing. + virtual ScreenEvents observe(const VideoSnapshot& frame, WallClock now) = 0; + + // The boxes the detectors read, for the video overlay. + virtual void make_overlays(VideoOverlaySet& items) const = 0; +}; + + +// A game's observer behind a look at the Switch itself: a frame showing +// the HOME menu shows SWITCH_HOME_MENU and nothing else, as a game's +// detectors may read HOME's plain screen as a quiet overworld (BDSP, +// lab-B 2026-11-09). Every other frame is the game's to read. +class SwitchHomeObserver : public ScreenEventObserver{ +public: + SwitchHomeObserver(NintendoSwitch::ConsoleHandle& console, ScreenEventObserver& game); + + virtual ScreenEvents observe(const VideoSnapshot& frame, WallClock now) override; + virtual void make_overlays(VideoOverlaySet& items) const override; + +private: + ScreenEventObserver& m_game; + NintendoSwitch::HomeMenuDetector m_home; +}; + + +// An observer as a run_until callback: it records every event it sees, in +// order in a log, and stops the action on any of `stop_on` (none: it only +// records). +class ScreenEventWatcher : public VisualInferenceCallback{ +public: + ScreenEventWatcher(ScreenEventObserver& observer, ScreenEvents stop_on = {}); + + virtual void make_overlays(VideoOverlaySet& items) const override; + using VisualInferenceCallback::process_frame; + virtual bool process_frame(const VideoSnapshot& frame) override; + + // Every event seen since construction (or the last reset()). + ScreenEvents seen() const{ + return ScreenEvents::from_bits(m_seen.load(std::memory_order_acquire)); + } + // The events of the frame that stopped the action ("nothing" if none did). + ScreenEvents stopped_on() const{ + return ScreenEvents::from_bits(m_stopped_on.load(std::memory_order_acquire)); + } + // A copy of the timed log of every frame since construction (or the + // last reset()). + ScreenEventLog log() const; + void reset(); + +private: + ScreenEventObserver& m_observer; + const ScreenEvents m_stop_on; + std::atomic m_seen{0}; + std::atomic m_stopped_on{0}; + mutable Mutex m_log_lock; + ScreenEventLog m_log; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp new file mode 100644 index 0000000000..6620fd0204 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp @@ -0,0 +1,280 @@ +/* Screen Events Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The shared event vocabulary, the watcher form of an observer, and the + * judgements over events (warp seen, talk-over). + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "Pokemon_AutoStory_Tests.h" +#include "Pokemon_SceneJudges.h" +#include "Pokemon_ScreenEvents.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +using namespace std::chrono_literals; + +UnitTestResult expect_equal(const std::string& what, const std::string& got, const std::string& expected){ + if (got == expected){ + return true; + } + return std::format("{}: expected \"{}\", got \"{}\"", what, expected, got); +} + + +UnitTestResult test_set_and_describe(){ + ScreenEvents events{ScreenEvent::DIALOG_BOX, ScreenEvent::PLAYER_CAN_MOVE}; + if (!events.has(ScreenEvent::DIALOG_BOX) || events.has(ScreenEvent::CHOICE_BOX)){ + return "has() disagrees with the constructor's events"; + } + events.set(ScreenEvent::DIALOG_BOX, false); + events.merge(fade_events(WarpFade::WHITE)); + events.merge(fade_events(WarpFade::NONE)); + if (fade_in(events) != WarpFade::WHITE){ + return "fade_events(WHITE) did not give a white fade"; + } + if (ScreenEvents::from_bits(events.bits()) != events){ + return "from_bits(bits()) is not the same set"; + } + if (describe(ScreenEvents()) != "nothing"){ + return "an empty set does not describe as nothing"; + } + return expect_equal("describe()", describe(events), "white fade, player can move"); +} + +// A screen filled with one colour, or a checkerboard of two. +ImageRGB32 screen_of(uint32_t a, uint32_t b){ + ImageRGB32 out(64, 36); + for (size_t y = 0; y < out.height(); y++){ + for (size_t x = 0; x < out.width(); x++){ + out.pixel(x, y) = (x + y) % 2 == 0 ? a : b; + } + } + return out; +} + +UnitTestResult test_fade_of_screen(){ + struct Row{ + const char* name; + uint32_t a; + uint32_t b; + WarpFade fade; + }; + const std::vector rows = { + {"black", 0xff000000, 0xff000000, WarpFade::BLACK}, + {"a cave mouth's dim fade (60 a channel)", 0xff3c3c3c, 0xff3c3c3c, WarpFade::BLACK}, + {"white", 0xffffffff, 0xffffffff, WarpFade::WHITE}, + {"grey, neither", 0xff787878, 0xff787878, WarpFade::NONE}, + {"a dark textured floor", 0xff101010, 0xff505050, WarpFade::NONE}, + }; + for (const Row& row : rows){ + const WarpFade got = fade_of_screen(screen_of(row.a, row.b)); + if (got != row.fade){ + return std::format("{}: expected {}, got {}", row.name, warp_fade_name(row.fade), warp_fade_name(got)); + } + } + return true; +} + +UnitTestResult test_warp_seen(){ + WarpSeen seen = note_warp({}, {ScreenEvent::DIALOG_BOX}, "Route 203"); + if (seen.any()){ + return "a dialog box with no banner event counted as a warp"; + } + seen = note_warp(seen, {ScreenEvent::FADE_BLACK}, ""); + seen = note_warp(seen, {ScreenEvent::FADE_WHITE, ScreenEvent::LOCATION_BANNER}, "Route 203"); + seen = note_warp(seen, {ScreenEvent::LOCATION_BANNER}, "Oreburgh Gate"); + return expect_equal("describe(WarpSeen)", describe(seen), "black fade, banner \"Route 203\""); +} + + +// A scripted scene: a look per beat, each `every` apart. Returns the beat +// TalkOver first says `want` at, or -1. +int first_beat(TalkOver& judge, const std::vector& beats, SceneMove want, Milliseconds every = 1000ms){ + WallClock now = WallClock(); + for (size_t c = 0; c < beats.size(); c++){ + if (judge.look(beats[c], now) == want){ + return (int)c; + } + now += every; + } + return -1; +} + +const ScreenEvents QUIET{ScreenEvent::PLAYER_CAN_MOVE, ScreenEvent::SCREEN_STILL}; +const ScreenEvents CALM{ScreenEvent::PLAYER_CAN_MOVE}; +const ScreenEvents BOX{ScreenEvent::DIALOG_BOX, ScreenEvent::PLAYER_CAN_MOVE, ScreenEvent::SCREEN_STILL}; +// A black frame as BDSP's eyes see it: no box, so "overworld", and still. +const ScreenEvents FADED{ScreenEvent::FADE_BLACK, ScreenEvent::PLAYER_CAN_MOVE, ScreenEvent::SCREEN_STILL}; +const ScreenEvents CALM_FADED{ScreenEvent::FADE_BLACK, ScreenEvent::PLAYER_CAN_MOVE}; + +std::vector repeat(const ScreenEvents& look, size_t count){ + return std::vector(count, look); +} +std::vector concat(std::vector a, const std::vector& b){ + a.insert(a.end(), b.begin(), b.end()); + return a; +} + +UnitTestResult test_talk_over(){ + struct Row{ + const char* name; + TalkOverRule rule; + std::vector beats; + SceneMove want; + int beat; + }; + const std::vector rows = { + {"5 s of quiet ends it", {}, repeat(QUIET, 8), SceneMove::DONE, 5}, + {"a box restarts the quiet", {}, concat(concat(repeat(QUIET, 3), {BOX}), repeat(QUIET, 8)), SceneMove::DONE, 9}, + {"a box is answered", {}, {BOX}, SceneMove::NEXT, 0}, + {"no box is a B press", {}, {QUIET}, SceneMove::B, 0}, + {"15 s calm but moving ends it", {}, repeat(CALM, 20), SceneMove::DONE, 15}, + {"a warp rule waits for the fade", {.warp = true}, + concat(concat(repeat(QUIET, 8), {ScreenEvents{ScreenEvent::FADE_BLACK}}), repeat(QUIET, 8)), + SceneMove::DONE, 14}, + {"a banner is the warp too", {.warp = true}, + concat({ScreenEvents{ScreenEvent::LOCATION_BANNER, ScreenEvent::PLAYER_CAN_MOVE}}, repeat(QUIET, 8)), + SceneMove::DONE, 6}, + {"no quiet ends a talk before a battle", {.end_on_quiet = false}, repeat(QUIET, 30), SceneMove::DONE, -1}, + {"a battle", {.end_on_quiet = false}, concat(repeat(QUIET, 6), {ScreenEvents{ScreenEvent::BATTLE_STARTED}}), SceneMove::BATTLE, 6}, + // Mom's Running Shoes scene (lab-B 2026-11-09 14:33): quiet, then + // the scene's closing fade. It ended at the fade's start and the + // next step's input landed in the fade. + {"a closing fade starts the quiet over", {}, + concat(concat(repeat(QUIET, 4), repeat(FADED, 3)), repeat(QUIET, 8)), + SceneMove::DONE, 12}, + {"a fade still down never ends it", {}, concat(repeat(QUIET, 3), repeat(FADED, 20)), SceneMove::DONE, -1}, + {"a fade is never calm", {}, concat(repeat(CALM, 10), repeat(CALM_FADED, 10)), SceneMove::DONE, -1}, + }; + for (const Row& row : rows){ + TalkOver judge(row.rule); + const int got = first_beat(judge, row.beats, row.want); + if (got != row.beat){ + return std::format("{}: expected beat {}, got {} ({})", row.name, row.beat, got, judge.describe()); + } + } + return true; +} + + +// Replays a fixed list of event sets, one per frame. +class ScriptedObserver : public ScreenEventObserver{ +public: + explicit ScriptedObserver(std::vector frames) + : m_frames(std::move(frames)) + {} + virtual ScreenEvents observe(const VideoSnapshot&, WallClock) override{ + return m_next < m_frames.size() ? m_frames[m_next++] : ScreenEvents(); + } + virtual void make_overlays(VideoOverlaySet&) const override{} + +private: + std::vector m_frames; + size_t m_next = 0; +}; + +UnitTestResult test_watcher(){ + ScriptedObserver observer({ + {ScreenEvent::PLAYER_CAN_MOVE}, + {ScreenEvent::FADE_BLACK}, + {ScreenEvent::LOCATION_BANNER, ScreenEvent::PLAYER_CAN_MOVE}, + {ScreenEvent::DIALOG_BOX}, + }); + ScreenEventWatcher watcher(observer, {ScreenEvent::LOCATION_BANNER}); + const VideoSnapshot frame; + std::vector stops; + for (size_t c = 0; c < 4; c++){ + stops.push_back(watcher.process_frame(frame)); + } + if (stops != std::vector{false, false, true, false}){ + return "the watcher did not stop exactly on the banner frame"; + } + UnitTestResult result = expect_equal("seen()", describe(watcher.seen()), + "black fade, location banner, dialog box, player can move"); + if (result.result != UnitTestResult::PASSED){ + return result; + } + result = expect_equal("stopped_on()", describe(watcher.stopped_on()), "location banner, player can move"); + if (result.result != UnitTestResult::PASSED){ + return result; + } + watcher.reset(); + return expect_equal("seen() after reset()", describe(watcher.seen()), "nothing"); +} + + +struct ScreenEventsInput{ + std::string name; + std::function body; +}; + +struct ScreenEventsExpectation{ +}; + +struct ScreenEventsCase{ + ScreenEventsInput input; + ScreenEventsExpectation expectation; +}; + +class Test_ScreenEvents : public UnitTest{ +public: + explicit Test_ScreenEvents(ScreenEventsCase test_case) + : UnitTest("Pokemon::ScreenEvents - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_case.input.body(); + } + +private: + ScreenEventsCase m_case; +}; + +} // namespace + + +const ScreenEventsCase SCREEN_EVENTS_CASES[] = { + { + .input = {"a set of events, its fade and its log text", test_set_and_describe}, + .expectation = {}, + }, + { + .input = {"a fade is uniform, dark or white; a textured floor is none", test_fade_of_screen}, + .expectation = {}, + }, + { + .input = {"a warp is the first fade and the first banner seen", test_warp_seen}, + .expectation = {}, + }, + { + .input = {"talk-over from scripted events", test_talk_over}, + .expectation = {}, + }, + { + .input = {"an observer as a watcher records and stops", test_watcher}, + .expectation = {}, + }, +}; + +void add_tests_ScreenEvents(UnitTestDatabase& database){ + for (const auto& item : SCREEN_EVENTS_CASES){ + database.add(item); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.cpp new file mode 100644 index 0000000000..715869aa27 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.cpp @@ -0,0 +1,272 @@ +/* Transitions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "Pokemon_Transitions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const FadeProfile BDSP_FADE_PROFILE{ + .uniform_max_stddev_sum = 10, + .partial_max_stddev_sum = 60, + .dark_max_sum = 225, + .partial_dark_max_sum = 300, + .white_min_sum = 500, + .partial_white_min_sum = 450, + .max_fall = Milliseconds(1000), + .max_hold = Milliseconds(8000), + .has_white_fade = true, + .flash_max_hold = Milliseconds(150), + .white_fade_min_hold = Milliseconds(400), +}; +const FadeProfile FRLG_FADE_PROFILE{ + .uniform_max_stddev_sum = 10, + .partial_max_stddev_sum = 60, + .dark_max_sum = 100, + .partial_dark_max_sum = 200, + .white_min_sum = 500, + .partial_white_min_sum = 450, + .max_fall = Milliseconds(1000), + .max_hold = Milliseconds(8000), + .has_white_fade = false, + .flash_max_hold = Milliseconds(150), + .white_fade_min_hold = Milliseconds(400), +}; + + +const char* transition_kind_name(TransitionKind kind){ + switch (kind){ + case TransitionKind::FADE_BLACK: return "black fade"; + case TransitionKind::FADE_WHITE: return "white fade"; + case TransitionKind::FLASH: return "flash"; + case TransitionKind::WHITE_UNSURE: return "white, flash or fade"; + } + return "?"; +} + + +TransitionSample transition_sample(const VideoSnapshot& frame){ + TransitionSample out{frame.timestamp, {}, frame}; + if (frame){ + out.middle = image_stats(extract_box_reference(*frame.frame, ImageFloatBox(0.1, 0.1, 0.8, 0.8))); + } + return out; +} + + +Milliseconds Transition::hold() const{ + if (!peak || !rise){ + return Milliseconds(0); + } + return std::chrono::duration_cast(*rise - *peak); +} + +namespace{ + +std::string offset(std::optional time, WallClock origin){ + if (!time){ + return "unseen"; + } + return std::format("{:+} ms", std::chrono::duration_cast(*time - origin).count()); +} +const char* scene_change_name(SceneChange change){ + switch (change){ + case SceneChange::UNKNOWN: return "scene unknown"; + case SceneChange::SAME: return "same scene"; + case SceneChange::DIFFERENT: return "other scene"; + } + return "?"; +} + +} // namespace + +std::string describe(const Transition& transition, WallClock origin){ + std::string out = std::format( + "{} {}, peak {}, rise {}", + transition_kind_name(transition.kind), + offset(transition.start, origin), + offset(transition.peak, origin), + offset(transition.rise, origin) + ); + if (!transition.end){ + return out + ", in progress"; + } + return out + std::format(", end {}, {}", offset(transition.end, origin), scene_change_name(transition.change)); +} + + +TransitionTracker::TransitionTracker(FadeProfile profile, CompareScenes compare) + : m_profile(profile) + , m_compare(std::move(compare)) +{} + +TransitionTracker::Level TransitionTracker::level_of(const ImageStats& middle) const{ + const double stddev = middle.stddev.sum(); + const double sum = middle.average.sum(); + if (stddev <= m_profile.uniform_max_stddev_sum){ + if (sum <= m_profile.dark_max_sum){ + return Level::DARK; + } + if (sum >= m_profile.white_min_sum){ + return Level::WHITE; + } + } + if (stddev <= m_profile.partial_max_stddev_sum){ + if (sum <= m_profile.partial_dark_max_sum){ + return Level::PARTIAL_DARK; + } + if (sum >= m_profile.partial_white_min_sum){ + return Level::PARTIAL_WHITE; + } + } + return Level::SCENE; +} + +std::optional TransitionTracker::push(const TransitionSample& sample){ + switch (level_of(sample.middle)){ + case Level::SCENE: + return on_scene(sample); + case Level::PARTIAL_DARK: + return on_partial(sample, false); + case Level::PARTIAL_WHITE: + return on_partial(sample, true); + case Level::DARK: + on_uniform(sample, false); + return std::nullopt; + case Level::WHITE: + on_uniform(sample, true); + return std::nullopt; + } + return std::nullopt; +} + +std::optional TransitionTracker::on_scene(const TransitionSample& sample){ + m_scene_is_partial = false; + if (m_phase == TransitionPhase::SCENE){ + m_before = sample; + return std::nullopt; + } + if (m_phase == TransitionPhase::HOLD){ + m_current.rise = sample.time; + } + return finish(sample); +} + +// A partial frame starts a fall from a scene, unless the scene itself +// looks partial (a dim floor). Partial frames for longer than max_fall, +// falling or rising, are a scene again. +std::optional TransitionTracker::on_partial(const TransitionSample& sample, bool white){ + switch (m_phase){ + case TransitionPhase::SCENE: + if (m_scene_is_partial){ + m_before = sample; + return std::nullopt; + } + m_current = Transition{.start = sample.time}; + m_white = white; + m_phase = TransitionPhase::FALLING; + return std::nullopt; + case TransitionPhase::FALLING: + m_white = white; + if (sample.time - m_current.start > m_profile.max_fall){ + m_phase = TransitionPhase::SCENE; + m_scene_is_partial = true; + m_before = sample; + } + return std::nullopt; + case TransitionPhase::HOLD: + m_current.rise = sample.time; + m_phase = TransitionPhase::RISING; + return std::nullopt; + case TransitionPhase::RISING: + if (sample.time - *m_current.rise <= m_profile.max_fall){ + return std::nullopt; + } + m_scene_is_partial = true; + return finish(sample); + } + return std::nullopt; +} + +void TransitionTracker::on_uniform(const TransitionSample& sample, bool white){ + switch (m_phase){ + case TransitionPhase::SCENE: + m_current = Transition{.start = sample.time, .peak = sample.time}; + m_white = white; + break; + case TransitionPhase::FALLING: + m_current.peak = sample.time; + m_white = white; + break; + case TransitionPhase::HOLD: + break; + case TransitionPhase::RISING: + // Back down again before a scene showed: the same hold. + m_current.rise.reset(); + break; + } + m_phase = TransitionPhase::HOLD; +} + +// Back on a scene: a transition if it held, or if it fell to another +// scene with its hold unseen. A fall back to the same scene is a dip. +std::optional TransitionTracker::finish(const TransitionSample& sample){ + const SceneChange change = m_compare && m_before ? m_compare(*m_before, sample) : SceneChange::UNKNOWN; + m_phase = TransitionPhase::SCENE; + m_before = sample; + if (!m_current.peak && change != SceneChange::DIFFERENT){ + return std::nullopt; + } + m_current.end = sample.time; + m_current.change = change; + m_current.kind = m_white ? kind_of(m_current.hold(), change) : TransitionKind::FADE_BLACK; + m_last = m_current; + return m_current; +} + +TransitionKind TransitionTracker::kind_of(Milliseconds hold, SceneChange change) const{ + if (!m_profile.has_white_fade){ + return TransitionKind::FLASH; + } + if (hold <= m_profile.flash_max_hold && change != SceneChange::DIFFERENT){ + return TransitionKind::FLASH; + } + if (hold >= m_profile.white_fade_min_hold && change != SceneChange::SAME){ + return TransitionKind::FADE_WHITE; + } + return TransitionKind::WHITE_UNSURE; +} + +std::optional TransitionTracker::current() const{ + if (m_phase == TransitionPhase::SCENE){ + return m_last; + } + Transition out = m_current; + out.kind = m_white ? TransitionKind::WHITE_UNSURE : TransitionKind::FADE_BLACK; + return out; +} + +bool TransitionTracker::timed_out(WallClock now) const{ + return m_phase != TransitionPhase::SCENE && now - m_current.start > m_profile.max_hold; +} + +void TransitionTracker::reset(){ + m_phase = TransitionPhase::SCENE; + m_white = false; + m_scene_is_partial = false; + m_before.reset(); + m_current = Transition{}; + m_last.reset(); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.h new file mode 100644 index 0000000000..5764247571 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions.h @@ -0,0 +1,197 @@ +/* Transitions + * + * From: https://github.com/PokemonAutomation/ + * + * A screen transition followed over many frames rather than judged on one: + * the scene, the screen falling toward a uniform colour, the uniform hold, + * the rise, and the scene it comes back on. fade_of() alone judges one + * frame, so a 50 ms door fade that falls between two sampled frames is never + * seen, and the step waits out its whole timeout (12 s for a BDSP door). + * The tracker sees the frames around it instead: the screen falling, then a + * different scene. + * + * Each game's numbers are a FadeProfile; the tracker is the same for all. + * + */ + +#ifndef PokemonAutomation_Pokemon_Transitions_H +#define PokemonAutomation_Pokemon_Transitions_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Whether the screen differs after a transition from before it. The +// tracker has only frame statistics; the caller compares the frames, or +// says it did not. +enum class SceneChange{ + UNKNOWN, + SAME, + DIFFERENT, +}; + + +// A game's fades, as data. Two tiers of the same test: a frame is uniform +// (the fade's hold) when its middle's stddev sum is at most +// `uniform_max_stddev_sum`, and partial (on the way down or up) when it is +// at most `partial_max_stddev_sum`. Either way it is dark or white by its +// rgb sum. +struct FadeProfile{ + double uniform_max_stddev_sum = 10; + double partial_max_stddev_sum = 60; + // Dark at or below this rgb sum; a partial frame up to `partial_dark_max_sum`. + double dark_max_sum = 225; + double partial_dark_max_sum = 300; + // White at or above this rgb sum; a partial frame from `partial_white_min_sum`. + double white_min_sum = 500; + double partial_white_min_sum = 450; + + // Partial frames for longer than this, with no hold, are the scene's + // own look (a dim cave floor, a street at night), not a fade. + Milliseconds max_fall = Milliseconds(1000); + // A transition still dark or white after this has timed out: the + // screen did not come back. + Milliseconds max_hold = Milliseconds(8000); + + // Whether the game fades to white between maps (BDSP's cave exits). + // Without, every white is an encounter's flash. + bool has_white_fade = true; + // A white held this long or less, back on the same scene, is a flash. + Milliseconds flash_max_hold = Milliseconds(150); + // A white held this long or more, not back on the same scene, is a + // white fade. Between the two the white is unsure. + Milliseconds white_fade_min_hold = Milliseconds(400); +}; + +// BDSP. The uniform tier is the shared walk's (FADE_MAX_STDDEV_SUM, the +// Oreburgh Gate's textured floor is no fade, lab-B 2026-11-08); the partial +// tier is run_into_door()'s 60, which caught the doorway's dim fade frames. +// A cave mouth's fade is dim (45 to 64 a channel), hence the dark sum of 225. +// The flash and white-fade holds are provisional: no console frames of an +// encounter flash and a cave exit have been timed side by side yet, so the +// band between them is wide and reports WHITE_UNSURE. +extern const FadeProfile BDSP_FADE_PROFILE; +// FRLG. The GBA fades to true black, so the dark tiers are the shared +// BlackScreenDetector's 100 and a little above; it has no white fade between +// maps, so every white is an encounter's flash. +extern const FadeProfile FRLG_FADE_PROFILE; + + +// What a transition was. +enum class TransitionKind : uint8_t{ + FADE_BLACK, // A door, a cave mouth, a scene cut, a battle's own fade. + FADE_WHITE, // A cave exit: a long white onto another scene. + FLASH, // An encounter's flash: a short white, back on the scene. + WHITE_UNSURE, // A white that may be either: wait for a battle. +}; +// "black fade", for the log. +const char* transition_kind_name(TransitionKind kind); + +// Where the tracker is in a transition. +enum class TransitionPhase : uint8_t{ + SCENE, // No transition: the screen shows a scene. + FALLING, // Partial frames, toward dark or white. + HOLD, // Uniform frames. + RISING, // Partial frames after the hold. +}; + +// One frame, as the tracker reads it. +struct TransitionSample{ + WallClock time = {}; + // The stats of the screen's middle 80%, as fade_of_screen() reads. + ImageStats middle = {}; + // The frame itself, for the caller's scene comparison. May be empty. + VideoSnapshot frame = {}; +}; +// A sample of `frame`, at its timestamp. +TransitionSample transition_sample(const VideoSnapshot& frame); + +// One transition, complete or in progress. +struct Transition{ + TransitionKind kind = TransitionKind::FADE_BLACK; + // The first frame off the scene: falling, or the hold if no fall was seen. + WallClock start = {}; + // The first uniform frame. None: the hold fell between two frames, and + // only the falling frames and the new scene were seen. + std::optional peak = {}; + // The first frame off the hold. + std::optional rise = {}; + // The first frame back on a scene. None while in progress. + std::optional end = {}; + // The scene after against the one before; UNKNOWN in progress. + SceneChange change = SceneChange::UNKNOWN; + + // How long the uniform frames showed; zero with no peak. + Milliseconds hold() const; +}; +// "black fade +200 ms, peak +300 ms, rise +700 ms, end +800 ms, other scene", +// times from `origin`. +std::string describe(const Transition& transition, WallClock origin); + + +// The transition state machine, fed one frame at a time: scene, falling, +// hold, rising, scene. Not thread-safe. +class TransitionTracker{ +public: + // Compares the last scene frame before a transition with the first + // after it. + using CompareScenes = std::function; + + // With no `compare`, every scene change is UNKNOWN, and a transition + // whose hold went unseen is not reported. + explicit TransitionTracker(FadeProfile profile, CompareScenes compare = {}); + + // Adds a frame; times must not go back. Returns the transition this + // frame completed, if any. + std::optional push(const TransitionSample& sample); + + TransitionPhase phase() const{ + return m_phase; + } + // The transition in progress, else the last one completed. + std::optional current() const; + // Whether the transition in progress has gone on longer than max_hold + // at `now`. + bool timed_out(WallClock now) const; + void reset(); + +private: + enum class Level : uint8_t{ + SCENE, + PARTIAL_DARK, + PARTIAL_WHITE, + DARK, + WHITE, + }; + Level level_of(const ImageStats& middle) const; + + std::optional on_scene(const TransitionSample& sample); + std::optional on_partial(const TransitionSample& sample, bool white); + void on_uniform(const TransitionSample& sample, bool white); + std::optional finish(const TransitionSample& sample); + TransitionKind kind_of(Milliseconds hold, SceneChange change) const; + + FadeProfile m_profile; + CompareScenes m_compare; + TransitionPhase m_phase = TransitionPhase::SCENE; + bool m_white = false; + // The scene itself looks partial (a dim floor): partial frames are no fall. + bool m_scene_is_partial = false; + std::optional m_before; + Transition m_current; + std::optional m_last; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp new file mode 100644 index 0000000000..2f29f54475 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp @@ -0,0 +1,378 @@ +/* Transitions Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The transition tracker on synthetic frame statistics: a frame is its + * middle's mean and stddev at a time. Then the same tracker on captured + * frames from CommandLineTests, when they are checked out. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Filesystem/FileIO.h" +#include "Common/Cpp/Filesystem/Filesystem.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/GlobalAutoPaths.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "Pokemon_AutoStory_Tests.h" +#include "Pokemon_Interrupts.h" +#include "Pokemon_Transitions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +using namespace std::chrono_literals; + +const WallClock T0 = WallClock() + std::chrono::hours(1); + +ImageStats stats(double r, double g, double b, double stddev){ + return ImageStats(FloatPixel(r, g, b), FloatPixel(stddev, stddev, stddev), 1000); +} + +// Scenes are textured; each has its own mean, which the comparison reads. +const ImageStats ROUTE = stats(120, 100, 90, 40); +const ImageStats HOUSE = stats(100, 120, 90, 40); +// A cave: dark, but textured past the partial tier. +const ImageStats CAVE = stats(50, 45, 40, 25); +// The Oreburgh Gate's dim floor: mean 46, textured within the partial tier. +const ImageStats DIM_FLOOR = stats(46, 46, 46, 8); +// A street at night: dark, but lit windows keep it textured. +const ImageStats NIGHT = stats(40, 40, 55, 30); +const ImageStats FALLING_DARK = stats(60, 60, 60, 10); +const ImageStats DARK = stats(5, 5, 5, 1); +const ImageStats FALLING_WHITE = stats(160, 160, 160, 10); +const ImageStats WHITE = stats(250, 250, 250, 1); + +SceneChange compare_means(const TransitionSample& before, const TransitionSample& after){ + const FloatPixel& a = before.middle.average; + const FloatPixel& b = after.middle.average; + return a.r == b.r && a.g == b.g && a.b == b.b ? SceneChange::SAME : SceneChange::DIFFERENT; +} + +// `stats` from `from_ms` to `to_ms`, a frame every 100 ms. +struct Span{ + int from_ms; + int to_ms; + ImageStats stats; +}; + +// The transitions completed, as describe() puts them, joined by "; "; +// "none" if none. +std::string run_tracker(TransitionTracker& tracker, const std::vector& spans){ + std::string out; + for (const Span& span : spans){ + for (int ms = span.from_ms; ms <= span.to_ms; ms += 100){ + const std::optional done = tracker.push({T0 + Milliseconds(ms), span.stats, {}}); + if (done){ + out += (out.empty() ? "" : "; ") + describe(*done, T0); + } + } + } + return out.empty() ? "none" : out; +} + + +// A synthetic stream of frames, through one game's profile. +struct TrackInput{ + std::string name; + std::vector spans; + const FadeProfile* profile = &BDSP_FADE_PROFILE; + bool compare = true; +}; + +struct TrackExpectation{ + // The transitions completed, as run_tracker() puts them. + std::string transitions; + // What judge_warp() makes of the tracker's current() at the end; empty + // for none. + std::string warp = ""; +}; + +struct TrackCase{ + TrackInput input; + TrackExpectation expectation; +}; + +class Test_TransitionTracker : public UnitTest{ +public: + explicit Test_TransitionTracker(TrackCase test_case) + : UnitTest("Pokemon::Transitions - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const TrackInput& input = m_case.input; + TransitionTracker tracker(*input.profile, input.compare ? compare_means : TransitionTracker::CompareScenes()); + const std::string got = run_tracker(tracker, input.spans); + if (got != m_case.expectation.transitions){ + return std::format("transitions: expected \"{}\", got \"{}\"", m_case.expectation.transitions, got); + } + const std::optional current = tracker.current(); + const InterruptKnobs knobs{.min_fade_hold = 200ms}; + const std::string warp = current ? warp_judgement_name(judge_warp(*current, knobs).judgement) : ""; + if (warp != m_case.expectation.warp){ + return std::format("warp: expected \"{}\", got \"{}\"", m_case.expectation.warp, warp); + } + return true; + } + +private: + TrackCase m_case; +}; + + +UnitTestResult test_timeout(){ + TransitionTracker tracker(BDSP_FADE_PROFILE, compare_means); + const std::string got = run_tracker(tracker, {{0, 100, ROUTE}, {200, 8200, DARK}}); + if (got != "none" || tracker.phase() != TransitionPhase::HOLD){ + return "a screen that stays dark completes no transition and stays in its hold"; + } + if (tracker.timed_out(T0 + 8200ms) || !tracker.timed_out(T0 + 8300ms)){ + return "a transition times out max_hold after it started, not before"; + } + const std::string current = describe(*tracker.current(), T0); + if (current != "black fade +200 ms, peak +200 ms, rise unseen, in progress"){ + return "current(): " + current; + } + tracker.reset(); + if (tracker.phase() != TransitionPhase::SCENE || tracker.current() || tracker.timed_out(T0 + 9000ms)){ + return "reset() did not clear the tracker"; + } + return true; +} + +UnitTestResult test_sample_of_frame(){ + ImageRGB32 image(40, 40); + image.fill(0xff000000); + const TransitionSample sample = transition_sample(VideoSnapshot(std::move(image), T0)); + TransitionTracker tracker(BDSP_FADE_PROFILE); + tracker.push(sample); + if (sample.time != T0 || tracker.phase() != TransitionPhase::HOLD){ + return "a black frame's sample is not a hold at its timestamp"; + } + return transition_sample(VideoSnapshot()).middle.count == 0 + ? UnitTestResult(true) + : UnitTestResult("an empty frame has stats"); +} + + +// Captured frames: CommandLineTests//Transitions// holds +// frames named by their time in ms ("0.png", "250.png"), and expected.txt +// with the transitions run_tracker() should report (no scene comparison). +struct CapturedInput{ + std::string game; + const FadeProfile* profile; +}; + +// Each case folder's expected.txt holds its expectation. +struct CapturedExpectation{ +}; + +struct CapturedCase{ + CapturedInput input; + CapturedExpectation expectation; +}; + +std::string track_captured_case(const Filesystem::Path& folder, const FadeProfile& profile){ + std::vector> frames; + for (const Filesystem::Path& file : Filesystem::list_directory(folder)){ + if (file.extension().string() == ".png"){ + frames.emplace_back(std::stoi(file.stem().string()), file); + } + } + std::sort(frames.begin(), frames.end(), [](const auto& a, const auto& b){ + return a.first < b.first; + }); + TransitionTracker tracker(profile); + std::string out; + for (const auto& frame : frames){ + VideoSnapshot snapshot(ImageRGB32(frame.second.string()), T0 + Milliseconds(frame.first)); + const std::optional done = tracker.push(transition_sample(snapshot)); + if (done){ + out += (out.empty() ? "" : "; ") + describe(*done, T0); + } + } + return out.empty() ? "none" : out; +} + +class Test_CapturedTransitions : public UnitTest{ +public: + explicit Test_CapturedTransitions(CapturedCase test_case) + : UnitTest("Pokemon::Transitions - captured frames: " + test_case.input.game) + , m_input(std::move(test_case.input)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const Filesystem::Path root(UNIT_TEST_RESOURCE_PATH() + m_input.game + "/Transitions/"); + if (!Filesystem::is_directory(root)){ + return UnitTestResult(UnitTestResult::SKIPPED, "no captured transitions at " + root.string()); + } + for (const Filesystem::Path& folder : Filesystem::list_directory(root)){ + if (!Filesystem::is_directory(folder)){ + continue; + } + std::string expected = file_to_string((folder / "expected.txt").string()); + expected.erase(expected.find_last_not_of("\r\n") + 1); + const std::string got = track_captured_case(folder, *m_input.profile); + if (got != expected){ + return std::format("{}: expected \"{}\", got \"{}\"", folder.filename().string(), expected, got); + } + } + return true; + } + +private: + CapturedInput m_input; +}; + + +struct TransitionsInput{ + std::string name; + UnitTestResult (*body)(); +}; + +// The body checks its own expectations. +struct TransitionsExpectation{ +}; + +struct TransitionsCase{ + TransitionsInput input; + TransitionsExpectation expectation; +}; + +class Test_Transitions : public UnitTest{ +public: + explicit Test_Transitions(TransitionsCase test_case) + : UnitTest("Pokemon::Transitions - " + test_case.input.name) + , m_input(std::move(test_case.input)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_input.body(); + } + +private: + TransitionsInput m_input; +}; + +} // namespace + + +const TrackCase TRACK_CASES[] = { + { + .input = {"a door: falls, holds, rises onto another scene", + {{0, 100, ROUTE}, {200, 200, FALLING_DARK}, {300, 700, DARK}, {800, 800, FALLING_DARK}, {900, 1000, HOUSE}}}, + .expectation = {"black fade +200 ms, peak +300 ms, rise +800 ms, end +900 ms, other scene", "warped"}, + }, + { + .input = {"a missed short fade: falling, then another scene", + {{0, 100, ROUTE}, {200, 200, FALLING_DARK}, {300, 400, HOUSE}}}, + .expectation = {"black fade +200 ms, peak unseen, rise unseen, end +300 ms, other scene", "warped"}, + }, + { + .input = {"a missed fade is not reported with no scene comparison", + {{0, 100, ROUTE}, {200, 200, FALLING_DARK}, {300, 400, HOUSE}}, &BDSP_FADE_PROFILE, false}, + .expectation = {"none"}, + }, + { + .input = {"a dip back onto the same scene is no transition", + {{0, 100, ROUTE}, {200, 300, FALLING_DARK}, {400, 500, ROUTE}}}, + .expectation = {"none"}, + }, + { + .input = {"a one-frame black onto the same scene is too short", + {{0, 100, ROUTE}, {200, 200, DARK}, {300, 400, ROUTE}}}, + .expectation = {"black fade +200 ms, peak +200 ms, rise +300 ms, end +300 ms, same scene", "same scene after the fade"}, + }, + { + .input = {"a one-frame black, scene unknown, is too short", + {{0, 100, ROUTE}, {200, 200, DARK}, {300, 400, ROUTE}}, &BDSP_FADE_PROFILE, false}, + .expectation = {"black fade +200 ms, peak +200 ms, rise +300 ms, end +300 ms, scene unknown", "fade too short"}, + }, + { + .input = {"an encounter's flash: a short white, back on the scene", + {{0, 100, ROUTE}, {200, 200, WHITE}, {300, 400, ROUTE}}}, + .expectation = {"flash +200 ms, peak +200 ms, rise +300 ms, end +300 ms, same scene", "an encounter's flash"}, + }, + { + .input = {"a cave exit: a long white onto another scene", + {{0, 100, CAVE}, {200, 200, FALLING_WHITE}, {300, 800, WHITE}, {900, 900, FALLING_WHITE}, {1000, 1100, ROUTE}}}, + .expectation = {"white fade +200 ms, peak +300 ms, rise +900 ms, end +1000 ms, other scene", "warped"}, + }, + { + .input = {"a white between a flash and a fade, scene unknown, is unsure", + {{0, 100, ROUTE}, {200, 400, WHITE}, {500, 600, ROUTE}}, &BDSP_FADE_PROFILE, false}, + .expectation = {"white, flash or fade +200 ms, peak +200 ms, rise +500 ms, end +500 ms, scene unknown", "a white, flash or fade"}, + }, + { + .input = {"a short white onto another scene may be the battle: unsure", + {{0, 100, ROUTE}, {200, 200, WHITE}, {300, 400, HOUSE}}}, + .expectation = {"white, flash or fade +200 ms, peak +200 ms, rise +300 ms, end +300 ms, other scene", "a white, flash or fade"}, + }, + { + .input = {"FRLG has no white fade: a long white is a flash", + {{0, 100, CAVE}, {300, 800, WHITE}, {1000, 1100, ROUTE}}, &FRLG_FADE_PROFILE}, + .expectation = {"flash +300 ms, peak +300 ms, rise +1000 ms, end +1000 ms, other scene", "an encounter's flash"}, + }, + { + .input = {"the Oreburgh Gate's dim floor is no fade, a door from it is", + {{0, 100, ROUTE}, {200, 3000, DIM_FLOOR}, {3100, 3400, DARK}, {3500, 3600, HOUSE}}}, + .expectation = {"black fade +3100 ms, peak +3100 ms, rise +3500 ms, end +3500 ms, other scene", "warped"}, + }, + { + .input = {"a street at night is no fade", {{0, 5000, NIGHT}}}, + .expectation = {"none"}, + }, + { + .input = {"a cave mouth's fade rises into a dim cave", + {{0, 100, ROUTE}, {200, 500, DARK}, {600, 2500, DIM_FLOOR}}}, + .expectation = {"black fade +200 ms, peak +200 ms, rise +600 ms, end +1700 ms, other scene", "warped"}, + }, + { + .input = {"a fade in progress is still showing", + {{0, 100, ROUTE}, {200, 200, FALLING_DARK}, {300, 600, DARK}}}, + .expectation = {"none", "fade still showing"}, + }, +}; + +const TransitionsCase TRANSITIONS_CASES[] = { + { + .input = {"a screen that stays dark times out", test_timeout}, + .expectation = {}, + }, + { + .input = {"a video frame's sample", test_sample_of_frame}, + .expectation = {}, + }, +}; + +const CapturedCase CAPTURED_CASES[] = { + { + .input = {"PokemonBDSP", &BDSP_FADE_PROFILE}, + .expectation = {}, + }, + { + .input = {"PokemonFRLG", &FRLG_FADE_PROFILE}, + .expectation = {}, + }, +}; + +void add_tests_Transitions(UnitTestDatabase& database){ + for (const auto& item : TRACK_CASES){ + database.add(item); + } + for (const auto& item : TRANSITIONS_CASES){ + database.add(item); + } + for (const auto& item : CAPTURED_CASES){ + database.add(item); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 69e99c18a7..8fa570314d 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1498,6 +1498,14 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h Source/Pokemon/AutoStory/Pokemon_AutoStoryStats.h Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h + Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp + Source/Pokemon/AutoStory/Pokemon_Interrupts.h + Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp + Source/Pokemon/AutoStory/Pokemon_SceneJudges.h + Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp + Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h + Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp Source/Pokemon/AutoStory/Pokemon_StoryEvents.h Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp @@ -1517,6 +1525,9 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp Source/Pokemon/AutoStory/Pokemon_TilePose.cpp Source/Pokemon/AutoStory/Pokemon_TilePose.h + Source/Pokemon/AutoStory/Pokemon_Transitions.cpp + Source/Pokemon/AutoStory/Pokemon_Transitions.h + Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp Source/Pokemon/Pokemon_AdvRng.cpp Source/Pokemon/Pokemon_AdvRng.h Source/Pokemon/Pokemon_BdspRng.cpp From 0a1ab58aeff94295f0b28ebd96fb183d650adca2 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 18:35:31 -0800 Subject: [PATCH 32/64] FRLG maps: adopt PokemonSimulation e52be04; spin, hole and button glyphs The FRLG map resource lock moves to PokemonSimulation e52be04 (dayfine/PokemonSimulation#83): all 152 maps regenerated, every pret warp and connection linked, elevation grids back on 14 water maps, Vermilion Gym's beams an overlay. Arduino still reads runtime/, the effective maps. The map glyph table gains the tile legend's u d l r o H B (spin tiles, the spin stop, fall holes and Strength switches), each a TileKind of its own; no loaded map uses them yet. MAP_NAMES gains Route 8, the east-west Underground Path and Route 7 to Celadon City for 00.30. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/Navigation/Pokemon_MapData.cpp | 7 +++++ .../Pokemon/Navigation/Pokemon_MapData.h | 7 +++++ .../Navigation/Pokemon_MapData_Tests.cpp | 27 ++++++++++++++++++- .../Overworld/PokemonFRLG_OverworldMaps.cpp | 8 ++++++ devtools/maps/map-resources.lock.json | 4 +-- 5 files changed, 50 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp index 087680cb09..1e0b488e6a 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp @@ -36,6 +36,13 @@ constexpr std::pair GLYPHS[] = { {'2', TileKind::CLOSED_SOUTH}, {'4', TileKind::CLOSED_WEST}, {'6', TileKind::CLOSED_EAST}, + {'u', TileKind::SPIN_NORTH}, + {'d', TileKind::SPIN_SOUTH}, + {'l', TileKind::SPIN_WEST}, + {'r', TileKind::SPIN_EAST}, + {'o', TileKind::STOP_SPIN}, + {'H', TileKind::FALL_HOLE}, + {'B', TileKind::STRENGTH_BUTTON}, }; constexpr std::pair WARP_ENTRIES[] = { diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h index a5adcea1b9..bb860467c0 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h @@ -69,6 +69,13 @@ enum class TileKind : uint8_t{ CLOSED_SOUTH, // '2' not entered from it, nor left through it (the CLOSED_WEST, // '4' number pad's arrows) CLOSED_EAST, // '6' + SPIN_NORTH, // 'u' open; stepping on it slides the player north + SPIN_SOUTH, // 'd' (Rocket Hideout and Viridian Gym spin tiles) + SPIN_WEST, // 'l' + SPIN_EAST, // 'r' + STOP_SPIN, // 'o' open; where a spin's slide stops + FALL_HOLE, // 'H' open; a hole that drops the player a floor + STRENGTH_BUTTON,// 'B' open; Victory Road's switch for a boulder }; // The tile a glyph stands for, or nothing if it isn't one. std::optional tile_from_glyph(char glyph); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp index 554ec84c3e..e745d28bd8 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp @@ -181,7 +181,7 @@ UnitTestResult test_lists_may_be_left_out(){ } UnitTestResult test_glyphs_round_trip(){ - for (char glyph : std::string("#.~wv^<>DS 8246")){ + for (char glyph : std::string("#.~wv^<>DS 8246udlroHB")){ const std::optional tile = tile_from_glyph(glyph); if (!tile || glyph_of(*tile) != glyph){ return std::string("Glyph '") + glyph + "' does not round-trip."; @@ -193,6 +193,27 @@ UnitTestResult test_glyphs_round_trip(){ return true; } +// PokemonSimulation's tile-legend.json glyphs for forced movement, holes and +// boulder switches, in a map's rows. +UnitTestResult test_spin_hole_and_button_glyphs_parse(){ + const std::string json = R"({ + "name": "SpinRoom", + "source": {"decomp_file": "f", "revision": "r", "date": "d"}, + "tiles": ["udlroHB"] +})"; + const MapData map = parse_map(parse_json(json), "SpinRoom.json"); + constexpr TileKind EXPECTED[] = { + TileKind::SPIN_NORTH, TileKind::SPIN_SOUTH, TileKind::SPIN_WEST, TileKind::SPIN_EAST, + TileKind::STOP_SPIN, TileKind::FALL_HOLE, TileKind::STRENGTH_BUTTON, + }; + for (int x = 0; x < (int)std::size(EXPECTED); x++){ + if (map.tiles.at({x, 0}) != EXPECTED[x]){ + return std::format("Tile ({}, 0) read '{}'.", x, glyph_of(map.tiles.at({x, 0}))); + } + } + return true; +} + struct BadMap{ const char* name; std::string json; @@ -484,6 +505,10 @@ const MapDataTestCase MAP_DATA_CASES[] = { .input = {.name = "glyphs round-trip", .test = test_glyphs_round_trip}, .expectation = {.description = "converts between tile characters and enum kinds"}, }, + { + .input = {.name = "spin, hole and button glyphs", .test = test_spin_hole_and_button_glyphs_parse}, + .expectation = {.description = "parses u d l r o H B as the tile legend's spin, stop, hole and switch tiles"}, + }, { .input = {.name = "each error class", .test = test_each_error_class}, .expectation = {.description = "rejects invalid JSON syntax and malformed map schemas"}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp index 35934b78c3..4d83c0db45 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.cpp @@ -83,6 +83,14 @@ const char* const MAP_NAMES[] = { "RockTunnel_B1F", "LavenderTown", "LavenderTown_PokemonCenter_1F", + // West from Lavender: Route 8, the Underground Path under Saffron and + // Route 7 to Celadon City. + "Route8", + "UndergroundPath_EastEntrance", + "UndergroundPath_EastWestTunnel", + "UndergroundPath_WestEntrance", + "Route7", + "CeladonCity", "CeruleanCave_1F", "CeruleanCave_2F", "CeruleanCave_B1F", diff --git a/devtools/maps/map-resources.lock.json b/devtools/maps/map-resources.lock.json index b608cb31ff..1f1e400006 100644 --- a/devtools/maps/map-resources.lock.json +++ b/devtools/maps/map-resources.lock.json @@ -3,9 +3,9 @@ "repository": "dayfine/PokemonSimulation", "games": { "frlg": { - "revision": "6c2f5c85534186cd9d52af4f844b9847cfd0f33a", + "revision": "e52be04ed7bb007c7219c7d2c96963cf053e0000", "manifest_path": "data/maps/runtime-manifest.json", - "manifest_sha256": "ebcb98381d508de0fb7fa256605b22a754cf83b7f054c83dd954fb019420d096" + "manifest_sha256": "1ccdf3c4e5b8abc90f13e80b6dc8fa429c20f641a018e0e11368930f16165d10" } } } From 6aa5a9bc02bc267b29162566a8b981d7cba6cc5a Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 18:58:11 -0800 Subject: [PATCH 33/64] FRLG replay: refresh the Parcel fixture for PokemonSimulation bdca47c The map lock moved to e52be04's regenerated maps, but the copied Parcel replay binding still pinned five of them at 158b007, so StoryReplay failed with "embedded map hash mismatch". PokemonSimulation #85 repins that binding; copy it, update the binding/candidate hashes and fixture revision in pin.json and CI, and move the map lock to the same commit (identical manifest). The regenerated route candidate has the same actions; only its binding hash moves. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .github/workflows/cpp-ci-serial-programs-base.yml | 2 +- .../Programs/AutoStory/ReplayData/binding.json | 12 ++++++------ .../Programs/AutoStory/ReplayData/pin.json | 6 +++--- .../AutoStory/ReplayData/route-candidate.json | 2 +- devtools/maps/map-resources.lock.json | 2 +- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/.github/workflows/cpp-ci-serial-programs-base.yml b/.github/workflows/cpp-ci-serial-programs-base.yml index 1601ddaa9a..48e45d1d1c 100644 --- a/.github/workflows/cpp-ci-serial-programs-base.yml +++ b/.github/workflows/cpp-ci-serial-programs-base.yml @@ -106,7 +106,7 @@ jobs: uses: actions/checkout@v7 with: repository: dayfine/PokemonSimulation - ref: 9cb12c52f5f055299e32c2a7cf43e7103c101e3e + ref: bdca47c5045797be1d2a1f0931ad6a8f15ab3225 path: StoryReplaySource - name: Verify replay preview bytes and independently regenerate its route input diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/ReplayData/binding.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/ReplayData/binding.json index b53d5e1259..067fa631d3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/ReplayData/binding.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/ReplayData/binding.json @@ -5,13 +5,13 @@ "sha256": "8b0c04f2e1507aee0f0927a8d022b8b431036431e95f8893aa7a2383360f8504", "source_revision": "b170b7d2103e887ded825c37fdbdc19fd654fca8" }, - "map_revision": "158b007ecd14efb5776ebdadc530c1a807ef3541", + "map_revision": "e52be04ed7bb007c7219c7d2c96963cf053e0000", "maps": { - "PalletTown_ProfessorOaksLab": "1dedda88f1238eccd6610cbff79c1e5d3cd21b516637b792654746e02b2cdbc8", - "PalletTown": "0dc7446f568097b36a9479954f01afe546cb64c82bb0efa91da0cb66ad950f9f", - "Route1": "78bf43c8bdf7a0c5dcb22880261626abc36d068c0dfbbc242056e12401c44033", - "ViridianCity": "6a671a0a0b06f78f566b89646f6b0f00c91c240a36300dff861f970455f99909", - "ViridianCity_Mart": "1b2b23f8f9a1b1fbe266f12bdac96cdf649d974b057e84bf9cba6befbaa15b3b" + "PalletTown_ProfessorOaksLab": "53d1c2b022cfadd2463fe405a60fb179562b2cc487ab4c5202f63cbc758d5109", + "PalletTown": "92ebe424c07773ba087b8fc8d2b8251876dd3b97b9aea47a1fee8d36abd6ab0c", + "Route1": "26ba91c2ecfdf0af8ccbdca9f21a522b68f93565594386c09af1011485de7781", + "ViridianCity": "c18f797d9fe5edf8fceb86f5e439778b44f78cf4397cd6b566f3ff7246c2d8cb", + "ViridianCity_Mart": "5e14587080521d433626347fa37024eb1ee36b4fe07a164e19e72714b1b755e8" }, "capabilities": { "below_mart_door": {"capability": "frlg-runtime-route/1", "parameters": {}}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/ReplayData/pin.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/ReplayData/pin.json index deeca459f8..1289d24a91 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/ReplayData/pin.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/ReplayData/pin.json @@ -1,12 +1,12 @@ { "format": "pokesim-native-replay-preview/1", "repository": "dayfine/PokemonSimulation", - "revision": "9cb12c52f5f055299e32c2a7cf43e7103c101e3e", + "revision": "bdca47c5045797be1d2a1f0931ad6a8f15ab3225", "status": "preview-unmerged-PR-73", "files": { "binding": { "path": "data/story/parcel-pilot/binding.json", - "sha256": "5de39f53f63a9fd6319b4afd2fa85d0b0c468da7e94161fe4ce22bb939bb846e" + "sha256": "ce91aba96599f443910dc76a985b97a45b8a76bcbbb1c9824cd247a627d946f4" }, "cases": { "path": "data/story/parcel-pilot/cases.json", @@ -18,7 +18,7 @@ } }, "candidate": { - "sha256": "1eeb9d6ba22362ae1854335aa914ed4e3cabad64403628beb430fe8822cca847", + "sha256": "78219878fedc2c531a4b0faabbe215193ebc7e842dee0237ff52d296a6d614ac", "producer": "checkpoint_replay.run actual route actions; expectations are not read" } } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/ReplayData/route-candidate.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/ReplayData/route-candidate.json index c253702c48..2ce8d3ce63 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/ReplayData/route-candidate.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/ReplayData/route-candidate.json @@ -1,6 +1,6 @@ { "format": "pokesim-route-candidate/1", - "binding_sha256": "5de39f53f63a9fd6319b4afd2fa85d0b0c468da7e94161fe4ce22bb939bb846e", + "binding_sha256": "ce91aba96599f443910dc76a985b97a45b8a76bcbbb1c9824cd247a627d946f4", "checkpoint": "00.05", "routes": { "below_mart_door": [ diff --git a/devtools/maps/map-resources.lock.json b/devtools/maps/map-resources.lock.json index 1f1e400006..a446a338aa 100644 --- a/devtools/maps/map-resources.lock.json +++ b/devtools/maps/map-resources.lock.json @@ -3,7 +3,7 @@ "repository": "dayfine/PokemonSimulation", "games": { "frlg": { - "revision": "e52be04ed7bb007c7219c7d2c96963cf053e0000", + "revision": "bdca47c5045797be1d2a1f0931ad6a8f15ab3225", "manifest_path": "data/maps/runtime-manifest.json", "manifest_sha256": "1ccdf3c4e5b8abc90f13e80b6dc8fa429c20f641a018e0e11368930f16165d10" } From 5b974f0c750680a314cc8e2ed536d9293bc3be08 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 20:22:58 -0800 Subject: [PATCH 34/64] AutoStory: story data types in Types/, executor as a data-free interface, spacing Review of #312: - The plain story data types move out of Pokemon_StorySteps.h into Pokemon/AutoStory/Types/ (StoryStepKind, StoryChecks, StoryStep with StoryLeg and StoryItem, StoryCheckpoint). Pokemon_StorySteps.h still includes them, so its users build unchanged; the JSON codec and the run options now include only the types. - StoryStepExecutor is an interface with no data and no protected or private members: begin_attempt(), run() (pure) and holds(). The 15 per-kind virtuals and dispatch_story_step() go: a game dispatches by kind in run(), as the StoryActionTable of the next layer does. The executor's checks level and language go too; nothing read them, and the program passes StoryRunOptions' values to the game's own steps. - Read-only sequence parameters take std::span. - Spacing: header comment blocks, blank lines after includes, around namespaces and between definitions, one statement per line. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon_AuthoredCheckpointJson.cpp | 3 + .../Pokemon_AuthoredCheckpointJson.h | 5 +- .../Pokemon_AuthoredCheckpointJson_Tests.cpp | 36 +++- .../AutoStory/Pokemon_AutoStory_Tests.h | 10 +- .../Pokemon/AutoStory/Pokemon_StoryEvents.cpp | 2 + .../AutoStory/Pokemon_StoryStepJson.cpp | 34 +++- .../Pokemon/AutoStory/Pokemon_StoryStepJson.h | 24 ++- .../AutoStory/Pokemon_StoryStepJson_Tests.cpp | 67 ++++++- .../Pokemon/AutoStory/Pokemon_StorySteps.cpp | 133 ------------- .../Pokemon/AutoStory/Pokemon_StorySteps.h | 179 ++---------------- .../AutoStory/Pokemon_StorySteps_Tests.cpp | 82 ++++---- .../Pokemon/AutoStory/Pokemon_StoryVariant.h | 1 + .../AutoStory/Types/Pokemon_StoryCheckpoint.h | 37 ++++ .../AutoStory/Types/Pokemon_StoryChecks.cpp | 26 +++ .../AutoStory/Types/Pokemon_StoryChecks.h | 33 ++++ .../AutoStory/Types/Pokemon_StoryStep.h | 87 +++++++++ .../AutoStory/Types/Pokemon_StoryStepKind.cpp | 52 +++++ .../AutoStory/Types/Pokemon_StoryStepKind.h | 43 +++++ .../Pokemon/Options/Pokemon_StoryRunOptions.h | 15 +- SerialPrograms/cmake/SourceFiles.cmake | 6 + 20 files changed, 509 insertions(+), 366 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.cpp index 699ece6df1..63cce48b7a 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.cpp @@ -1,5 +1,7 @@ /* Shared Authored Checkpoint JSON + * * From: https://github.com/PokemonAutomation/ + * */ #include @@ -63,5 +65,6 @@ AuthoredCheckpoint load_authored_checkpoint( } + } // namespace Pokemon } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.h index 1b1be213dd..5bcbc181a2 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.h @@ -1,5 +1,7 @@ /* Shared Authored Checkpoint JSON + * * From: https://github.com/PokemonAutomation/ + * */ #ifndef PokemonAutomation_AuthoredCheckpointJson_H @@ -11,7 +13,7 @@ #include #include #include "Common/Cpp/Json/JsonObject.h" -#include "Pokemon_StorySteps.h" +#include "Types/Pokemon_StoryCheckpoint.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -47,6 +49,7 @@ AuthoredCheckpoint load_authored_checkpoint( ); + } // namespace Pokemon } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson_Tests.cpp index 7aba0e12f4..d01a4fe633 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson_Tests.cpp @@ -1,8 +1,12 @@ /* Shared Authored Checkpoint JSON Tests + * * From: https://github.com/PokemonAutomation/ + * */ #include +#include +#include #include #include "Common/Cpp/Exceptions.h" #include "Pokemon_AuthoredCheckpointJson.h" @@ -13,13 +17,21 @@ namespace PokemonAutomation{ namespace Pokemon{ + + namespace{ + // Documents intentionally contain no game headers or native bookkeeping. const std::string FRLG = R"({"format":"pokesim-authored-checkpoint/1","game":"frlg","checkpoint":{"id":"00.05","title":"Parcel","events":[{"id":"first","kind":"route"},{"id":"second","kind":"scene"}]},"execution":{"menu":"before_pokedex"}})"; const std::string BDSP = R"({"format":"pokesim-authored-checkpoint/1","game":"bdsp","checkpoint":{"id":"01.03","title":"Mine","events":[{"id":"roark","kind":"talk"}]},"execution":{"on_failure":"reload_and_retry","saves_in":"Oreburgh City"}})"; -enum class Failure{ NONE, PARSE, MISSING_RESOURCE }; +// How a case fails, if it does. +enum class Failure{ + NONE, + PARSE, + MISSING_RESOURCE, +}; struct AuthoredInput{ std::string name; @@ -60,6 +72,9 @@ const AuthoredCase CASES[] = { .checkpoint = "x", .execution = R"({"zero":0,"false":false,"null":null})", .events = {}}}, }; + +// "" when `actual` is what `test` expects and survives a write and a +// read, else what was expected and what was read. std::string check_loaded(const AuthoredCheckpoint& actual, const AuthoredCase& test){ if (test.expectation.failure != Failure::NONE){ return "Expected rejection, read accepted authored checkpoint."; @@ -85,6 +100,7 @@ std::string check_loaded(const AuthoredCheckpoint& actual, const AuthoredCase& t return ""; } +// "" when `test` reads or fails as expected. std::string check_case(const AuthoredCase& test){ try{ const std::vector> files = {{"plan", test.input.json}}; @@ -99,34 +115,49 @@ std::string check_case(const AuthoredCase& test){ } } + #ifndef PA_STORY_DATA_STANDALONE + class AuthoredJsonTest : public UnitTest{ public: explicit AuthoredJsonTest(AuthoredCase test) - : UnitTest("Pokemon::AuthoredCheckpointJson - " + test.input.name), m_case(std::move(test)){} + : UnitTest("Pokemon::AuthoredCheckpointJson - " + test.input.name) + , m_case(std::move(test)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ const std::string error = check_case(m_case); return error.empty() ? UnitTestResult(true) : UnitTestResult(error); } + private: AuthoredCase m_case; }; + #endif + } // namespace + #ifndef PA_STORY_DATA_STANDALONE + void add_tests_AuthoredCheckpointJson(UnitTestDatabase& database){ for (const AuthoredCase& test : CASES){ database.add(test); } } + #endif + + } // namespace Pokemon } // namespace PokemonAutomation + #ifdef PA_STORY_DATA_STANDALONE + int main(){ int failed = 0; for (const auto& test : PokemonAutomation::Pokemon::CASES){ @@ -136,4 +167,5 @@ int main(){ } return failed != 0; } + #endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 5d0bbe1172..0efa649a7c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -21,15 +21,13 @@ void add_tests_StoryEvents(UnitTestDatabase& database); void add_tests_StorySegments(UnitTestDatabase& database); // Registers unit tests for high-level story step dispatching and table conversion. void add_tests_StorySteps(UnitTestDatabase& database); - - - -// Lossless shared story-data wire contract. +// Registers unit tests for the lossless shared story-data wire contract. void add_tests_StoryStepJson(UnitTestDatabase& database); - -// Shared authored envelope, game identity and embedded-resource loading. +// Registers unit tests for the shared authored envelope, game identity and embedded-resource loading. void add_tests_AuthoredCheckpointJson(UnitTestDatabase& database); + + } // namespace Pokemon } // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp index ad22d7a6a7..35c61a688c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp @@ -68,11 +68,13 @@ Outcome outcome_ok(Pose pose){ outcome.pose = std::move(pose); return outcome; } + Outcome outcome_unchanged(){ Outcome outcome; outcome.changed_nothing = true; return outcome; } + Outcome outcome_failed(std::string failure, std::string detail){ Outcome outcome; outcome.failure = std::move(failure); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp index 3ee2f51f6d..78427f9667 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp @@ -1,19 +1,31 @@ /* Story Step JSON + * * From: https://github.com/PokemonAutomation/ + * */ + #include #include #include #include +#include #include +#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Json/JsonArray.h" #include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Pokemon_StoryStepJson.h" + namespace PokemonAutomation{ namespace Pokemon{ + + namespace{ + + +// The wire names of the step kinds. constexpr std::array, 15> KINDS{{ {StoryStepKind::NEW_GAME, "new_game"}, {StoryStepKind::OPTIONS, "options"}, @@ -31,6 +43,8 @@ constexpr std::array, 15> KINDS{{ {StoryStepKind::READY, "ready"}, {StoryStepKind::GAME, "game_action"}, }}; + +// The wire names of the pose certainties. constexpr std::array, 5> CERTAINTIES{{ {PoseCertainty::TILE, "tile"}, {PoseCertainty::COLUMN, "column"}, @@ -38,6 +52,8 @@ constexpr std::array, 5> CERTAINTIES{ {PoseCertainty::SET, "set"}, {PoseCertainty::UNKNOWN, "unknown"}, }}; + +// The wire names of the directions. constexpr std::array, 4> DIRECTIONS{{ {Direction::NORTH, "north"}, {Direction::EAST, "east"}, @@ -45,6 +61,8 @@ constexpr std::array, 4> DIRECTIONS{{ {Direction::WEST, "west"}, }}; + +// `value` as an object with no field outside `keys`. const JsonObject& fields(const JsonValue& value, std::initializer_list keys, std::string_view source){ const JsonObject& object = value.to_object_throw(std::string(source)); for (const auto& [key, unused] : object){ @@ -102,7 +120,7 @@ JsonValue count_json(size_t value){ return (uint64_t)value; } -JsonArray strings_json(const std::vector& strings){ +JsonArray strings_json(std::span strings){ JsonArray result; for (const std::string& value : strings){ result.push_back(value); @@ -118,7 +136,7 @@ std::vector read_strings(const JsonValue& value, std::string_view s return result; } -JsonArray legs_json(const std::vector& legs){ +JsonArray legs_json(std::span legs){ JsonArray result; for (const StoryLeg& leg : legs){ JsonObject item; @@ -139,7 +157,7 @@ std::vector read_legs(const JsonValue& value, std::string_view source) return result; } -JsonArray items_json(const std::vector& items){ +JsonArray items_json(std::span items){ JsonArray result; for (const StoryItem& item : items){ JsonObject row; @@ -158,6 +176,8 @@ std::vector read_items(const JsonValue& value, std::string_view sourc } return result; } + +// `result` with the step's yes/no and count fields read from `root`. StoryStep read_step_options(StoryStep result, const JsonObject& root, std::string_view source){ if (const JsonValue* field = root.get_value("fight_wild")){ result.fight_wild = field->to_boolean_throw(); @@ -174,8 +194,10 @@ StoryStep read_step_options(StoryStep result, const JsonObject& root, std::strin return result; } + } // namespace + JsonValue story_pose_json(const Pose& pose){ JsonObject result; result["map"] = pose.map; @@ -191,7 +213,8 @@ JsonValue story_pose_json(const Pose& pose){ JsonArray positions; for (const TilePos& tile : tiles->tiles){ JsonArray pair; - pair.push_back(tile.x); pair.push_back(tile.y); + pair.push_back(tile.x); + pair.push_back(tile.y); positions.push_back(std::move(pair)); } where["tiles"] = std::move(positions); @@ -351,5 +374,8 @@ StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view s } return result; } + + + } // namespace Pokemon } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.h index d58fd9828c..b50caadc58 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.h @@ -1,26 +1,48 @@ /* Story Step JSON + * * From: https://github.com/PokemonAutomation/ + * + * The shared JSON wire form of the story data types (Types/): poses, + * steps and checkpoints, read strictly and written losslessly. + * */ + #ifndef PokemonAutomation_StoryStepJson_H #define PokemonAutomation_StoryStepJson_H + #include #include "Common/Cpp/Json/JsonValue.h" -#include "Pokemon_StorySteps.h" +#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "Types/Pokemon_StoryCheckpoint.h" +#include "Types/Pokemon_StoryStep.h" + namespace PokemonAutomation{ namespace Pokemon{ + + // Lossless tile-game pose data, including uncertainty and absent position/facing. // An unsupported Position subtype fails instead of being converted to unknown. JsonValue story_pose_json(const Pose& pose); + // Read a tile-game pose; malformed fields and unsupported position tags fail. Pose read_story_pose(const JsonValue& value, std::string_view source); + + // Encode every shared step field. This does not bind or execute an action. JsonValue story_step_json(const StoryStep& step); + // Read the shared step record; unknown fields/kinds and invalid values fail. StoryStep read_story_step(const JsonValue& value, std::string_view source); + + // Encode the common checkpoint; game adapters supply the shared policy/state envelope. JsonValue story_checkpoint_json(const StoryCheckpoint& checkpoint); + // Read only the common checkpoint record, retaining ordered steps and start belief. StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view source); + + + } // namespace Pokemon } // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp index 021b18f508..269b9f4412 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp @@ -1,7 +1,16 @@ /* Story Step JSON Tests + * * From: https://github.com/PokemonAutomation/ + * + * Each case reads a record from JSON and writes it back: the canonical + * form, or a rejection. Built standalone (PA_STORY_DATA_STANDALONE), it + * also checks the shared case file the Python reader checks. + * */ + #include +#include +#include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Json/JsonObject.h" #include "Common/Cpp/Json/JsonArray.h" @@ -9,23 +18,39 @@ #ifndef PA_STORY_DATA_STANDALONE #include "Pokemon_AutoStory_Tests.h" #endif + namespace PokemonAutomation{ namespace Pokemon{ + + namespace{ -enum class Record{ POSE, STEP, CHECKPOINT }; + + +// Which record a case reads. +enum class Record{ + POSE, + STEP, + CHECKPOINT, +}; + +// A record to read, and which kind it is. struct WireInput{ std::string_view name; Record record = Record::STEP; std::string_view json; }; + +// What reading it gives: the canonical record, or a rejection. struct WireExpectation{ std::string_view canonical = {}; bool rejected = false; }; + struct WireCase{ WireInput input; WireExpectation expectation; }; + const WireCase CASES[] = { {.input = {.name = "default fields", .json = R"({"id":"talk","kind":"talk"})"}, .expectation = {.canonical = R"({"id":"talk","kind":"talk"})"}}, {.input = {.name = "all shared fields", .json = R"({"id":"all","kind":"game_action","why":"source reason","direction":"west","legs":[{"direction":"south","tiles":0}],"fight_wild":true,"yes":false,"may_lose":true,"battles":3,"items":[{"item":"potion","quantity":0}],"variant":"profile","skip_if":["flag"],"target":{"map":"A","certainty":"unknown","where":{"kind":"unknown"}},"declared_after":{"map":"B","certainty":"set","where":{"kind":"tiles","tiles":[[0,0],[1,0]],"facing":"east"}}})"}, .expectation = {.canonical = R"({"id":"all","kind":"game_action","why":"source reason","direction":"west","legs":[{"direction":"south","tiles":0}],"fight_wild":true,"yes":false,"may_lose":true,"battles":3,"items":[{"item":"potion","quantity":0}],"variant":"profile","skip_if":["flag"],"target":{"map":"A","certainty":"unknown","where":{"kind":"unknown"}},"declared_after":{"map":"B","certainty":"set","where":{"kind":"tiles","tiles":[[0,0],[1,0]],"facing":"east"}}})"}}, @@ -42,16 +67,22 @@ const WireCase CASES[] = { {.input = {.name = "duplicate events", .record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[{"id":"a","kind":"talk"},{"id":"a","kind":"talk"}]})"}, .expectation = {.rejected = true}}, }; + +// `input` read and written back. JsonValue round_trip(const WireInput& input){ const JsonValue value = parse_json(std::string(input.json)); switch (input.record){ - case Record::POSE: return story_pose_json(read_story_pose(value, input.name)); - case Record::STEP: return story_step_json(read_story_step(value, input.name)); - case Record::CHECKPOINT: return story_checkpoint_json(read_story_checkpoint(value, input.name)); + case Record::POSE: + return story_pose_json(read_story_pose(value, input.name)); + case Record::STEP: + return story_step_json(read_story_step(value, input.name)); + case Record::CHECKPOINT: + return story_checkpoint_json(read_story_checkpoint(value, input.name)); } throw ParseException("Unknown test record."); } +// "" when `test` reads as expected, else what was expected and what was read. std::string check_case(const WireCase& test){ try{ const JsonValue actual = round_trip(test.input); @@ -67,7 +98,11 @@ std::string check_case(const WireCase& test){ } return ""; } + + #ifdef PA_STORY_DATA_STANDALONE + +// A shared case file's record kind. Record record_kind(const std::string& name){ if (name == "pose"){ return Record::POSE; @@ -81,6 +116,7 @@ Record record_kind(const std::string& name){ throw ParseException("Unsupported shared case record kind."); } +// Checks every case of the shared file `filename`; nonzero if any failed. int check_shared_file(const std::string& filename){ const JsonValue document = load_json_file(filename); const JsonObject& root = document.to_object_throw(filename); @@ -109,32 +145,52 @@ int check_shared_file(const std::string& filename){ std::cout << "Checked " << root.get_array_throw("cases").size() << " shared story records.\n"; return failed != 0; } + #endif + #ifndef PA_STORY_DATA_STANDALONE + class StoryJsonTest : public UnitTest{ public: explicit StoryJsonTest(WireCase test) - : UnitTest("Pokemon::StoryStepJson - " + std::string(test.input.name)), m_case(test){} + : UnitTest("Pokemon::StoryStepJson - " + std::string(test.input.name)) + , m_case(test) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ const std::string error = check_case(m_case); return error.empty() ? UnitTestResult(true) : UnitTestResult(error); } + private: WireCase m_case; }; + #endif + + } // namespace + + #ifndef PA_STORY_DATA_STANDALONE + void add_tests_StoryStepJson(UnitTestDatabase& database){ for (const WireCase& test : CASES){ database.add(test); } } + #endif + + + } // namespace Pokemon } // namespace PokemonAutomation + + #ifdef PA_STORY_DATA_STANDALONE + int main(int argc, char** argv){ if (argc == 2){ return PokemonAutomation::Pokemon::check_shared_file(argv[1]); @@ -147,4 +203,5 @@ int main(int argc, char** argv){ } return failed != 0; } + #endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp index 3004ba6013..5309b3e496 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp @@ -14,61 +14,10 @@ namespace PokemonAutomation{ namespace Pokemon{ -const char* story_step_kind_name(StoryStepKind kind){ - switch (kind){ - case StoryStepKind::NEW_GAME: - return "NEW_GAME"; - case StoryStepKind::OPTIONS: - return "OPTIONS"; - case StoryStepKind::ROUTE: - return "ROUTE"; - case StoryStepKind::LEGS: - return "LEGS"; - case StoryStepKind::STEP: - return "STEP"; - case StoryStepKind::TALK: - return "TALK"; - case StoryStepKind::ANSWER: - return "ANSWER"; - case StoryStepKind::MASH: - return "MASH"; - case StoryStepKind::BATTLE: - return "BATTLE"; - case StoryStepKind::TRAIN: - return "TRAIN"; - case StoryStepKind::HEAL: - return "HEAL"; - case StoryStepKind::SHOP: - return "SHOP"; - case StoryStepKind::SAVE: - return "SAVE"; - case StoryStepKind::READY: - return "READY"; - case StoryStepKind::GAME: - return "GAME"; - } - return "?"; -} - - -const char* story_checks_name(StoryChecks checks){ - switch (checks){ - case StoryChecks::THOROUGH: - return "thorough"; - case StoryChecks::FAST: - return "fast"; - } - return "?"; -} - - Outcome unsupported_step(const StoryStep& step){ return outcome_failed("unsupported_step", std::format("{} {}", story_step_kind_name(step.kind), step.name)); } -Outcome StoryStepExecutor::run(RunState& state, const StoryStep& step){ - return dispatch_story_step(*this, state, step); -} void StoryStepExecutor::begin_attempt(const StoryCheckpoint&){} @@ -76,88 +25,6 @@ bool StoryStepExecutor::holds(const std::string& condition, RunState& state){ return state.flags.contains(condition); } -Outcome StoryStepExecutor::new_game(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::options(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::route(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::legs(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::step(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::talk(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::answer(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::mash(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::battle(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::train(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::heal(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::shop(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::save(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::ready(RunState&, const StoryStep& step){ - return unsupported_step(step); -} -Outcome StoryStepExecutor::game(RunState&, const StoryStep& step){ - return unsupported_step(step); -} - -Outcome dispatch_story_step(StoryStepExecutor& executor, RunState& state, const StoryStep& step){ - switch (step.kind){ - case StoryStepKind::NEW_GAME: - return executor.new_game(state, step); - case StoryStepKind::OPTIONS: - return executor.options(state, step); - case StoryStepKind::ROUTE: - return executor.route(state, step); - case StoryStepKind::LEGS: - return executor.legs(state, step); - case StoryStepKind::STEP: - return executor.step(state, step); - case StoryStepKind::TALK: - return executor.talk(state, step); - case StoryStepKind::ANSWER: - return executor.answer(state, step); - case StoryStepKind::MASH: - return executor.mash(state, step); - case StoryStepKind::BATTLE: - return executor.battle(state, step); - case StoryStepKind::TRAIN: - return executor.train(state, step); - case StoryStepKind::HEAL: - return executor.heal(state, step); - case StoryStepKind::SHOP: - return executor.shop(state, step); - case StoryStepKind::SAVE: - return executor.save(state, step); - case StoryStepKind::READY: - return executor.ready(state, step); - case StoryStepKind::GAME: - return executor.game(state, step); - } - return unsupported_step(step); -} - Event story_event(const StoryStep& step, StoryStepExecutor& executor){ Event event; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h index 27aaabad8a..7b76155d63 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h @@ -5,21 +5,22 @@ * One vocabulary of story steps for the tile games (FRLG, BDSP): a route, * a fixed walk, a step onto a trigger, a talk, a YES/NO, a scene, a * battle, the nurse, a shop, a save, and so on. A checkpoint is a list of - * such steps, plain data, so a game's story is a table its unit tests can - * plan without a console. + * such steps, plain data (Types/), so a game's story is a table its unit + * tests can plan without a console. * * build_story_checkpoint() turns a table row into engine events * (Pokemon_StoryEvents.h). Each event's action asks the game's - * StoryStepExecutor to do its step: one virtual per kind, so a game - * implements the kinds it uses, and a step the game has no way of doing - * fails by name instead of doing something else. + * StoryStepExecutor to do its step; a game implements the kinds it uses, + * and a step it has no way of doing fails by name (unsupported_step()) + * instead of doing something else. * * Steps never match dialogue or menu text: they look for screen state (a * dialogue box, an arrow, a fade, a battle menu, colours, positions). The * few reads that need text (item names in a shop or the Bag) take the - * game's language from the executor, and with no reader for it fall back - * to checks that need none (a row's position, digits, a changed screen), - * so a run never fails because its language is not supported. + * game's language from the program's options (StoryRunOptions), and with + * no reader for it fall back to checks that need none (a row's position, + * digits, a changed screen), so a run never fails because its language + * is not supported. * * Poses are the game's own (Pose, with a TilePose for these games): a * checkpoint's start, a scene's end and a route's target are poses, and @@ -31,123 +32,28 @@ #ifndef PokemonAutomation_Pokemon_StorySteps_H #define PokemonAutomation_Pokemon_StorySteps_H -#include #include #include #include #include -#include "CommonFramework/Language.h" #include "Pokemon/Navigation/Pokemon_Grid.h" #include "Pokemon_AutoStoryStats.h" #include "Pokemon_StoryEvents.h" #include "Pokemon_StorySegments.h" #include "Pokemon_TilePose.h" +#include "Types/Pokemon_StoryChecks.h" +#include "Types/Pokemon_StoryCheckpoint.h" +#include "Types/Pokemon_StoryStep.h" +#include "Types/Pokemon_StoryStepKind.h" namespace PokemonAutomation{ namespace Pokemon{ -// Action category classification for individual story steps. -enum class StoryStepKind{ - NEW_GAME, // title screen (no save) to the first room - OPTIONS, // the game's options as the story needs them - ROUTE, // plan and walk to `target` - LEGS, // walk `legs` as given - STEP, // one step `direction`: onto a trigger, into a door - TALK, // A at what the player faces - ANSWER, // text to a YES/NO, then `yes` - MASH, // text until the overworld is back: a scene - BATTLE, // text into a battle, fight it, text to the overworld - TRAIN, // fight `battles` wild battles where the player stands - HEAL, // the nurse, from in front of her or of the Center's door - SHOP, // `items` from a shop - SAVE, // save the game where the player stands - READY, // before a big battle: items, and the nurse at `target` if they can't - GAME, // a step only this game has, named by `variant` -}; -// Returns the readable string representation of a story step kind. -const char* story_step_kind_name(StoryStepKind kind); - -// How much a step reads the screen to confirm what it did. Each game -// decides what its steps check at each level. -enum class StoryChecks{ - // Confirm on screen: purchases, the Bag, status after battles, position. - THOROUGH, - // In a rush: trust counts and timings. - FAST, -}; -// Returns the readable string representation of a story check level. -const char* story_checks_name(StoryChecks checks); - - -// A straight leg of a fixed walk. -struct StoryLeg{ - Direction direction = Direction::NORTH; - int tiles = 0; -}; - -// An item and how many to get. -struct StoryItem{ - std::string item; - size_t quantity = 0; -}; - -// Specification of an atomic story task with actions and postconditions. -struct StoryStep{ - StoryStepKind kind = StoryStepKind::TALK; - std::string name; - std::string why; - - // ROUTE: where to go; with several tiles, any of them. READY: the nurse. - std::optional target; - // STEP - Direction direction = Direction::NORTH; - // LEGS - std::vector legs; - // ROUTE, LEGS: fight wild battles on the way instead of running. - bool fight_wild = false; - // ANSWER - bool yes = true; - // BATTLE: losing goes on (a rival's first battle). - bool may_lose = false; - // TRAIN - size_t battles = 0; - // SHOP - std::vector items; - // How this game does the kind, when it has more than one way: a - // route's plan costs, a door lined up by sight, the Mart lady instead - // of the clerk. Empty is the game's usual way. GAME: the step's name - // in the game's executor. - std::string variant; - - // Skipped when all of these hold (and there is at least one): names - // the game's executor answers (StoryStepExecutor::holds()), run flags - // unless the game reads them off the screen. - std::vector skip_if; - // Preparation for what follows, done once per save: a TEACH, a check, - // a read. Once it has succeeded and changed nothing - // (Outcome::changed_nothing), the attempts after a reload of the same - // save skip it, so a retry goes from the reload straight to the - // battle. One that changed the game (a TM taught) runs again, as the - // reload undid it. Only with build_story_checkpoint()'s PreparedSteps. - bool once_per_save = false; - // Where the step leaves the player, when its action does not say: the - // end of a scene that moves the player. - std::optional pose_after; -}; - -// Milestone row in the story table grouping related steps and starting pose. -struct StoryCheckpoint{ - std::string id; - std::string title; - // Where its starting save leaves the player; none for a new game. - std::optional start; - std::vector steps; -}; - - -// How a game does each kind of step. Every kind fails as unsupported -// unless the game overrides it. +// How a game does its story steps: an interface with no data. run() is the +// game's: it does the step's kind its own way (FRLG and BDSP bind kinds and +// variants to actions in a table), and returns unsupported_step() for a +// kind it has no way of doing. class StoryStepExecutor{ public: virtual ~StoryStepExecutor() = default; @@ -157,61 +63,14 @@ class StoryStepExecutor{ // who can see us again, the row's own settings). Does nothing by default. virtual void begin_attempt(const StoryCheckpoint& data); - // The checks level the program's options chose (StoryRunOptions); - // THOROUGH unless set. Steps read it to decide what to confirm. - StoryChecks checks() const{ - return m_checks; - } - void set_checks(StoryChecks checks){ - m_checks = checks; - } - // The game's language (StoryRunOptions), for the reads that need text; - // English unless set. A game with no reader for it uses language-free - // checks instead. - Language language() const{ - return m_language; - } - void set_language(Language language){ - m_language = language; - } - - // Runs `step`: dispatch_story_step() by default. A game overrides it - // to wrap every step, e.g. to turn a failed console step into a failed - // Outcome. - virtual Outcome run(RunState& state, const StoryStep& step); + // Does `step`, from the run so far. + virtual Outcome run(RunState& state, const StoryStep& step) = 0; // Whether the condition named in a step's skip_if holds: by default, // whether the run has the flag (set by an earlier step's action). virtual bool holds(const std::string& condition, RunState& state); - -protected: - // One per step kind, called by dispatch_story_step(); each fails as - // unsupported unless the game overrides it. - friend Outcome dispatch_story_step(StoryStepExecutor& executor, RunState& state, const StoryStep& step); - virtual Outcome new_game(RunState& state, const StoryStep& step); - virtual Outcome options(RunState& state, const StoryStep& step); - virtual Outcome route(RunState& state, const StoryStep& step); - virtual Outcome legs(RunState& state, const StoryStep& step); - virtual Outcome step(RunState& state, const StoryStep& step); - virtual Outcome talk(RunState& state, const StoryStep& step); - virtual Outcome answer(RunState& state, const StoryStep& step); - virtual Outcome mash(RunState& state, const StoryStep& step); - virtual Outcome battle(RunState& state, const StoryStep& step); - virtual Outcome train(RunState& state, const StoryStep& step); - virtual Outcome heal(RunState& state, const StoryStep& step); - virtual Outcome shop(RunState& state, const StoryStep& step); - virtual Outcome save(RunState& state, const StoryStep& step); - virtual Outcome ready(RunState& state, const StoryStep& step); - virtual Outcome game(RunState& state, const StoryStep& step); - -private: - StoryChecks m_checks = StoryChecks::THOROUGH; - Language m_language = Language::English; }; -// Calls the executor's method for the step's kind. -Outcome dispatch_story_step(StoryStepExecutor& executor, RunState& state, const StoryStep& step); - // "unsupported_step: TRAIN train_in_grass": what an executor without the kind returns. Outcome unsupported_step(const StoryStep& step); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp index e61a1eeb95..a61a345ee2 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -64,41 +65,53 @@ class FakeExecutor : public StoryStepExecutor{ left--; return outcome_failed("blocked", step.name + " was blocked"); } - return StoryStepExecutor::run(state, step); + return run_kind(state, step); } + virtual bool holds(const std::string& condition, RunState& state) override{ return conditions.contains(condition) || StoryStepExecutor::holds(condition, state); } -protected: - virtual Outcome route(RunState&, const StoryStep& step) override{ - return outcome_ok(*step.target); +private: + // The kinds this world has; any other is unsupported. + Outcome run_kind(RunState& state, const StoryStep& step){ + switch (step.kind){ + case StoryStepKind::ROUTE: + return outcome_ok(*step.target); + case StoryStepKind::STEP: + return step_one_tile(state, step); + case StoryStepKind::TALK: + case StoryStepKind::MASH: + return outcome_ok(); + case StoryStepKind::BATTLE: + // The first battle is lost; a step that may lose goes on. + return step.may_lose ? outcome_ok() : outcome_failed("blackout"); + case StoryStepKind::SHOP: + return shop(step); + case StoryStepKind::GAME: + return game(state, step); + default: + return unsupported_step(step); + } } - virtual Outcome step(RunState& state, const StoryStep& step) override{ + + Outcome step_one_tile(RunState& state, const StoryStep& step){ const std::vector tiles = tiles_of(state.pose); if (tiles.size() != 1){ return outcome_failed("no_pose", to_string(state.pose)); } return outcome_ok(tile_pose(state.pose.map, {tiles[0].next(step.direction)}, step.direction)); } - virtual Outcome talk(RunState&, const StoryStep&) override{ - return outcome_ok(); - } - virtual Outcome mash(RunState&, const StoryStep&) override{ - return outcome_ok(); - } - virtual Outcome battle(RunState&, const StoryStep& step) override{ - // The first battle is lost; a step that may lose goes on. - return step.may_lose ? outcome_ok() : outcome_failed("blackout"); - } - virtual Outcome shop(RunState&, const StoryStep& step) override{ + + Outcome shop(const StoryStep& step){ for (const StoryItem& item : step.items){ trace.push_back(" bought " + std::to_string(item.quantity) + " " + item.item); } return outcome_ok(); } + // A game step sets a run flag named for its variant. - virtual Outcome game(RunState& state, const StoryStep& step) override{ + Outcome game(RunState& state, const StoryStep& step){ trace.push_back(" game " + step.variant); state.flags.insert(step.variant); return unchanged.contains(step.name) ? outcome_unchanged() : outcome_ok(); @@ -166,7 +179,7 @@ Run run(const StoryCheckpoint& data, StoryStepExecutor& executor){ return ret; } -std::string joined(const std::vector& lines){ +std::string joined(std::span lines){ std::string text; for (const std::string& line : lines){ text += "\n " + line; @@ -300,7 +313,7 @@ UnitTestResult test_unsupported_and_lost_battles(){ // Runs `tables` as one segment whose saves and reloads go into the // executor's trace and whose log lines go into `lines`. Whatever blocked a // step has gone by the reload. -SegmentReport run_tables(const std::vector& tables, FakeExecutor& executor, std::vector& lines){ +SegmentReport run_tables(std::span tables, FakeExecutor& executor, std::vector& lines){ Segment segment; segment.id = "00"; for (const StoryCheckpoint& data : tables){ @@ -577,32 +590,6 @@ UnitTestResult test_once_per_save_verify(){ } -// The checks level: THOROUGH by default, and what the program sets is -// what a step reads. -UnitTestResult test_checks_level(){ - class CheckingExecutor : public FakeExecutor{ - public: - std::vector seen; - virtual Outcome talk(RunState&, const StoryStep& step) override{ - seen.push_back(step.name + " " + story_checks_name(checks())); - return outcome_ok(); - } - }; - StoryCheckpoint data = lab_checkpoint(); - CheckingExecutor executor; - run(data, executor); - executor.set_checks(StoryChecks::FAST); - executor.set_language(Language::Korean); - run(data, executor); - if (executor.language() != Language::Korean){ - return "Expected the language set on the executor."; - } - if (executor.seen != std::vector{"talk_oak thorough", "talk_oak fast"}){ - return "Expected the talk to read thorough, then fast:" + joined(executor.seen); - } - return true; -} - // Two sections of a story, as BDSP has segments 00 and 01. const std::vector& two_sections(){ static const std::vector rows{ @@ -612,6 +599,7 @@ const std::vector& two_sections(){ }; return rows; } + const StringSelectDatabase& two_sections_database(){ static const StringSelectDatabase database = story_checkpoint_database(two_sections()); return database; @@ -797,10 +785,6 @@ const StoryStepTestCase STORY_STEP_CASES[] = { .input = {.name = "lint", .test = test_lint}, .expectation = {.description = "verifies lint validation rules on story checkpoints"}, }, - { - .input = {.name = "the checks level reaches the steps", .test = test_checks_level}, - .expectation = {.description = "transfers checks granularity option to step execution"}, - }, { .input = {.name = "the run options' defaults", .test = test_run_options}, .expectation = {.description = "validates initial default story run option values"}, diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.h index f136fa147b..79f854bdd6 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.h @@ -30,6 +30,7 @@ struct VariantPair{ std::string_view key; std::string_view value; }; + // `word` split at its first '='; nothing without one or with an empty key. std::optional variant_pair(std::string_view word); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h new file mode 100644 index 0000000000..7071035402 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h @@ -0,0 +1,37 @@ +/* Story Checkpoint + * + * From: https://github.com/PokemonAutomation/ + * + * A checkpoint of a tile game's story table as plain data: where its save + * leaves the player and its steps in order. build_story_checkpoint() + * (Pokemon_StorySteps.h) turns it into engine events. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryCheckpoint_H +#define PokemonAutomation_Pokemon_StoryCheckpoint_H + +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "Pokemon_StoryStep.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Milestone row in the story table grouping related steps and starting pose. +struct StoryCheckpoint{ + std::string id; + std::string title; + // Where its starting save leaves the player; none for a new game. + std::optional start; + std::vector steps; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.cpp new file mode 100644 index 0000000000..1ea9bbb92a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.cpp @@ -0,0 +1,26 @@ +/* Story Checks + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryChecks.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const char* story_checks_name(StoryChecks checks){ + switch (checks){ + case StoryChecks::THOROUGH: + return "thorough"; + case StoryChecks::FAST: + return "fast"; + } + return "?"; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.h new file mode 100644 index 0000000000..3dba180603 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.h @@ -0,0 +1,33 @@ +/* Story Checks + * + * From: https://github.com/PokemonAutomation/ + * + * How much a story step reads the screen to confirm what it did. The + * program's options choose it (StoryRunOptions); each game decides what + * its steps check at each level. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryChecks_H +#define PokemonAutomation_Pokemon_StoryChecks_H + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How much a step reads the screen to confirm what it did. +enum class StoryChecks{ + // Confirm on screen: purchases, the Bag, status after battles, position. + THOROUGH, + // In a rush: trust counts and timings. + FAST, +}; + +// Returns the readable string representation of a story check level. +const char* story_checks_name(StoryChecks checks); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h new file mode 100644 index 0000000000..457725dc05 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h @@ -0,0 +1,87 @@ +/* Story Step + * + * From: https://github.com/PokemonAutomation/ + * + * One step of a tile game's story (FRLG, BDSP) as plain data: its kind + * and the fields that kind reads. A game's executor does it + * (Pokemon_StorySteps.h); the shared JSON reads and writes it + * (Pokemon_StoryStepJson.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStep_H +#define PokemonAutomation_Pokemon_StoryStep_H + +#include +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_StoryEvents.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A straight leg of a fixed walk. +struct StoryLeg{ + Direction direction = Direction::NORTH; + int tiles = 0; +}; + +// An item and how many to get. +struct StoryItem{ + std::string item; + size_t quantity = 0; +}; + +// Specification of an atomic story task with actions and postconditions. +struct StoryStep{ + StoryStepKind kind = StoryStepKind::TALK; + std::string name; + std::string why; + + // ROUTE: where to go; with several tiles, any of them. READY: the nurse. + std::optional target; + // STEP + Direction direction = Direction::NORTH; + // LEGS + std::vector legs; + // ROUTE, LEGS: fight wild battles on the way instead of running. + bool fight_wild = false; + // ANSWER + bool yes = true; + // BATTLE: losing goes on (a rival's first battle). + bool may_lose = false; + // TRAIN + size_t battles = 0; + // SHOP + std::vector items; + // How this game does the kind, when it has more than one way: a + // route's plan costs, a door lined up by sight, the Mart lady instead + // of the clerk. Empty is the game's usual way. GAME: the step's name + // in the game's executor. + std::string variant; + + // Skipped when all of these hold (and there is at least one): names + // the game's executor answers (StoryStepExecutor::holds()), run flags + // unless the game reads them off the screen. + std::vector skip_if; + // Preparation for what follows, done once per save: a TEACH, a check, + // a read. Once it has succeeded and changed nothing + // (Outcome::changed_nothing), the attempts after a reload of the same + // save skip it, so a retry goes from the reload straight to the + // battle. One that changed the game (a TM taught) runs again, as the + // reload undid it. Only with build_story_checkpoint()'s PreparedSteps. + bool once_per_save = false; + // Where the step leaves the player, when its action does not say: the + // end of a scene that moves the player. + std::optional pose_after; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp new file mode 100644 index 0000000000..8491db4f90 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp @@ -0,0 +1,52 @@ +/* Story Step Kind + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_StoryStepKind.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const char* story_step_kind_name(StoryStepKind kind){ + switch (kind){ + case StoryStepKind::NEW_GAME: + return "NEW_GAME"; + case StoryStepKind::OPTIONS: + return "OPTIONS"; + case StoryStepKind::ROUTE: + return "ROUTE"; + case StoryStepKind::LEGS: + return "LEGS"; + case StoryStepKind::STEP: + return "STEP"; + case StoryStepKind::TALK: + return "TALK"; + case StoryStepKind::ANSWER: + return "ANSWER"; + case StoryStepKind::MASH: + return "MASH"; + case StoryStepKind::BATTLE: + return "BATTLE"; + case StoryStepKind::TRAIN: + return "TRAIN"; + case StoryStepKind::HEAL: + return "HEAL"; + case StoryStepKind::SHOP: + return "SHOP"; + case StoryStepKind::SAVE: + return "SAVE"; + case StoryStepKind::READY: + return "READY"; + case StoryStepKind::GAME: + return "GAME"; + } + return "?"; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h new file mode 100644 index 0000000000..a62d40e7d6 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h @@ -0,0 +1,43 @@ +/* Story Step Kind + * + * From: https://github.com/PokemonAutomation/ + * + * The kinds of story step the tile games (FRLG, BDSP) share. A game's + * executor does each kind its own way (Pokemon_StorySteps.h). + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryStepKind_H +#define PokemonAutomation_Pokemon_StoryStepKind_H + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Action category classification for individual story steps. +enum class StoryStepKind{ + NEW_GAME, // title screen (no save) to the first room + OPTIONS, // the game's options as the story needs them + ROUTE, // plan and walk to `target` + LEGS, // walk `legs` as given + STEP, // one step `direction`: onto a trigger, into a door + TALK, // A at what the player faces + ANSWER, // text to a YES/NO, then `yes` + MASH, // text until the overworld is back: a scene + BATTLE, // text into a battle, fight it, text to the overworld + TRAIN, // fight `battles` wild battles where the player stands + HEAL, // the nurse, from in front of her or of the Center's door + SHOP, // `items` from a shop + SAVE, // save the game where the player stands + READY, // before a big battle: items, and the nurse at `target` if they can't + GAME, // a step only this game has, named by `variant` +}; + +// Returns the readable string representation of a story step kind. +const char* story_step_kind_name(StoryStepKind kind); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h index c54482cc52..f362ce875f 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h @@ -4,8 +4,9 @@ * * The options every AutoStory program shows for where to start and end, how * hard to try and how much to check: the same group in each game, read into the shared - * SegmentPolicy (Pokemon/AutoStory/Pokemon_StorySegments.h) and the - * executor's checks level (Pokemon_StorySteps.h). + * SegmentPolicy (Pokemon/AutoStory/Pokemon_StorySegments.h), the checks + * level (Types/Pokemon_StoryChecks.h) and the language the game's steps + * read text in. * */ @@ -21,10 +22,12 @@ #include "Common/Cpp/Options/EnumDropdownOption.h" #include "Common/Cpp/Options/GroupOption.h" #include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Language.h" #include "CommonTools/Options/StringSelectOption.h" #include "Pokemon/AutoStory/Pokemon_AutoStorySelect.h" #include "Pokemon/AutoStory/Pokemon_StorySegments.h" -#include "Pokemon/AutoStory/Pokemon_StorySteps.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryChecks.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -34,10 +37,12 @@ namespace Pokemon{ // segments: "00.09 Pewter Gym: Camper Liam, then Brock". struct StoryCheckpointEntry{ std::string label; + const std::string& name() const{ return label; } }; + // Formats a checkpoint identifier and description into a dropdown label. std::string story_checkpoint_label(const StoryCheckpoint& checkpoint); @@ -94,9 +99,9 @@ class StoryRunOptions : public GroupOption{ // The policy these options set. In-place recoveries are the game's to // set, not the user's. SegmentPolicy policy() const; - // The checks level for the game's story step executor (set_checks()). + // The checks level, for the game's steps to read. StoryChecks checks() const; - // The game's language, for the executor (set_language()). + // The game's language, for the steps that read text. Language language() const; public: diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 69e99c18a7..4630157b77 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1517,6 +1517,12 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp Source/Pokemon/AutoStory/Pokemon_TilePose.cpp Source/Pokemon/AutoStory/Pokemon_TilePose.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryStepKind.h Source/Pokemon/Pokemon_AdvRng.cpp Source/Pokemon/Pokemon_AdvRng.h Source/Pokemon/Pokemon_BdspRng.cpp From 6b908f4c1210ce6b76183ee9aa4cfb161c092349 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 20:25:55 -0800 Subject: [PATCH 35/64] AutoStory: TableExecutor without per-kind virtuals #312's StoryStepExecutor no longer has a virtual per step kind, so a step the table has no action for is unsupported_step(). A binding that still does some kinds itself overrides run_action(). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryActions.cpp | 2 +- .../Pokemon/AutoStory/Pokemon_StoryActions.h | 13 ++++++------ .../AutoStory/Pokemon_StoryActions_Tests.cpp | 20 +++++++++++-------- 3 files changed, 20 insertions(+), 15 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp index 99138d9a23..9dbe7f0bcb 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp @@ -124,7 +124,7 @@ Outcome TableExecutor::run_action(RunState& state, const StoryStep& step){ if (const StoryAction* action = m_table.find(step)){ return action->act(state, step); } - return StoryStepExecutor::run(state, step); + return unsupported_step(step); } // Clears what interrupted the player before `step`, counting it in diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h index e672b0df15..9f7143d8dc 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h @@ -109,10 +109,10 @@ class TableExecutor : public StoryStepExecutor{ // `table` and `guard` must outlive the executor. TableExecutor(const StoryActionTable& table, StepGuard& guard); - // The table's action for the step; with none, the kind's virtual - // (StoryStepExecutor::run()), so a game can move to the table one - // kind at a time. An OperationFailedException from either is the - // failed Outcome "operation_failed", unless the guard stops on it. + // The table's action for the step (run_action()); with none, the + // step is unsupported (unsupported_step()). An OperationFailedException + // from the action is the failed Outcome "operation_failed", unless the + // guard stops on it. // With interrupts set, each step first clears what stopped the player // since the step before, and a failed step that an interrupt explains // runs again once it is cleared. @@ -125,8 +125,9 @@ class TableExecutor : public StoryStepExecutor{ } protected: - // The table's action for the step, or the kind's virtual: what run() - // runs once the screen is clear. A binding may wrap it. + // The table's action for the step, or unsupported_step() with none: + // what run() runs once the screen is clear. A binding may wrap it, or + // do the kinds its table does not have yet. virtual Outcome run_action(RunState& state, const StoryStep& step); private: diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp index 851a6ecd03..7c916d45aa 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp @@ -199,14 +199,18 @@ UnitTestResult test_lint_names_steps_without_actions(){ } -// Steps without an action of their own go to this TALK. +// A binding that does TALK itself when its table has no action for it. class FakeTableExecutor : public TableExecutor{ public: using TableExecutor::TableExecutor; protected: - virtual Outcome talk(RunState&, const StoryStep&) override{ - return outcome_failed("talk virtual"); + virtual Outcome run_action(RunState& state, const StoryStep& step) override{ + const Outcome outcome = TableExecutor::run_action(state, step); + if (step.kind == StoryStepKind::TALK && outcome.failure == "unsupported_step"){ + return outcome_failed("talk binding"); + } + return outcome; } }; @@ -236,7 +240,7 @@ StoryAction throwing(){ }; } -UnitTestResult test_executor_uses_table_then_virtuals(){ +UnitTestResult test_executor_uses_table_then_binding(){ StoryActionTable table; table.add(StoryStepKind::GAME, "bill", named("bill action")); FakeGuard guard; @@ -245,8 +249,8 @@ UnitTestResult test_executor_uses_table_then_virtuals(){ const std::string bill = executor.run(state, make(StoryStepKind::GAME, "bill", "bill")).failure; const std::string talk = executor.run(state, make(StoryStepKind::TALK, "talk")).failure; const std::string mash = executor.run(state, make(StoryStepKind::MASH, "mash")).failure; - if (bill != "bill action" || talk != "talk virtual" || mash != "unsupported_step"){ - return "Expected table, virtual, unsupported; got " + bill + ", " + talk + ", " + mash; + if (bill != "bill action" || talk != "talk binding" || mash != "unsupported_step"){ + return "Expected table, binding, unsupported; got " + bill + ", " + talk + ", " + mash; } if (guard.trace != std::vector{"before bill", "before talk", "before mash"}){ return "Expected the guard before every step."; @@ -356,8 +360,8 @@ const StoryActionsCase STORY_ACTIONS_CASES[] = { .expectation = {.description = "names each step the table has no action for"}, }, { - .input = {.name = "executor: the table, then the kind's virtual", .test = test_executor_uses_table_then_virtuals}, - .expectation = {.description = "falls back to the per-kind virtuals, guarded before every step"}, + .input = {.name = "executor: the table, then the binding", .test = test_executor_uses_table_then_binding}, + .expectation = {.description = "a step without a table action is the binding's or unsupported, guarded before every step"}, }, { .input = {.name = "executor: a console failure fails the step", .test = test_guard_turns_failures_into_outcomes}, From 1b74c8256d2352f60e34375be67c84d93db306fc Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 20:42:44 -0800 Subject: [PATCH 36/64] AutoStory: structured step args next to a plain variant name A step's variant carried its action's arguments as free text ("mart CeruleanCity_Mart budget=1500 ..."), parsed by each action. Steps now carry them in `args` (flags, whole numbers, words), which the shared JSON codec reads and writes; actions declare StoryArgSpecs and a game checks args against them at load. split_legacy_variant() reads an old variant into a name and args during the migration; the variant word helpers are deprecated. Design: docs/design/AutoStory.md section 10. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../ComputerPrograms_UnitTestRunner.cpp | 1 + .../AutoStory/Pokemon_AutoStory_Tests.h | 2 + .../AutoStory/Pokemon_StoryArgs_Tests.cpp | 144 ++++++++++++++++++ .../AutoStory/Pokemon_StoryStepJson.cpp | 34 ++++- .../AutoStory/Pokemon_StoryStepJson_Tests.cpp | 5 + .../AutoStory/Pokemon_StoryVariant.cpp | 26 ++++ .../Pokemon/AutoStory/Pokemon_StoryVariant.h | 23 +++ .../AutoStory/Types/Pokemon_StoryArgs.cpp | 84 ++++++++++ .../AutoStory/Types/Pokemon_StoryArgs.h | 68 +++++++++ .../AutoStory/Types/Pokemon_StoryStep.h | 7 +- SerialPrograms/cmake/SourceFiles.cmake | 3 + devtools/story-data-tests/CMakeLists.txt | 8 +- docs/design/AutoStory.md | 45 ++++++ 13 files changed, 447 insertions(+), 3 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryArgs_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryArgs.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryArgs.h diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index df98fc4df2..a47faa19ff 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -82,6 +82,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_StorySegments(ret); Pokemon::add_tests_StorySteps(ret); Pokemon::add_tests_StoryStepJson(ret); + Pokemon::add_tests_StoryArgs(ret); Pokemon::add_tests_AuthoredCheckpointJson(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 0efa649a7c..d48ec292d1 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -23,6 +23,8 @@ void add_tests_StorySegments(UnitTestDatabase& database); void add_tests_StorySteps(UnitTestDatabase& database); // Registers unit tests for the lossless shared story-data wire contract. void add_tests_StoryStepJson(UnitTestDatabase& database); +// Registers unit tests for step args: action specs and reading old variant strings. +void add_tests_StoryArgs(UnitTestDatabase& database); // Registers unit tests for the shared authored envelope, game identity and embedded-resource loading. void add_tests_AuthoredCheckpointJson(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryArgs_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryArgs_Tests.cpp new file mode 100644 index 0000000000..889639d650 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryArgs_Tests.cpp @@ -0,0 +1,144 @@ +/* Story Args Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Checking a step's args against an action's specs, and reading an old + * "name key=value" variant into a name and args. Built standalone + * (PA_STORY_DATA_STANDALONE), it runs without the application. + * + */ + +#include +#include +#include +#include +#include "Pokemon_StoryVariant.h" +#include "Types/Pokemon_StoryArgs.h" +#ifndef PA_STORY_DATA_STANDALONE +#include "Pokemon_AutoStory_Tests.h" +#endif + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +// The args a Mart step takes, as an action declares them. +constexpr StoryArgSpec MART_SPECS[] = { + {.key = "map", .type = StoryArgType::TEXT, .required = true}, + {.key = "budget", .type = StoryArgType::NUMBER, .required = true}, + {.key = "floor", .type = StoryArgType::NUMBER}, + {.key = "if_present", .type = StoryArgType::FLAG}, +}; + +constexpr std::string_view MART_POSITIONAL[] = {"map"}; + + +// An old variant, read with an action's positional keys and checked +// against its specs. +struct ArgsInput{ + std::string_view name; + std::string_view variant; + std::span specs = MART_SPECS; + std::span positional = MART_POSITIONAL; +}; + +// The action name and args it gives, and the first error: the split's, +// else the specs'. +struct ArgsExpectation{ + std::string_view action; + StoryArgs args = {}; + std::string_view error = {}; +}; + +struct ArgsCase{ + ArgsInput input; + ArgsExpectation expectation; +}; + +const ArgsCase CASES[] = { + {.input = {.name = "mart", .variant = "mart CeruleanCity_Mart budget=1500 floor=1500 if_present"}, + .expectation = {.action = "mart", .args = {{"map", std::string("CeruleanCity_Mart")}, {"budget", int64_t(1500)}, {"floor", int64_t(1500)}, {"if_present", true}}}}, + {.input = {.name = "plain name", .variant = "run", .specs = {}, .positional = {}}, .expectation = {.action = "run"}}, + {.input = {.name = "words stay words", .variant = "teach tutor forget=tail-whip", .specs = {}, .positional = {}}, + .expectation = {.action = "teach", .args = {{"tutor", true}, {"forget", std::string("tail-whip")}}, .error = "unknown argument \"forget\""}}, + {.input = {.name = "unknown key", .variant = "mart M budget=1 budgte=1"}, + .expectation = {.action = "mart", .args = {{"map", std::string("M")}, {"budget", int64_t(1)}, {"budgte", int64_t(1)}}, .error = "unknown argument \"budgte\""}}, + {.input = {.name = "wrong type", .variant = "mart M budget=lots"}, + .expectation = {.action = "mart", .args = {{"map", std::string("M")}, {"budget", std::string("lots")}}, .error = "argument \"budget\" has the wrong type"}}, + {.input = {.name = "missing required", .variant = "mart M"}, + .expectation = {.action = "mart", .args = {{"map", std::string("M")}}, .error = "missing argument \"budget\""}}, + {.input = {.name = "repeated key", .variant = "mart M budget=1 budget=2"}, + .expectation = {.action = "mart", .args = {{"map", std::string("M")}, {"budget", int64_t(1)}}, .error = "\"budget=2\" repeats an argument"}}, +}; + + +// "" when `test` reads as expected, else what differs. +std::string check_case(const ArgsCase& test){ + const LegacyVariant read = split_legacy_variant(test.input.variant, test.input.positional); + const std::string error = read.error.empty() ? story_args_error(read.args, test.input.specs) : read.error; + if (read.name != test.expectation.action || read.args != test.expectation.args){ + return "read \"" + read.name + "\" with other args"; + } + if (error != test.expectation.error){ + return "expected error \"" + std::string(test.expectation.error) + "\", got \"" + error + "\""; + } + return ""; +} + + +#ifndef PA_STORY_DATA_STANDALONE + +class StoryArgsTest : public UnitTest{ +public: + explicit StoryArgsTest(ArgsCase test) + : UnitTest("Pokemon::StoryArgs - " + std::string(test.input.name)) + , m_case(test) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string error = check_case(m_case); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } + +private: + ArgsCase m_case; +}; + +#endif + + +} // namespace + + +#ifndef PA_STORY_DATA_STANDALONE + +void add_tests_StoryArgs(UnitTestDatabase& database){ + for (const ArgsCase& test : CASES){ + database.add(test); + } +} + +#endif + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +#ifdef PA_STORY_DATA_STANDALONE + +int main(){ + int failed = 0; + for (const auto& test : PokemonAutomation::Pokemon::CASES){ + const std::string error = PokemonAutomation::Pokemon::check_case(test); + std::cout << test.input.name << ": " << (error.empty() ? "PASS" : error) << '\n'; + failed += !error.empty(); + } + return failed != 0; +} + +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp index 78427f9667..a1483a3505 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Json/JsonArray.h" #include "Common/Cpp/Json/JsonObject.h" @@ -177,6 +178,31 @@ std::vector read_items(const JsonValue& value, std::string_view sourc return result; } +JsonObject args_json(const StoryArgs& args){ + JsonObject result; + for (const auto& [key, value] : args){ + std::visit([&](const auto& held){ result[key] = held; }, value); + } + return result; +} + +// A step's args: flags, whole numbers and words; any other value fails. +StoryArgs read_args(const JsonValue& value, std::string_view source){ + StoryArgs result; + for (const auto& [key, item] : value.to_object_throw(std::string(source))){ + if (item.is_boolean()){ + result[key] = item.to_boolean_throw(); + }else if (item.is_integer()){ + result[key] = item.to_integer_throw(); + }else if (item.is_string()){ + result[key] = item.to_string_throw(); + }else{ + throw ParseException(std::format("{}: argument {} is not a flag, whole number or word", source, key)); + } + } + return result; +} + // `result` with the step's yes/no and count fields read from `root`. StoryStep read_step_options(StoryStep result, const JsonObject& root, std::string_view source){ if (const JsonValue* field = root.get_value("fight_wild")){ @@ -292,6 +318,9 @@ JsonValue story_step_json(const StoryStep& step){ if (!step.variant.empty()){ result["variant"] = step.variant; } + if (!step.args.empty()){ + result["args"] = args_json(step.args); + } if (!step.skip_if.empty()){ result["skip_if"] = strings_json(step.skip_if); } @@ -303,7 +332,7 @@ JsonValue story_step_json(const StoryStep& step){ StoryStep read_story_step(const JsonValue& value, std::string_view source){ const JsonObject& root = fields(value, {"id", "kind", "why", "target", "direction", "legs", "fight_wild", "yes", - "may_lose", "battles", "items", "variant", "skip_if", "declared_after"}, source); + "may_lose", "battles", "items", "variant", "args", "skip_if", "declared_after"}, source); StoryStep result; result.name = root.get_string_throw("id"); if (result.name.empty()){ @@ -329,6 +358,9 @@ StoryStep read_story_step(const JsonValue& value, std::string_view source){ if (const JsonValue* field = root.get_value("variant")){ result.variant = field->to_string_throw(); } + if (const JsonValue* field = root.get_value("args")){ + result.args = read_args(*field, source); + } if (const JsonValue* field = root.get_value("skip_if")){ result.skip_if = read_strings(*field, source); } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp index 269b9f4412..60178eae1f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp @@ -57,6 +57,11 @@ const WireCase CASES[] = { {.input = {.name = "unknown facing stays absent", .record = Record::POSE, .json = R"({"map":"M","certainty":"tile","where":{"kind":"tiles","tiles":[[0,0]]}})"}, .expectation = {.canonical = R"({"map":"M","certainty":"tile","where":{"kind":"tiles","tiles":[[0,0]]}})"}}, {.input = {.name = "empty position differs from no position", .record = Record::POSE, .json = R"({"map":"M","certainty":"unknown","where":{"kind":"tiles","tiles":[]}})"}, .expectation = {.canonical = R"({"map":"M","certainty":"unknown","where":{"kind":"tiles","tiles":[]}})"}}, {.input = {.name = "ordered checkpoint", .record = Record::CHECKPOINT, .json = R"({"id":"00.05","title":"Parcel","events":[{"id":"first","kind":"route"},{"id":"second","kind":"scene"}]})"}, .expectation = {.canonical = R"({"id":"00.05","title":"Parcel","events":[{"id":"first","kind":"route"},{"id":"second","kind":"scene"}]})"}}, + {.input = {.name = "args", .json = R"({"id":"buy","kind":"game_action","variant":"mart","args":{"map":"CeruleanCity_Mart","budget":3000,"if_present":true}})"}, .expectation = {.canonical = R"({"id":"buy","kind":"game_action","variant":"mart","args":{"budget":3000,"if_present":true,"map":"CeruleanCity_Mart"}})"}}, + {.input = {.name = "empty args are omitted", .json = R"({"id":"buy","kind":"game_action","variant":"mart","args":{}})"}, .expectation = {.canonical = R"({"id":"buy","kind":"game_action","variant":"mart"})"}}, + {.input = {.name = "fractional arg", .json = R"({"id":"a","kind":"game_action","variant":"mart","args":{"budget":1.5}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "nested arg", .json = R"({"id":"a","kind":"game_action","variant":"mart","args":{"items":[1]}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "args not an object", .json = R"({"id":"a","kind":"game_action","variant":"mart","args":["map"]})"}, .expectation = {.rejected = true}}, {.input = {.name = "unknown field", .json = R"({"id":"a","kind":"talk","mystery":0})"}, .expectation = {.rejected = true}}, {.input = {.name = "unknown action", .json = R"({"id":"a","kind":"magic"})"}, .expectation = {.rejected = true}}, {.input = {.name = "negative count", .json = R"({"id":"a","kind":"train","battles":-1})"}, .expectation = {.rejected = true}}, diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.cpp index 6df0e9df31..a10163f584 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.cpp @@ -66,6 +66,32 @@ std::optional variant_number(std::string_view text, size_t max_digits){ return value; } +LegacyVariant split_legacy_variant(std::string_view variant, std::span positional){ + LegacyVariant result; + const std::vector words = variant_words(variant); + result.name = variant_name(variant); + size_t next = 0; + for (size_t c = result.name.empty() ? 0 : 1; c < words.size(); c++){ + std::string key; + StoryArgValue value = true; + if (const std::optional pair = variant_pair(words[c])){ + key = pair->key; + const std::optional number = variant_number(pair->value, 18); + value = number ? StoryArgValue(int64_t(*number)) : StoryArgValue(std::string(pair->value)); + }else if (next < positional.size()){ + key = positional[next++]; + value = std::string(words[c]); + }else{ + key = words[c]; + } + if (!result.args.emplace(std::move(key), std::move(value)).second){ + result.error = "\"" + std::string(words[c]) + "\" repeats an argument"; + return result; + } + } + return result; +} + } // namespace Pokemon diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.h index 79f854bdd6..bd8c02343a 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryVariant.h @@ -8,6 +8,11 @@ * picks the step's action (Pokemon_StoryActions.h) and the action reads * the rest. * + * Deprecated: a step's variant is now a plain action name and its + * arguments are structured (StoryStep::args, Types/Pokemon_StoryArgs.h). + * split_legacy_variant() reads an old variant into that form while plans + * and callers move over; the word helpers go once none reads them. + * */ #ifndef PokemonAutomation_Pokemon_StoryVariant_H @@ -15,8 +20,11 @@ #include #include +#include +#include #include #include +#include "Types/Pokemon_StoryArgs.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -46,6 +54,21 @@ std::optional variant_value(std::string_view variant, std::str std::optional variant_number(std::string_view text, size_t max_digits = 6); +// An old variant as an action name and its args, or why it can't be read. +struct LegacyVariant{ + std::string name; + StoryArgs args; + std::string error; +}; + +// `variant` written the old way ("mart CeruleanCity_Mart budget=3000 +// if_present"): its first word is the name; the next plain words take the +// keys in `positional`, in order, and plain words after those are flags; +// "key=value" words are numbers when all digits, else words. It reads no +// action's specs: check the args against them (story_args_error()). +LegacyVariant split_legacy_variant(std::string_view variant, std::span positional = {}); + + } // namespace Pokemon } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryArgs.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryArgs.cpp new file mode 100644 index 0000000000..c4da5548fd --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryArgs.cpp @@ -0,0 +1,84 @@ +/* Story Args + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryArgs.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + + +template +const Type* find_arg(const StoryArgs& args, std::string_view key){ + const auto iter = args.find(key); + return iter == args.end() ? nullptr : std::get_if(&iter->second); +} + +bool has_type(const StoryArgValue& value, StoryArgType type){ + switch (type){ + case StoryArgType::FLAG: + return std::holds_alternative(value); + case StoryArgType::NUMBER: + return std::holds_alternative(value); + case StoryArgType::TEXT: + return std::holds_alternative(value); + } + return false; +} + +const StoryArgSpec* find_spec(std::span specs, std::string_view key){ + for (const StoryArgSpec& spec : specs){ + if (spec.key == key){ + return &spec; + } + } + return nullptr; +} + + +} // namespace + + +std::optional story_arg_number(const StoryArgs& args, std::string_view key){ + const int64_t* value = find_arg(args, key); + return value ? std::optional(*value) : std::nullopt; +} + +std::optional story_arg_text(const StoryArgs& args, std::string_view key){ + const std::string* value = find_arg(args, key); + return value ? std::optional(*value) : std::nullopt; +} + +bool story_arg_flag(const StoryArgs& args, std::string_view key){ + const bool* value = find_arg(args, key); + return value != nullptr && *value; +} + +std::string story_args_error(const StoryArgs& args, std::span specs){ + for (const auto& [key, value] : args){ + const StoryArgSpec* spec = find_spec(specs, key); + if (spec == nullptr){ + return std::format("unknown argument \"{}\"", key); + } + if (!has_type(value, spec->type)){ + return std::format("argument \"{}\" has the wrong type", key); + } + } + for (const StoryArgSpec& spec : specs){ + if (spec.required && args.find(spec.key) == args.end()){ + return std::format("missing argument \"{}\"", spec.key); + } + } + return ""; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryArgs.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryArgs.h new file mode 100644 index 0000000000..96214deed7 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryArgs.h @@ -0,0 +1,68 @@ +/* Story Args + * + * From: https://github.com/PokemonAutomation/ + * + * A step's arguments (StoryStep::args): named flags, whole numbers and + * words that its action reads, e.g. a Mart step's {"map": + * "CeruleanCity_Mart", "budget": 3000}. Each action declares the ones it + * takes (StoryArgSpec); a game checks a step's args against them when it + * loads the step, so a typo fails at load instead of mid-run. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryArgs_H +#define PokemonAutomation_Pokemon_StoryArgs_H + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// One argument's value: a flag, a whole number or a word. +using StoryArgValue = std::variant; + +// A step's arguments by name. +using StoryArgs = std::map>; + + +// The number `key` holds; nothing if absent or not a number. +std::optional story_arg_number(const StoryArgs& args, std::string_view key); + +// The word `key` holds; nothing if absent or not a word. +std::optional story_arg_text(const StoryArgs& args, std::string_view key); + +// Whether flag `key` is set; absent is unset. +bool story_arg_flag(const StoryArgs& args, std::string_view key); + + +// The type an action declares for an argument. +enum class StoryArgType{ + FLAG, + NUMBER, + TEXT, +}; + +// An argument an action takes. +struct StoryArgSpec{ + std::string_view key; + StoryArgType type = StoryArgType::TEXT; + bool required = false; +}; + +// Why `args` don't fit `specs`: a key no spec names, a value of another +// type, or a required one missing. Empty when they fit. +std::string story_args_error(const StoryArgs& args, std::span specs); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h index 457725dc05..8255c60e3f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h @@ -18,6 +18,7 @@ #include #include "Pokemon/AutoStory/Pokemon_StoryEvents.h" #include "Pokemon/Navigation/Pokemon_Grid.h" +#include "Pokemon_StoryArgs.h" #include "Pokemon_StoryStepKind.h" namespace PokemonAutomation{ @@ -61,8 +62,12 @@ struct StoryStep{ // How this game does the kind, when it has more than one way: a // route's plan costs, a door lined up by sight, the Mart lady instead // of the clerk. Empty is the game's usual way. GAME: the step's name - // in the game's executor. + // in the game's executor. A plain name; what the action needs beyond + // it goes in `args`. std::string variant; + // The arguments the variant's action reads (a Mart's map and budget), + // checked against the ones it declares when the game loads the step. + StoryArgs args; // Skipped when all of these hold (and there is at least one): names // the game's executor answers (StoryStepExecutor::holds()), run flags diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 4630157b77..736bed62e3 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1512,11 +1512,14 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StoryStepJson.cpp Source/Pokemon/AutoStory/Pokemon_StoryStepJson.h Source/Pokemon/AutoStory/Pokemon_StoryStepJson_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryArgs_Tests.cpp Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp Source/Pokemon/AutoStory/Pokemon_StorySteps.h Source/Pokemon/AutoStory/Pokemon_StorySteps_Tests.cpp Source/Pokemon/AutoStory/Pokemon_TilePose.cpp Source/Pokemon/AutoStory/Pokemon_TilePose.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryArgs.cpp + Source/Pokemon/AutoStory/Types/Pokemon_StoryArgs.h Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.cpp Source/Pokemon/AutoStory/Types/Pokemon_StoryChecks.h Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h diff --git a/devtools/story-data-tests/CMakeLists.txt b/devtools/story-data-tests/CMakeLists.txt index 978db4f6d0..78d07af69e 100644 --- a/devtools/story-data-tests/CMakeLists.txt +++ b/devtools/story-data-tests/CMakeLists.txt @@ -11,6 +11,7 @@ add_executable(StoryDataTests "${STORY}/Pokemon_StoryStepJson.cpp" "${STORY}/Pokemon_StoryStepJson_Tests.cpp" "${STORY}/Pokemon_TilePose.cpp" + "${STORY}/Types/Pokemon_StoryArgs.cpp" "${ROOT}/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.cpp" "${ROOT}/Common/Cpp/Exceptions.cpp" "${ROOT}/Common/Cpp/Json/JsonValue.cpp" @@ -26,8 +27,12 @@ list(REMOVE_ITEM STORY_DATA_SOURCES "${STORY}/Pokemon_StoryStepJson_Tests.cpp") add_executable(AuthoredCheckpointTests ${STORY_DATA_SOURCES} "${STORY}/Pokemon_AuthoredCheckpointJson.cpp" "${STORY}/Pokemon_AuthoredCheckpointJson_Tests.cpp") +add_executable(StoryArgsTests + "${STORY}/Types/Pokemon_StoryArgs.cpp" + "${STORY}/Pokemon_StoryVariant.cpp" + "${STORY}/Pokemon_StoryArgs_Tests.cpp") -foreach(TEST_TARGET IN ITEMS StoryDataTests AuthoredCheckpointTests) +foreach(TEST_TARGET IN ITEMS StoryDataTests AuthoredCheckpointTests StoryArgsTests) target_include_directories(${TEST_TARGET} PRIVATE "${ROOT}" "${ROOT}/SerialPrograms/Source") target_compile_features(${TEST_TARGET} PRIVATE cxx_std_23) target_compile_definitions(${TEST_TARGET} PRIVATE PA_STORY_DATA_STANDALONE) @@ -41,3 +46,4 @@ endif() endforeach() add_test(NAME StoryData COMMAND StoryDataTests) add_test(NAME AuthoredCheckpoint COMMAND AuthoredCheckpointTests) +add_test(NAME StoryArgs COMMAND StoryArgsTests) diff --git a/docs/design/AutoStory.md b/docs/design/AutoStory.md index d14601e42e..4e5d1eb607 100644 --- a/docs/design/AutoStory.md +++ b/docs/design/AutoStory.md @@ -885,3 +885,48 @@ among the agents is recorded outside this doc. trade-back, or a levelled Pokémon brought in from another save. Optional trades the game itself offers (e.g. the Vermilion Farfetch'd) are allowed only behind an option. + +## 10. Step arguments (user, 2026-11-09) + +A story step's `variant` used to carry its action's arguments as free text, +for example `"mart CeruleanCity_Mart budget=1500 floor=1500 potion=3 +awakening=2"`. Each action parsed its own words, so a typo or a missing +argument showed up only when the step ran, and the Python reader in +PokemonSimulation had to copy every action's parser to read a plan. + +Now `variant` is only the action's name, the key it is registered under in a +game's action table. Its arguments move to `args`, a JSON object on the step +whose values are flags, whole numbers or words (`StoryStep::args`, +`Types/Pokemon_StoryArgs.h`). Each action declares the arguments it takes, +with a type and whether each one is required (`StoryArgSpec`). A game checks +every step's `args` against those specs when it loads the plan, so an +unknown key, a word where a number belongs or a missing budget fails at +load. Items to buy stay in the step's `items` list and are not repeated in +`args`. The shared JSON codec reads and writes `args` without knowing any +action, and omits it when it is empty. + +During the migration, a plan may still carry an old variant string. +`split_legacy_variant()` turns it into a name and args: the leading plain +words take the action's positional keys (a Mart's `map`), `key=value` +words become numbers when they are all digits and words otherwise, and any +remaining plain word becomes a flag (`if_present`). The word helpers in +`Pokemon_StoryVariant.h` are deprecated and will be removed once no action +reads them. + +The actions that take arguments today, all FRLG (BDSP's are listed for a +later change): + +| Action | Arguments | Notes | +|---|---|---| +| `mart` | `map` word, required; `budget` number, required; `floor` number | What to buy goes in `items`. | +| `teach` | `item` word (`tm03`, `hm01`, `tutor`), `move` word, `slot` number, all required; `forget` word | | +| `pc` | `op` word (`deposit`), `slot` number, `box` number, all required; `if_present` flag | | +| `grind`, `grind_check` | `slot`, `level`, `encounters` numbers and `pace` word, required; `heal_every`, `chance` numbers; `beat` word | `grind_check` takes the same arguments. | +| `capture` | `species` word, `catches`, `encounters`, `balls` numbers, all required; `pace` word | | +| `level` | `slot`, `min` numbers, required | Built in C++, not in a plan. | +| `fossil` | `fossil` word (`helix`, `dome`), required | | +| `use_item` | `item` word, required; `slot` number | 00.30 onwards. | +| `lift_floor` | `from`, `to` words, required | 00.30 onwards. | + +Plain names such as `run`, `trainer_line`, `cut_tree` and `bike` take no +arguments and stay as they are. From 29844566fe5230e77efc65bdd4df064c45b394f0 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 20:43:46 -0800 Subject: [PATCH 37/64] AutoStory: actions declare their args; lint checks steps against them StoryAction::args lists the args an action's steps may carry, and lint_story_checkpoint() reports a step whose args don't fit, as it reports a step without an action. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Pokemon_StoryActions.cpp | 8 ++++--- .../Pokemon/AutoStory/Pokemon_StoryActions.h | 7 +++++- .../AutoStory/Pokemon_StoryActions_Tests.cpp | 22 ++++++++++++++++++- 3 files changed, 32 insertions(+), 5 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp index 9dbe7f0bcb..fb95a779f8 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp @@ -66,10 +66,12 @@ std::vector lint_story_checkpoint(const StoryCheckpoint& data, cons std::vector problems; for (size_t c = 0; c < data.steps.size(); c++){ const StoryStep& step = data.steps[c]; - if (table.find(step) == nullptr){ + const StoryAction* action = table.find(step); + const std::string error = action == nullptr ? "no action" : story_args_error(step.args, action->args); + if (!error.empty()){ problems.emplace_back(std::format( - "{} step {} {}: no action for {} '{}'", - data.id, c + 1, step.name, story_step_kind_name(step.kind), variant_name(step.variant) + "{} step {} {}: {} for {} '{}'", + data.id, c + 1, step.name, error, story_step_kind_name(step.kind), variant_name(step.variant) )); } } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h index 9f7143d8dc..3f778729ee 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -47,6 +48,9 @@ struct StoryAction{ // The screen event the action ends on ("fade", "dialog"). Declared for // the event-driven waits to come; nothing reads it yet. std::string waits_for = {}; + // The args its steps may carry (StoryStep::args); a step with any + // other, or without a required one, fails lint_story_checkpoint(). + std::span args = {}; }; @@ -75,7 +79,8 @@ class StoryActionTable{ }; // The steps of `data` that `table` has no action for, as -// " step : no action for GAME 'bill'". +// " step : no action for GAME 'bill'", or whose args +// don't fit their action's, as "... missing argument \"budget\" for GAME 'mart'". std::vector lint_story_checkpoint(const StoryCheckpoint& data, const StoryActionTable& table); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp index 7c916d45aa..c29ac429e3 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp @@ -168,10 +168,25 @@ UnitTestResult test_duplicate_actions_throw(){ return found(table, StoryStepKind::TALK, "bill") == "first" ? UnitTestResult(true) : UnitTestResult("Expected the first action kept."); } +// The args a test Mart takes. +constexpr StoryArgSpec MART_ARGS[] = { + {.key = "map", .type = StoryArgType::TEXT, .required = true}, + {.key = "budget", .type = StoryArgType::NUMBER, .required = true}, +}; + +// `step` with `args`. +StoryStep with_args(StoryStep step, StoryArgs args){ + step.args = std::move(args); + return step; +} + UnitTestResult test_lint_names_steps_without_actions(){ StoryActionTable table; table.add(StoryStepKind::ROUTE, "", named("route")); table.add_any_kind("bill", named("bill")); + StoryAction mart = named("mart"); + mart.args = MART_ARGS; + table.add(StoryStepKind::GAME, "mart", std::move(mart)); const StoryCheckpoint data{ .id = "00.05", .title = "", @@ -181,19 +196,24 @@ UnitTestResult test_lint_names_steps_without_actions(){ make(StoryStepKind::GAME, "meet Bill", "bill"), make(StoryStepKind::GAME, "teleporter", "cell_separator x=1"), make(StoryStepKind::TALK, "talk"), + with_args(make(StoryStepKind::GAME, "buy", "mart"), {{"map", std::string("M")}, {"budget", int64_t(1500)}}), + with_args(make(StoryStepKind::GAME, "buy more", "mart"), {{"map", std::string("M")}}), + with_args(make(StoryStepKind::GAME, "meet Bill again", "bill"), {{"slot", int64_t(1)}}), }, }; const std::vector problems = lint_story_checkpoint(data, table); const std::vector expected = { "00.05 step 3 teleporter: no action for GAME 'cell_separator'", "00.05 step 4 talk: no action for TALK ''", + "00.05 step 6 buy more: missing argument \"budget\" for GAME 'mart'", + "00.05 step 7 meet Bill again: unknown argument \"slot\" for GAME 'bill'", }; if (problems != expected){ std::string got; for (const std::string& problem : problems){ got += "\n" + problem; } - return "Expected two steps without actions, got:" + got; + return "Expected two steps without actions and two with bad args, got:" + got; } return true; } From dd9529b51b6052b8080bd2871b44f1daa595e084 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 20:45:06 -0800 Subject: [PATCH 38/64] AutoStory: shared story range options and story log lines StoryRangeOptions is the start/end checkpoint dropdowns over one list with the start-before-end check; StoryRunOptions is now that group plus the run policy, with the same keys and public members. Pokemon_StoryLog holds the checkpoint start/attempt/pass/reset lines, event_log_line and a stats counts helper, with no engine dependency; run_checkpoint, run_segment and record_story_stats use it, with unchanged output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../ComputerPrograms_UnitTestRunner.cpp | 2 + .../AutoStory/Pokemon_AutoStory_Tests.h | 4 + .../Pokemon/AutoStory/Pokemon_StoryEvents.cpp | 7 +- .../Pokemon/AutoStory/Pokemon_StoryEvents.h | 6 +- .../Pokemon/AutoStory/Pokemon_StoryLog.cpp | 75 ++++++++ .../Pokemon/AutoStory/Pokemon_StoryLog.h | 76 ++++++++ .../AutoStory/Pokemon_StoryLog_Tests.cpp | 173 ++++++++++++++++++ .../AutoStory/Pokemon_StorySegments.cpp | 19 +- .../Pokemon/AutoStory/Pokemon_StorySteps.cpp | 7 +- .../Options/Pokemon_StoryRangeOptions.cpp | 51 ++++++ .../Options/Pokemon_StoryRangeOptions.h | 48 +++++ .../Pokemon_StoryRangeOptions_Tests.cpp | 134 ++++++++++++++ .../Options/Pokemon_StoryRunOptions.cpp | 31 +--- .../Pokemon/Options/Pokemon_StoryRunOptions.h | 17 +- SerialPrograms/cmake/SourceFiles.cmake | 6 + 15 files changed, 591 insertions(+), 65 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h create mode 100644 SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.cpp create mode 100644 SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.h create mode 100644 SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index df98fc4df2..266e64a2f3 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -83,6 +83,8 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_StorySteps(ret); Pokemon::add_tests_StoryStepJson(ret); Pokemon::add_tests_AuthoredCheckpointJson(ret); + Pokemon::add_tests_StoryLog(ret); + Pokemon::add_tests_StoryRangeOptions(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); NintendoSwitch::add_tests_UpdatePopupDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 0efa649a7c..9f975f6b39 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -25,6 +25,10 @@ void add_tests_StorySteps(UnitTestDatabase& database); void add_tests_StoryStepJson(UnitTestDatabase& database); // Registers unit tests for the shared authored envelope, game identity and embedded-resource loading. void add_tests_AuthoredCheckpointJson(UnitTestDatabase& database); +// Registers unit tests for the shared checkpoint log lines and stats counts. +void add_tests_StoryLog(UnitTestDatabase& database); +// Registers unit tests for the shared start/end checkpoint range options. +void add_tests_StoryRangeOptions(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp index 35c61a688c..f9a87c6778 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp @@ -113,11 +113,6 @@ const char* recovery_name(RecoveryKind kind){ } -std::string event_log_line(const std::string& checkpoint, size_t number, const std::string& event, const std::string& status){ - return std::format("[Event] {}/{} {}: {}", checkpoint, number, event, status); -} - - namespace{ // Runs an action; if it succeeded knowing where it left the player, that @@ -410,7 +405,7 @@ Outcome finish_checkpoint(RunState& state, Checkpoint& checkpoint){ CheckpointReport run_checkpoint(RunState& state, Checkpoint& checkpoint, EventLogger& log){ CheckpointReport report; const std::string& id = checkpoint.id; - log(std::format("[Checkpoint] {}: start, {} events", id, checkpoint.events.size())); + log(checkpoint_start_line(id, checkpoint.events.size())); std::optional failing = first_failing(checkpoint.start, state); if (failing){ return stop_checkpoint(report, log, id, outcome_failed("start_failed", *failing)); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h index 388ce48b03..582518b9c3 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.h @@ -34,6 +34,7 @@ #include #include #include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon_StoryLog.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -237,11 +238,6 @@ struct CheckpointReport{ using EventLogger = MoveOnlyFunction; -// One log line, in a format the lab watcher parses: -// [Event] 00.04/3 talk_mom: start -// [Event] 00.04/3 talk_mom: failed: expect_failed: has_parcel -std::string event_log_line(const std::string& checkpoint, size_t number, const std::string& event, const std::string& status); - // Problems an author should fix before running: unnamed or empty events, // missing actions, recoveries out of escalation order. std::vector lint_checkpoint(const Checkpoint& checkpoint); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp new file mode 100644 index 0000000000..8b5b3e0dca --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp @@ -0,0 +1,75 @@ +/* Story Log + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryLog.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +std::string resets_text(size_t attempt){ + if (attempt <= 1){ + return "one-shot"; + } + return std::format("{} reset{}", attempt - 1, attempt == 2 ? "" : "s"); +} + +} // namespace + + +std::string event_log_line(std::string_view checkpoint, size_t number, std::string_view event, std::string_view status){ + return std::format("[Event] {}/{} {}: {}", checkpoint, number, event, status); +} + +std::string checkpoint_start_line(std::string_view checkpoint){ + return std::format("[Checkpoint] {}: start", checkpoint); +} + +std::string checkpoint_start_line(std::string_view checkpoint, size_t events){ + return std::format("[Checkpoint] {}: start, {} events", checkpoint, events); +} + +std::string checkpoint_attempt_line(std::string_view checkpoint, size_t attempt){ + return std::format("[Checkpoint] {}: attempt {}", checkpoint, attempt); +} + +std::string checkpoint_attempt_line(std::string_view checkpoint, size_t attempt, size_t attempts){ + return std::format("[Checkpoint] {}: attempt {}/{}", checkpoint, attempt, attempts); +} + +std::string checkpoint_pass_line(std::string_view checkpoint, size_t attempt, size_t in_place){ + return std::format( + "[Checkpoint] {}: passed on attempt {} ({}){}", + checkpoint, attempt, resets_text(attempt), + in_place == 0 ? "" : std::format(", {} in place", in_place) + ); +} + +std::string checkpoint_reset_line(std::string_view checkpoint, size_t next_attempt){ + return std::format("[Checkpoint] {}: failed, resetting for attempt {}", checkpoint, next_attempt); +} + +std::string checkpoint_reset_line(std::string_view segment, std::string_view checkpoint, size_t next_attempt, size_t attempts){ + return std::format( + "[Segment] {}: {} failed, reloading for attempt {}/{}", + segment, checkpoint, next_attempt, attempts + ); +} + + +void record_story_counts(AutoStoryStats& stats, const StoryRunCounts& counts){ + stats.m_segment += counts.segments; + stats.m_checkpoint += counts.checkpoints; + stats.m_reset += counts.resets; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h new file mode 100644 index 0000000000..5b5df714a9 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog.h @@ -0,0 +1,76 @@ +/* Story Log + * + * From: https://github.com/PokemonAutomation/ + * + * The log lines an AutoStory program writes around its checkpoints, in + * one format for every game: the story engine (Pokemon_StoryEvents.h, + * Pokemon_StorySegments.h) writes them, and a game with its own checkpoint + * loop (SV's) writes the same lines, so the lab watcher and whoever reads + * a log find each checkpoint's start, attempts, resets and pass the same + * way. Also the program's stats counts. Nothing here runs a story. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryLog_H +#define PokemonAutomation_Pokemon_StoryLog_H + +#include +#include +#include +#include "Pokemon_AutoStoryStats.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// One event's line: +// [Event] 00.04/3 talk_mom: start +// [Event] 00.04/3 talk_mom: failed: expect_failed: has_parcel +std::string event_log_line(std::string_view checkpoint, size_t number, std::string_view event, std::string_view status); + +// A checkpoint starts: +// [Checkpoint] 00.04: start +std::string checkpoint_start_line(std::string_view checkpoint); +// The story engine starts a checkpoint of `events` events: +// [Checkpoint] 00.04: start, 3 events +std::string checkpoint_start_line(std::string_view checkpoint, size_t events); + +// An attempt at a checkpoint starts, counting from 1: +// [Checkpoint] 00.04: attempt 2 +std::string checkpoint_attempt_line(std::string_view checkpoint, size_t attempt); +// The same, out of the program's limit of `attempts`: +// [Checkpoint] 00.04: attempt 2/3 +std::string checkpoint_attempt_line(std::string_view checkpoint, size_t attempt, size_t attempts); + +// A checkpoint passed on attempt `attempt`, after `in_place` recoveries in +// place: +// [Checkpoint] 00.03: passed on attempt 1 (one-shot) +// [Checkpoint] 00.04: passed on attempt 3 (2 resets), 1 in place +std::string checkpoint_pass_line(std::string_view checkpoint, size_t attempt, size_t in_place = 0); + +// An attempt failed and the game resets to the checkpoint's save for +// attempt `next_attempt`: +// [Checkpoint] 00.04: failed, resetting for attempt 2 +std::string checkpoint_reset_line(std::string_view checkpoint, size_t next_attempt); +// The story engine reloads within segment `segment`, out of `attempts`: +// [Segment] 00: 00.02 failed, reloading for attempt 2/3 +std::string checkpoint_reset_line(std::string_view segment, std::string_view checkpoint, size_t next_attempt, size_t attempts); + + +// What a story run adds to the program's stats. +struct StoryRunCounts{ + size_t segments = 0; + // Checkpoints passed (and saved at). + size_t checkpoints = 0; + // Game resets or reloads after failed attempts. + size_t resets = 0; +}; + +// Adds `counts` to the shared AutoStory stats. +void record_story_counts(AutoStoryStats& stats, const StoryRunCounts& counts); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp new file mode 100644 index 0000000000..7737d2cb41 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp @@ -0,0 +1,173 @@ +/* Story Log Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_AutoStory_Tests.h" +#include "Pokemon_StoryLog.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +// A formatter's line, made when the table is built. +struct StoryLogInput{ + std::string name; + std::string line; +}; + +// The exact line: the lab watcher and the engine tests read these. +struct StoryLogExpectation{ + std::string line; +}; + +// One formatter call and the line it must make. +struct StoryLogCase{ + StoryLogInput input; + StoryLogExpectation expectation; +}; + +class Test_StoryLog : public UnitTest{ +public: + Test_StoryLog(StoryLogCase test_case) + : UnitTest("Pokemon::StoryLog - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + if (m_case.input.line != m_case.expectation.line){ + return "Expected \"" + m_case.expectation.line + "\", got \"" + m_case.input.line + "\""; + } + return true; + } + +private: + const StoryLogCase m_case; +}; + +const StoryLogCase STORY_LOG_CASES[] = { + { + .input = {.name = "event", .line = event_log_line("00.04", 3, "talk_mom", "start")}, + .expectation = {.line = "[Event] 00.04/3 talk_mom: start"}, + }, + { + .input = {.name = "checkpoint start", .line = checkpoint_start_line("00.04")}, + .expectation = {.line = "[Checkpoint] 00.04: start"}, + }, + { + .input = {.name = "checkpoint start with its events", .line = checkpoint_start_line("00.04", 3)}, + .expectation = {.line = "[Checkpoint] 00.04: start, 3 events"}, + }, + { + .input = {.name = "attempt", .line = checkpoint_attempt_line("00.04", 2)}, + .expectation = {.line = "[Checkpoint] 00.04: attempt 2"}, + }, + { + .input = {.name = "attempt out of a limit", .line = checkpoint_attempt_line("00.04", 2, 3)}, + .expectation = {.line = "[Checkpoint] 00.04: attempt 2/3"}, + }, + { + .input = {.name = "one-shot pass", .line = checkpoint_pass_line("00.03", 1)}, + .expectation = {.line = "[Checkpoint] 00.03: passed on attempt 1 (one-shot)"}, + }, + { + .input = {.name = "pass after one reset", .line = checkpoint_pass_line("00.04", 2)}, + .expectation = {.line = "[Checkpoint] 00.04: passed on attempt 2 (1 reset)"}, + }, + { + .input = {.name = "pass after resets and recoveries in place", .line = checkpoint_pass_line("00.04", 3, 1)}, + .expectation = {.line = "[Checkpoint] 00.04: passed on attempt 3 (2 resets), 1 in place"}, + }, + { + .input = {.name = "reset", .line = checkpoint_reset_line("00.04", 2)}, + .expectation = {.line = "[Checkpoint] 00.04: failed, resetting for attempt 2"}, + }, + { + .input = {.name = "reload within a segment", .line = checkpoint_reset_line("00", "00.02", 2, 3)}, + .expectation = {.line = "[Segment] 00: 00.02 failed, reloading for attempt 2/3"}, + }, +}; + + +// Counts added to fresh stats, in order. +struct StoryCountsInput{ + std::string name; + std::vector added; +}; + +// The stats after them: counts add up rather than replace. +struct StoryCountsExpectation{ + uint64_t segments; + uint64_t checkpoints; + uint64_t resets; +}; + +// Counts recorded into the AutoStory stats and the totals they must reach. +struct StoryCountsCase{ + StoryCountsInput input; + StoryCountsExpectation expectation; +}; + +class Test_StoryCounts : public UnitTest{ +public: + Test_StoryCounts(StoryCountsCase test_case) + : UnitTest("Pokemon::StoryLog - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + AutoStoryStats stats; + for (const StoryRunCounts& counts : m_case.input.added){ + record_story_counts(stats, counts); + } + const StoryCountsExpectation& expected = m_case.expectation; + if (stats.m_segment != expected.segments || stats.m_checkpoint != expected.checkpoints || stats.m_reset != expected.resets){ + return "Expected " + std::to_string(expected.segments) + " segments, " + std::to_string(expected.checkpoints) + + " checkpoints and " + std::to_string(expected.resets) + " resets, got " + + std::to_string(stats.m_segment) + ", " + std::to_string(stats.m_checkpoint) + + " and " + std::to_string(stats.m_reset); + } + return true; + } + +private: + const StoryCountsCase m_case; +}; + +const StoryCountsCase STORY_COUNTS_CASES[] = { + { + .input = {.name = "a segment's counts in the stats", .added = {{.segments = 1, .checkpoints = 2, .resets = 3}}}, + .expectation = {.segments = 1, .checkpoints = 2, .resets = 3}, + }, + { + .input = { + .name = "a checkpoint loop's counts add up", + .added = {{.segments = 0, .checkpoints = 1, .resets = 0}, {.segments = 0, .checkpoints = 0, .resets = 1}, {.segments = 0, .checkpoints = 1, .resets = 0}}, + }, + .expectation = {.segments = 0, .checkpoints = 2, .resets = 1}, + }, +}; + +} // namespace + + +void add_tests_StoryLog(UnitTestDatabase& database){ + for (const StoryLogCase& test_case : STORY_LOG_CASES){ + database.add(test_case); + } + for (const StoryCountsCase& test_case : STORY_COUNTS_CASES){ + database.add(test_case); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp index 5653725467..358f606dc6 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp @@ -6,6 +6,7 @@ #include #include +#include "Pokemon_StoryLog.h" #include "Pokemon_StorySegments.h" namespace PokemonAutomation{ @@ -121,13 +122,6 @@ void add_policy_recoveries(Checkpoint& checkpoint, const SegmentPolicy& policy, } } -std::string resets_text(size_t attempts){ - if (attempts == 1){ - return "one-shot"; - } - return std::format("{} reset{}", attempts - 1, attempts == 2 ? "" : "s"); -} - // One row to success, reloading and rebuilding after each failed attempt. // Returns the last attempt's report, or the reload's failure; `run` says // how many attempts and recoveries it took. @@ -148,11 +142,7 @@ CheckpointReport run_row( CheckpointReport result = run_checkpoint(state, checkpoint, log); if (result.completed){ run.passed = true; - say(hooks, std::format( - "[Checkpoint] {}: passed on attempt {} ({}){}", - spec.id, attempt, resets_text(attempt), - run.recoveries == 0 ? "" : std::format(", {} in place", run.recoveries) - )); + say(hooks, checkpoint_pass_line(spec.id, attempt, run.recoveries)); return result; } const bool not_running = result.failure.failure == GAME_NOT_RUNNING; @@ -167,10 +157,7 @@ CheckpointReport run_row( if (attempt >= policy.attempts_per_checkpoint){ return result; } - say(hooks, std::format( - "[Segment] {}: {} failed, reloading for attempt {}/{}", - segment.id, spec.id, attempt + 1, policy.attempts_per_checkpoint - )); + say(hooks, checkpoint_reset_line(segment.id, spec.id, attempt + 1, policy.attempts_per_checkpoint)); report.reloads++; Outcome reloaded = reload(state, hooks); if (!reloaded.succeeded()){ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp index 5309b3e496..07cf478f66 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.cpp @@ -8,6 +8,7 @@ #include #include #include +#include "Pokemon_StoryLog.h" #include "Pokemon_StorySteps.h" namespace PokemonAutomation{ @@ -162,13 +163,13 @@ std::vector lint_story_checkpoint(const StoryCheckpoint& data){ void record_story_stats(AutoStoryStats& stats, const SegmentReport& report){ - stats.m_segment++; + StoryRunCounts counts{.segments = 1, .checkpoints = 0, .resets = report.reloads}; for (const CheckpointRun& run : report.runs){ if (run.passed){ - stats.m_checkpoint++; + counts.checkpoints++; } } - stats.m_reset += report.reloads; + record_story_counts(stats, counts); } diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.cpp new file mode 100644 index 0000000000..8526f48574 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.cpp @@ -0,0 +1,51 @@ +/* Story Range Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryRangeOptions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +StoryRangeOptions::StoryRangeOptions(std::string label, const StringSelectDatabase& checkpoints) + : GroupOption(std::move(label), LockMode::LOCK_WHILE_RUNNING) + , START_CHECKPOINT( + "Start checkpoint:
The program starts from this checkpoint's save.", + checkpoints, + LockMode::LOCK_WHILE_RUNNING, + 0 + ) + , END_CHECKPOINT( + "End checkpoint:
The program stops after this checkpoint.", + checkpoints, + LockMode::LOCK_WHILE_RUNNING, + checkpoints.size() == 0 ? 0 : checkpoints.size() - 1 + ) +{ + PA_ADD_OPTION(START_CHECKPOINT); + PA_ADD_OPTION(END_CHECKPOINT); +} + +size_t StoryRangeOptions::start_index() const{ + return START_CHECKPOINT.index(); +} + +size_t StoryRangeOptions::end_index() const{ + return END_CHECKPOINT.index(); +} + +std::string StoryRangeOptions::check_validity() const{ + if (start_index() > end_index()){ + return "The start checkpoint comes after the end checkpoint."; + } + return GroupOption::check_validity(); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.h new file mode 100644 index 0000000000..26afe4cafd --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.h @@ -0,0 +1,48 @@ +/* Story Range Options + * + * From: https://github.com/PokemonAutomation/ + * + * The start and end checkpoint dropdowns of an AutoStory program, over one + * list of the story's checkpoints, and the check that the start does not + * come after the end. StoryRunOptions (Pokemon_StoryRunOptions.h) is this + * group plus the run policy. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRangeOptions_H +#define PokemonAutomation_Pokemon_StoryRangeOptions_H + +#include +#include "Common/Cpp/Options/GroupOption.h" +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A program shows the group, or adds START_CHECKPOINT and END_CHECKPOINT +// to its own options under its own keys (keeping the keys its saved +// settings already use) and calls check_validity() from its own. +class StoryRangeOptions : public GroupOption{ +public: + // `checkpoints`: the dropdown database (make_story_select_database() + // or story_checkpoint_database()), kept alive by the caller. The + // dropdowns start on its first and last entries. + StoryRangeOptions(std::string label, const StringSelectDatabase& checkpoints); + + // The checkpoints chosen, by index in the database, both inclusive. + size_t start_index() const; + size_t end_index() const; + // "The start checkpoint comes after the end checkpoint." if it does. + virtual std::string check_validity() const override; + +public: + StringSelectOption START_CHECKPOINT; + StringSelectOption END_CHECKPOINT; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp new file mode 100644 index 0000000000..1126620526 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp @@ -0,0 +1,134 @@ +/* Story Range Options Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Pokemon_AutoStorySelect.h" +#include "Pokemon/AutoStory/Pokemon_AutoStory_Tests.h" +#include "Pokemon_StoryRangeOptions.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +// A stand-in for a story checkpoint: only its name is read. +struct NamedCheckpoint{ + std::string label; + std::string name() const{ + return label; + } +}; + +// Two tutorial checkpoints, then three of the main story, as SV's list is +// laid out. +const std::vector>& story_list(){ + static const std::vector> list = []{ + std::vector> ret; + for (const char* label : {"tutorial 0", "tutorial 1", "main 0", "main 1", "main 2"}){ + ret.emplace_back(std::make_unique(NamedCheckpoint{.label = label})); + } + return ret; + }(); + return list; +} + +// The main story's dropdowns: entries 2..4 of the list, slugged 2..4. +const StringSelectDatabase& main_story_database(){ + static const StringSelectDatabase database = make_story_select_database(story_list(), 2, story_list().size()); + return database; +} + +// The start and end set by slug, as saved settings load them; empty +// leaves the default. +struct StoryRangeInput{ + std::string name; + std::string start_slug; + std::string end_slug; +}; + +// The indexes in the dropdown, and whether the range is valid. +struct StoryRangeExpectation{ + size_t start; + size_t end; + bool valid; +}; + +// A range chosen in the main story's dropdowns and what the group reads from it. +struct StoryRangeCase{ + StoryRangeInput input; + StoryRangeExpectation expectation; +}; + +class Test_StoryRange : public UnitTest{ +public: + Test_StoryRange(StoryRangeCase test_case) + : UnitTest("Pokemon::StoryRangeOptions - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + StoryRangeOptions range("Checkpoints", main_story_database()); + if (!m_case.input.start_slug.empty()){ + range.START_CHECKPOINT.set_by_slug(m_case.input.start_slug); + } + if (!m_case.input.end_slug.empty()){ + range.END_CHECKPOINT.set_by_slug(m_case.input.end_slug); + } + const StoryRangeExpectation& expected = m_case.expectation; + if (range.start_index() != expected.start || range.end_index() != expected.end){ + return "Expected indexes " + std::to_string(expected.start) + " to " + std::to_string(expected.end) + + ", got " + std::to_string(range.start_index()) + " to " + std::to_string(range.end_index()); + } + const std::string error = range.check_validity(); + if (error.empty() != expected.valid){ + return expected.valid ? "Expected a valid range, got: " + error : "Expected the range refused."; + } + if (!expected.valid && error != "The start checkpoint comes after the end checkpoint."){ + return "Unexpected message: " + error; + } + return true; + } + +private: + const StoryRangeCase m_case; +}; + +const StoryRangeCase STORY_RANGE_CASES[] = { + { + .input = {.name = "the whole database by default", .start_slug = "", .end_slug = ""}, + .expectation = {.start = 0, .end = 2, .valid = true}, + }, + { + .input = {.name = "slugs are whole-list indexes, indexes are the dropdown's", .start_slug = "3", .end_slug = "4"}, + .expectation = {.start = 1, .end = 2, .valid = true}, + }, + { + .input = {.name = "one checkpoint", .start_slug = "3", .end_slug = "3"}, + .expectation = {.start = 1, .end = 1, .valid = true}, + }, + { + .input = {.name = "a start after the end is refused", .start_slug = "4", .end_slug = "2"}, + .expectation = {.start = 2, .end = 0, .valid = false}, + }, +}; + +} // namespace + + +void add_tests_StoryRangeOptions(UnitTestDatabase& database){ + for (const StoryRangeCase& test_case : STORY_RANGE_CASES){ + database.add(test_case); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp index 5ce0fb7ab0..9f8da731a0 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp @@ -76,19 +76,7 @@ std::string StoryVerifyOptions::check_validity() const{ StoryRunOptions::StoryRunOptions(const StringSelectDatabase& checkpoints) - : GroupOption("Story Run", LockMode::LOCK_WHILE_RUNNING) - , START_CHECKPOINT( - "Start checkpoint:
The program starts from this checkpoint's save.", - checkpoints, - LockMode::LOCK_WHILE_RUNNING, - 0 - ) - , END_CHECKPOINT( - "End checkpoint:
The program stops after this checkpoint.", - checkpoints, - LockMode::LOCK_WHILE_RUNNING, - checkpoints.size() == 0 ? 0 : checkpoints.size() - 1 - ) + : StoryRangeOptions("Story Run", checkpoints) , ATTEMPTS_PER_CHECKPOINT( "Attempts per checkpoint:
A failed checkpoint reloads its save and runs again, up to this many times in all.", LockMode::LOCK_WHILE_RUNNING, @@ -113,8 +101,6 @@ StoryRunOptions::StoryRunOptions(const StringSelectDatabase& checkpoints) Language::English ) { - PA_ADD_OPTION(START_CHECKPOINT); - PA_ADD_OPTION(END_CHECKPOINT); PA_ADD_OPTION(ATTEMPTS_PER_CHECKPOINT); PA_ADD_OPTION(STOP_AT_FIRST_FAILURE); PA_ADD_OPTION(CHECKS); @@ -122,22 +108,15 @@ StoryRunOptions::StoryRunOptions(const StringSelectDatabase& checkpoints) PA_ADD_OPTION(VERIFY); } -size_t StoryRunOptions::start_index() const{ - return START_CHECKPOINT.index(); -} - -size_t StoryRunOptions::end_index() const{ - return END_CHECKPOINT.index(); -} - std::string StoryRunOptions::check_validity() const{ - if (start_index() > end_index()){ - return "The start checkpoint comes after the end checkpoint."; + std::string error = StoryRangeOptions::check_validity(); + if (!error.empty()){ + return error; } if (VERIFY.enabled() && start_index() != end_index()){ return "Verify mode runs one checkpoint: set the end checkpoint to the start checkpoint."; } - return GroupOption::check_validity(); + return error; } SegmentPolicy StoryRunOptions::policy() const{ diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h index f362ce875f..e166c57fd2 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRunOptions.h @@ -3,7 +3,8 @@ * From: https://github.com/PokemonAutomation/ * * The options every AutoStory program shows for where to start and end, how - * hard to try and how much to check: the same group in each game, read into the shared + * hard to try and how much to check: the shared range group + * (Pokemon_StoryRangeOptions.h) plus the run policy, read into the shared * SegmentPolicy (Pokemon/AutoStory/Pokemon_StorySegments.h), the checks * level (Types/Pokemon_StoryChecks.h) and the language the game's steps * read text in. @@ -28,6 +29,7 @@ #include "Pokemon/AutoStory/Pokemon_StorySegments.h" #include "Pokemon/AutoStory/Types/Pokemon_StoryChecks.h" #include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" +#include "Pokemon_StoryRangeOptions.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -83,17 +85,16 @@ class StoryVerifyOptions : public GroupOption{ }; -// Configuration options panel for selecting story checkpoints and execution mode. -class StoryRunOptions : public GroupOption{ +// The range group (START_CHECKPOINT, END_CHECKPOINT, start_index(), +// end_index()) with the run policy added to the same group, so the saved +// settings keep one flat object. +class StoryRunOptions : public StoryRangeOptions{ public: // `checkpoints`: story_checkpoint_database() of the game's story, kept // alive by the caller; the dropdowns start on its first and last. explicit StoryRunOptions(const StringSelectDatabase& checkpoints); - // The checkpoints to run, by index in the database, both inclusive. - size_t start_index() const; - size_t end_index() const; - // "The start checkpoint comes after the end checkpoint." if it does. + // The range's check, then verify mode's: one checkpoint only. virtual std::string check_validity() const override; // The policy these options set. In-place recoveries are the game's to @@ -105,8 +106,6 @@ class StoryRunOptions : public GroupOption{ Language language() const; public: - StringSelectOption START_CHECKPOINT; - StringSelectOption END_CHECKPOINT; SimpleIntegerOption ATTEMPTS_PER_CHECKPOINT; BooleanCheckBoxOption STOP_AT_FIRST_FAILURE; EnumDropdownOption CHECKS; diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 4630157b77..3c8cc0ad01 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1491,6 +1491,9 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Options/Pokemon_NameSelectWidget.h Source/Pokemon/Options/Pokemon_StatsHuntFilter.cpp Source/Pokemon/Options/Pokemon_StatsHuntFilter.h + Source/Pokemon/Options/Pokemon_StoryRangeOptions.cpp + Source/Pokemon/Options/Pokemon_StoryRangeOptions.h + Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp Source/Pokemon/Options/Pokemon_StoryRunOptions.cpp Source/Pokemon/Options/Pokemon_StoryRunOptions.h Source/Pokemon/AutoStory/Pokemon_AutoStorySelect.h @@ -1501,6 +1504,9 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp Source/Pokemon/AutoStory/Pokemon_StoryEvents.h Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryLog.cpp + Source/Pokemon/AutoStory/Pokemon_StoryLog.h + Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp Source/Pokemon/AutoStory/Pokemon_StorySegments.cpp Source/Pokemon/AutoStory/Pokemon_StorySegments.h Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp From 48c10b75c67e1e1c297fb8fdf70fa7cf16e2a134 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 20:49:18 -0800 Subject: [PATCH 39/64] StoryRangeOptions: let a program unlock the end while running SV reads its end checkpoint after each checkpoint and leaves the end dropdown unlocked during a run; the range group now takes that lock mode. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Source/Pokemon/Options/Pokemon_StoryRangeOptions.cpp | 4 ++-- .../Source/Pokemon/Options/Pokemon_StoryRangeOptions.h | 9 +++++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.cpp index 8526f48574..d294e5e386 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.cpp +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.cpp @@ -11,7 +11,7 @@ namespace PokemonAutomation{ namespace Pokemon{ -StoryRangeOptions::StoryRangeOptions(std::string label, const StringSelectDatabase& checkpoints) +StoryRangeOptions::StoryRangeOptions(std::string label, const StringSelectDatabase& checkpoints, LockMode end_lock) : GroupOption(std::move(label), LockMode::LOCK_WHILE_RUNNING) , START_CHECKPOINT( "Start checkpoint:
The program starts from this checkpoint's save.", @@ -22,7 +22,7 @@ StoryRangeOptions::StoryRangeOptions(std::string label, const StringSelectDataba , END_CHECKPOINT( "End checkpoint:
The program stops after this checkpoint.", checkpoints, - LockMode::LOCK_WHILE_RUNNING, + end_lock, checkpoints.size() == 0 ? 0 : checkpoints.size() - 1 ) { diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.h index 26afe4cafd..809f3324d2 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.h +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions.h @@ -27,8 +27,13 @@ class StoryRangeOptions : public GroupOption{ public: // `checkpoints`: the dropdown database (make_story_select_database() // or story_checkpoint_database()), kept alive by the caller. The - // dropdowns start on its first and last entries. - StoryRangeOptions(std::string label, const StringSelectDatabase& checkpoints); + // dropdowns start on its first and last entries. `end_lock`: + // UNLOCK_WHILE_RUNNING for a program that reads the end after each + // checkpoint, so the end can be moved during a run. + StoryRangeOptions( + std::string label, const StringSelectDatabase& checkpoints, + LockMode end_lock = LockMode::LOCK_WHILE_RUNNING + ); // The checkpoints chosen, by index in the database, both inclusive. size_t start_index() const; From c766e871c3e213620f86d4e34d5a8015315ed2c8 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 20:55:12 -0800 Subject: [PATCH 40/64] AutoStory tests: register the story engine suites through one call Keeps the unit test runner's list short as the stacked layers add suites. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../ComputerPrograms_UnitTestRunner.cpp | 9 +-------- .../Pokemon/AutoStory/Pokemon_AutoStory_Tests.h | 12 ++++++++++++ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 9f629691a4..dfbabc0d0d 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -78,14 +78,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_MapData(ret); Pokemon::add_tests_RuntimeMap(ret); Pokemon::add_tests_RouteLog(ret); - Pokemon::add_tests_StoryEvents(ret); - Pokemon::add_tests_StorySegments(ret); - Pokemon::add_tests_StorySteps(ret); - Pokemon::add_tests_StoryStepJson(ret); - Pokemon::add_tests_StoryArgs(ret); - Pokemon::add_tests_AuthoredCheckpointJson(ret); - Pokemon::add_tests_StoryLog(ret); - Pokemon::add_tests_StoryRangeOptions(ret); + Pokemon::add_tests_AutoStory(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); NintendoSwitch::add_tests_UpdatePopupDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 0c3e2218da..24af2d8db9 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -32,6 +32,18 @@ void add_tests_StoryLog(UnitTestDatabase& database); // Registers unit tests for the shared start/end checkpoint range options. void add_tests_StoryRangeOptions(UnitTestDatabase& database); +// Registers every suite above, for the unit test runner. +inline void add_tests_AutoStory(UnitTestDatabase& database){ + add_tests_StoryEvents(database); + add_tests_StorySegments(database); + add_tests_StorySteps(database); + add_tests_StoryStepJson(database); + add_tests_StoryArgs(database); + add_tests_AuthoredCheckpointJson(database); + add_tests_StoryLog(database); + add_tests_StoryRangeOptions(database); +} + } // namespace Pokemon From c326739faf38a9737e419c93c7da5c36bbf76f75 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 21:07:54 -0800 Subject: [PATCH 41/64] FRLG AutoStory: build against the core's executor interface The core's StoryStepExecutor no longer holds the checks level or the language, nor one virtual per kind. The program sets the language on the StoryEnv its actions read; the storage test executor overrides run(). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Programs/AutoStory/PokemonFRLG_AutoStory.cpp | 6 ++---- .../AutoStory/PokemonFRLG_AutoStoryCapture_Tests.cpp | 6 ++++-- .../AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp | 2 -- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index 8f9fb0623a..a7b676ef5e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -252,10 +252,9 @@ void verify_story_checkpoint( const std::vector& checkpoints = story_checkpoints(); const StoryCheckpoint& checkpoint = checkpoints[run.start_index()]; StoryEnv story = story_env(env, context, checkpoint, run.checks(), false); + story.language = run.language(); load_verify_save(env, context, story, checkpoint); StoryExecutor executor(story); - executor.set_checks(run.checks()); - executor.set_language(run.language()); Pokemon::Segment segment = make_story_segment(checkpoints, executor); Pokemon::SegmentHooks hooks = story_hooks(env, story); @@ -665,12 +664,11 @@ void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContex plan = plan_story_run(checkpoints, first, last, handoffs); } StoryEnv story = story_env(env, context, checkpoints[first], RUN.checks(), KEEP_START_FRAME); + story.language = RUN.language(); story.player_name = player_name; const bool at_gift_rng = plan.stop == StoryHandoff::GIFT_RNG && plan.rows.empty(); prepare_start(env, context, checkpoints, first, story, at_gift_rng); StoryExecutor executor(story); - executor.set_checks(RUN.checks()); - executor.set_language(RUN.language()); const std::optional done_through = at_gift_rng ? run_from_gift_rng_save(env, context, story, executor, first) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture_Tests.cpp index f3fa9e4161..39310cd804 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCapture_Tests.cpp @@ -436,8 +436,10 @@ class StorageExecutor : public Pokemon::StoryStepExecutor{ FakeCaptureGame capture; IdlePc pc; -protected: - virtual Pokemon::Outcome game(Pokemon::RunState&, const StoryStep& step) override{ + virtual Pokemon::Outcome run(Pokemon::RunState&, const StoryStep& step) override{ + if (step.kind != Pokemon::StoryStepKind::GAME){ + return Pokemon::unsupported_step(step); + } const std::optional outcome = run_storage_game_step(logger, nullptr, step, capture, pc); return outcome ? *outcome : Pokemon::unsupported_step(step); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp index a874f2e22b..a11981cf33 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp @@ -112,9 +112,7 @@ struct Simulation{ std::vector> saves; Pokemon::SegmentPolicy policy; - // A language no reader supports, so a step that needed text would show. Pokemon::SegmentReport run(const Pokemon::SegmentRange& range){ - game.set_language(Language::Japanese); Pokemon::Segment segment; segment.id = "00"; for (const StoryCheckpoint& data : rows){ From 42e98c56ff60552eac3894d8573b1b0ac1119791 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 21:36:48 -0800 Subject: [PATCH 42/64] Pokemon navigation: write a route plan on one log line route_plan_line() put each planned leg on its own line under "plan from X:", so one log record wrapped across several lines while every other route line is one. The legs now follow on the same line, separated by "; ", in the same text route_leg_line() writes for them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Source/Pokemon/Navigation/Pokemon_RouteLog.cpp | 11 ++++++++--- .../Source/Pokemon/Navigation/Pokemon_RouteLog.h | 8 ++++---- .../Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp | 8 ++++---- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp index 29a51c94ea..b5d8912010 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp @@ -53,16 +53,21 @@ const char* basis_name(EndBasis basis){ } +// " to ", as the plan and the leg lines both write a leg. +static std::string planned_leg_text(const PlannedRouteLeg& leg){ + return to_string(leg.leg) + " to " + describe(leg.after); +} + std::string route_plan_line(const std::string& label, const std::vector& from, const std::vector& legs){ std::string text = label + ": plan from " + describe(from) + ":"; - for (const PlannedRouteLeg& leg : legs){ - text += "\n " + to_string(leg.leg) + " to " + describe(leg.after); + for (size_t i = 0; i < legs.size(); i++){ + text += (i == 0 ? " " : "; ") + planned_leg_text(legs[i]); } return text; } std::string route_leg_line(size_t number, size_t count, const PlannedRouteLeg& leg){ - return std::format("Leg {}/{}: {} to {}", number, count, to_string(leg.leg), describe(leg.after)); + return std::format("Leg {}/{}: {}", number, count, planned_leg_text(leg)); } std::string route_leg_end_line( diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h index 07eb571f20..2b67f169d9 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h @@ -7,9 +7,7 @@ * routes from it. These are BDSP AutoStory's route lines, lifted from * PokemonBDSP_AutoStory_RouteWalk.cpp, with what the other games need: * - * [Route] To the grass: plan from Route 202 (15, 25), Route 202 (16, 25): - * east 15 (to wall) to Route 202 (23, 25), Route 202 (30, 26) - * north 5 (to wall) to Route 202 (23, 24) + * [Route] To the grass: plan from Route 202 (15, 25), Route 202 (16, 25): east 15 (to wall) to Route 202 (23, 25), Route 202 (30, 26); north 5 (to wall) to Route 202 (23, 24) * [Route] Leg 1/2: east 15 (to wall) to Route 202 (23, 25), Route 202 (30, 26) * [Route] To the grass: east 15 (to wall): ended at Route 202 (23, 25) (walked). * [Route] To the grass: north 5 (to wall): stopped early after about 2 tiles, at Route 202 (23, 23); planning again. @@ -93,7 +91,9 @@ enum class EndBasis{ const char* basis_name(EndBasis basis); -// "