From 445e9530038b5f805b6c3d6cf39a3bbea55e3093 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 02:03:16 -0800 Subject: [PATCH 001/166] BDSP AutoStory sim: a grid simulation of the walker, and story rows on it GridSim moves a player on the story maps as measured on the console: short D-pad taps only turn, 160 ms steps a tile, holds walk to the wall, a stick tap moves part of a tile and the D-pad keeps that offset, doors warp only from their column, people block and trainers' sight lines stop the walk. GridSimRouteIO runs the route walker on it. The executor's walking steps (ROUTE, LEGS, STEP, TALK, MASH) move into StoryWalkSteps on a StoryStepIO, so the story sim tests run rows 00.04 to 00.05c with the program's own steps on the simulation. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 4 + .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 418 ++++++++++++++++++ .../PokemonBDSP_AutoStory_GridSim_Tests.h | 28 ++ .../PokemonBDSP_AutoStory_StoryExecutor.cpp | 274 +----------- .../PokemonBDSP_AutoStory_StoryExecutor.h | 15 +- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 392 ++++++++++++++++ .../PokemonBDSP_AutoStory_StorySim_Tests.h | 28 ++ .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 146 ++++++ .../PokemonBDSP_AutoStory_StoryStepIO.h | 78 ++++ .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 250 +++++++++++ .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 71 +++ .../Utils/PokemonBDSP_AutoStory_GridSim.cpp | 361 +++++++++++++++ .../Utils/PokemonBDSP_AutoStory_GridSim.h | 181 ++++++++ SerialPrograms/cmake/SourceFiles.cmake | 10 + 14 files changed, 1984 insertions(+), 272 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.h diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index c4f3752ab1..621d4421ef 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -6,12 +6,14 @@ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Actions_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h" @@ -34,6 +36,8 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_StoryTable(database); add_tests_AutoStory_Walk(database); add_tests_AutoStory_PlannedRoute(database); + add_tests_AutoStory_GridSim(database); + add_tests_AutoStory_StorySim(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.cpp new file mode 100644 index 0000000000..8d5d49b517 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -0,0 +1,418 @@ +/* BDSP AutoStory Grid Simulation Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The grid simulation's moves against the console's measurements, then the + * route walker (walk_route()) on it: every route of the story table from + * where the table has the player, and the routes to doors that a turn on + * the stick missed on the console (r49, r57). + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Data/PokemonBDSP_AutoStory_Maps.h" +#include "Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "Utils/PokemonBDSP_AutoStory_GridSim.h" +#include "Utils/PokemonBDSP_AutoStory_PlannedRoute.h" +#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP_AutoStory_GridSim_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::Pose; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + + +StoryWorld make_world(const std::vector& rows){ + Pokemon::MapData map; + map.name = "Test"; + map.tiles = Pokemon::Grid{(int)rows[0].size(), (int)rows.size(), {}}; + for (const std::string& row : rows){ + for (char glyph : row){ + map.tiles.cells.push_back(*Pokemon::tile_from_glyph(glyph)); + } + } + StoryWorld world; + world.add("Test", map, {0, 0}); + return world; +} + +SimPos at_tile(int x, int y, int part_x = 0, int part_y = 0){ + return {x * SIM_TILE + part_x, y * SIM_TILE + part_y}; +} + + +// One input to the simulation. +enum class SimInputKind{ + DPAD, + STICK, + HOLD, +}; +struct SimInput{ + SimInputKind kind; + Direction direction; + Milliseconds time; +}; + +// Inputs from `start`, and where the player must end and how the last +// input ended. +struct MoveCase{ + std::string name; + TilePos start; + std::vector inputs; + SimPos end; + SimStop stop; +}; + +SimMove apply(GridSim& sim, const SimInput& input){ + switch (input.kind){ + case SimInputKind::DPAD: + return sim.tap(input.direction, input.time, false); + case SimInputKind::STICK: + return sim.tap(input.direction, input.time, true); + case SimInputKind::HOLD: + return sim.hold(input.direction, input.time, SimPace::WALK); + } + return {}; +} + +// A room with a door in row 3 at x 3, a ledge south at x 7, someone +// standing at (5, 1), and a trainer east of row 2 who looks west 3 tiles. +UnitTestResult test_moves(Logger&){ + StoryWorld world = make_world({ + "#########", + "#.......#", + "#.......#", + "###D###v#", + "#.......#", + "#########", + }); + world.block({5, 1}); + const SimWorld setup{.world = &world, .trainers = {{.name = "watcher", .pos = {8, 2}, .facing = Direction::WEST, .range = 3}}}; + constexpr Direction EAST = Direction::EAST; + constexpr Direction SOUTH = Direction::SOUTH; + constexpr Direction WEST = Direction::WEST; + const std::vector cases{ + {.name = "a 50 ms D-pad tap only turns", .start = {2, 1}, .inputs = {{SimInputKind::DPAD, EAST, 50ms}}, .end = at_tile(2, 1), .stop = SimStop::DONE}, + {.name = "a 160 ms D-pad tap steps a tile", .start = {2, 1}, .inputs = {{SimInputKind::DPAD, EAST, 160ms}}, .end = at_tile(3, 1), .stop = SimStop::DONE}, + {.name = "a 100 ms stick tap steps 0.6 tile across", .start = {2, 1}, .inputs = {{SimInputKind::STICK, EAST, 100ms}}, .end = at_tile(2, 1, 625), .stop = SimStop::DONE}, + {.name = "a 100 ms stick tap steps 0.4 tile down", .start = {2, 1}, .inputs = {{SimInputKind::STICK, SOUTH, 100ms}}, .end = at_tile(2, 1, 0, 416), .stop = SimStop::DONE}, + {.name = "the D-pad keeps a stick tap's offset", .start = {2, 1}, + .inputs = {{SimInputKind::STICK, EAST, 100ms}, {SimInputKind::DPAD, EAST, 160ms}}, .end = at_tile(3, 1, 625), .stop = SimStop::DONE}, + {.name = "a held walk stops at someone standing", .start = {2, 1}, .inputs = {{SimInputKind::HOLD, EAST, 5000ms}}, .end = at_tile(4, 1), .stop = SimStop::BLOCKED}, + {.name = "a door warps from its column", .start = {3, 2}, .inputs = {{SimInputKind::HOLD, SOUTH, 3000ms}}, .end = at_tile(3, 3), .stop = SimStop::WARP}, + {.name = "part of a tile off the door's column, the frame stops us", .start = {3, 2}, + .inputs = {{SimInputKind::STICK, WEST, 100ms}, {SimInputKind::HOLD, SOUTH, 3000ms}}, .end = at_tile(2, 2, 375), .stop = SimStop::BLOCKED}, + {.name = "a trainer's sight stops a walk", .start = {1, 2}, .inputs = {{SimInputKind::HOLD, EAST, 5000ms}}, .end = at_tile(5, 2), .stop = SimStop::DIALOG}, + {.name = "a ledge hops two tiles", .start = {7, 2}, .inputs = {{SimInputKind::DPAD, SOUTH, 160ms}}, .end = at_tile(7, 4), .stop = SimStop::DONE}, + }; + for (const MoveCase& item : cases){ + GridSim sim(setup, item.start, Direction::NORTH, false); + SimMove last; + for (const SimInput& input : item.inputs){ + last = apply(sim, input); + } + if (sim.player().pos != item.end || last.stop != item.stop){ + return std::format("{}: expected {} ({}), got {} ({}).", item.name, to_string(item.end), sim_stop_name(item.stop), + to_string(sim.player().pos), sim_stop_name(last.stop)); + } + } + return true; +} + + +// A turn on the stick, as before r49: each turn tap of the D-pad becomes a +// 100 ms stick tap, which moves the player part of a tile. +class StickTurnIO : public RouteIO{ +public: + explicit StickTurnIO(RouteIO& io) + : m_io(io) + {} + virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override{ + return m_io.walk_to_wall(walk); + } + virtual WalkResult walk_taps(Direction direction, size_t tiles, const std::string& label) override{ + return m_io.walk_taps(direction, tiles, label); + } + virtual void press(const RouteInput& input) override{ + if (input.kind != RouteInputKind::DPAD || input.hold >= 100ms){ + m_io.press(input); + return; + } + RouteInput stick = input; + stick.kind = RouteInputKind::STICK; + stick.hold = 100ms; + m_io.press(stick); + } + virtual bool dialog_within(Milliseconds wait, Color color) override{ + return m_io.dialog_within(wait, color); + } + virtual bool holding_against_wall(Direction direction, const std::string& label) override{ + return m_io.holding_against_wall(direction, label); + } + virtual void look(const std::function& at) override{ + m_io.look(at); + } + virtual void note(const std::string& text, RouteNote kind) override{ + m_io.note(text, kind); + } + +private: + RouteIO& m_io; +}; + + +// A route walked on the simulation: where the walker believes it ended, +// where the player is, and why it failed. +struct SimWalk{ + std::vector believed; + SimPos actual; + std::string failure; + std::vector notes; +}; + +// One route to walk: on `world`, from `from` (the walker's belief) with the +// player on `start`, to any of `targets`. +struct SimRoute{ + std::string label; + const StoryWorld* world; + std::vector from; + TilePos start; + std::vector targets; + RobustPlanCosts costs; + bool can_run; +}; + +SimWalk walk_on_sim(const SimRoute& route, bool stick_turns){ + SimWalk out; + GridSim sim({.world = route.world, .trainers = story_trainers(*route.world)}, route.start, Direction::NORTH, route.can_run); + GridSimRouteIO sim_io(sim, out.notes); + StickTurnIO stick_io(sim_io); + RouteIO& io = stick_turns ? static_cast(stick_io) : sim_io; + RouteTrainers trainers{story_trainers(*route.world), [&sim](const std::string&){ sim.end_dialogue(); }}; + const std::vector& targets = route.targets; + try{ + out.believed = walk_route(io, *route.world, route.from, trainers, { + .goal = [&targets](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }, + .label = route.label, + .avoid = {}, + .costs = route.costs, + .speed = route.can_run ? MoveSpeed::RUN : MoveSpeed::WALK, + }); + }catch (const GridSimFailure& e){ + out.failure = e.message; + } + out.actual = sim.player().pos; + return out; +} + +// Why a walk did not end where it should: on the grid, on one of the +// targets, and on a tile the walker believes. Empty if it did. +std::string walk_error(const SimRoute& route, const SimWalk& walk){ + const auto has = [](const std::vector& tiles, const TilePos& pos){ + return std::find(tiles.begin(), tiles.end(), pos) != tiles.end(); + }; + const TilePos tile = nearest_tile(walk.actual); + if (!walk.failure.empty()){ + return std::format("{} from {}: failed at {}: {}", route.label, describe(*route.world, route.start), + to_string(walk.actual), walk.failure); + } + if (!on_grid(walk.actual) || !has(route.targets, tile) || !has(walk.believed, tile)){ + return std::format("{} from {}: ended at {} ({}), off the grid or off the target.", route.label, + describe(*route.world, route.start), to_string(walk.actual), describe(*route.world, tile)); + } + return ""; +} + + +std::vector world_tiles(const StoryWorld& world, const Pose& pose){ + std::vector tiles; + for (const TilePos& pos : Pokemon::tiles_of(pose)){ + tiles.push_back(story_to_world(world, pose.map, pos)); + } + return tiles; +} + +// Where the table has the player after `step`, from `at`: a route's +// target, a walk's last tile, a step's next tile; a scene or an event's +// end is the table's pose_after, or unknown. +std::optional pose_after_step(const std::optional& at, const StoryStep& step){ + std::optional next; + if (step.kind == StoryStepKind::ROUTE){ + next = step.target; + }else if (at && step.kind == StoryStepKind::STEP){ + std::vector tiles; + for (const TilePos& pos : Pokemon::tiles_of(*at)){ + tiles.push_back(pos.next(step.direction)); + } + next = Pokemon::tile_pose(at->map, tiles, step.direction); + }else if (at && step.kind == StoryStepKind::LEGS && step.variant.empty()){ + std::vector tiles = Pokemon::tiles_of(*at); + for (const Pokemon::StoryLeg& leg : step.legs){ + for (TilePos& pos : tiles){ + for (int i = 0; i < leg.tiles; i++){ + pos = pos.next(leg.direction); + } + } + } + next = Pokemon::tile_pose(at->map, tiles, step.legs.back().direction); + }else if (step.kind != StoryStepKind::GAME && step.kind != StoryStepKind::SHOP && + step.kind != StoryStepKind::MASH && step.kind != StoryStepKind::LEGS + ){ + next = at; + } + return step.pose_after ? step.pose_after : next; +} + +// Every ROUTE step of the table that starts from a known pose, from its +// first and its last tile, at the pace StoryExecutor walks it. +std::vector table_routes(){ + std::vector routes; + for (const StoryCheckpoint& row : story_checkpoints()){ + std::optional at = row.start; + bool shoes = row.id > std::string(RUNNING_SHOES_ROW); + for (const StoryStep& step : row.steps){ + const StoryWorld* world = at && step.kind == StoryStepKind::ROUTE ? story_plan_world(at->map, step.target->map) : nullptr; + const std::vector from = world ? world_tiles(*world, *at) : std::vector{}; + std::vector starts; + if (!from.empty()){ + starts.push_back(from.front()); + } + if (from.size() > 1){ + starts.push_back(from.back()); + } + for (const TilePos& start : starts){ + routes.push_back({.label = row.id + " " + step.name, .world = world, .from = from, .start = start, + .targets = world_tiles(*world, *step.target), .costs = *story_route_costs(step.variant), .can_run = shoes}); + } + at = pose_after_step(at, step); + shoes = shoes || (row.id == RUNNING_SHOES_ROW && step.name == RUNNING_SHOES_STEP); + } + } + return routes; +} + +UnitTestResult test_table_routes(Logger& logger){ + std::string errors; + size_t walked = 0; + for (const SimRoute& route : table_routes()){ + const SimWalk walk = walk_on_sim(route, false); + walked++; + const std::string error = walk_error(route, walk); + logger.log(std::format("{} from {}: {}", route.label, describe(*route.world, route.start), error.empty() ? "on target" : error)); + if (!error.empty()){ + errors += "\n " + error; + } + } + if (walked < 10){ + return std::format("Expected the table's routes; found {}.", walked); + } + return errors.empty() ? UnitTestResult(true) : UnitTestResult("Routes that did not end on their target:" + errors); +} + + +// A route to the tile below a door, then a walk north into it. +struct DoorRoute{ + std::string name; + std::string map; + TilePos from; + std::string door; +}; + +// Whether the route ends below the door and a walk north goes in. +std::string door_route_error(const DoorRoute& item, bool stick_turns){ + const StoryWorld& world = *story_plan_world(item.map, item.map); + const TilePos from = story_to_world(world, item.map, item.from); + const TilePos below = story_to_world(world, item.map, map_point(item.map, item.door).next(Direction::SOUTH)); + const SimRoute route{.label = item.name, .world = &world, .from = {from}, .start = from, .targets = {below}, + .costs = town_plan_costs(), .can_run = true}; + const SimWalk walk = walk_on_sim(route, stick_turns); + const std::string error = walk_error(route, walk); + if (!error.empty()){ + return error; + } + GridSim sim({.world = &world}, below, Direction::NORTH, true); + if (sim.hold(Direction::NORTH, 3000ms, SimPace::RUN).stop != SimStop::WARP){ + return item.name + ": the walk north did not go through the door."; + } + return ""; +} + +// r49 put us a tile west of Sandgem's Center door after a stick "turn", +// and r57 walked the Jubilife School's row a column short: a turn tap on +// the stick moves part of a tile, and every D-pad tap after keeps it. With +// D-pad turns both routes end below their doors; with stick turns they +// must miss, or the simulation would not have caught it. +UnitTestResult test_door_routes(Logger& logger){ + const std::vector routes{ + {.name = "Sandgem: below the Center's door", .map = "SandgemTown", .from = map_point("SandgemTown", "front_row_east_end"), + .door = "pokemon_center_door"}, + {.name = "Jubilife: below the School's door", .map = "JubilifeCity", .from = map_point("JubilifeCity", "pokemon_center_door").next(Direction::SOUTH), + .door = "trainers_school_door"}, + }; + for (const DoorRoute& item : routes){ + const std::string dpad = door_route_error(item, false); + if (!dpad.empty()){ + return "D-pad turns: " + dpad; + } + const std::string stick = door_route_error(item, true); + logger.log(item.name + ", stick turns: " + stick); + if (stick.empty()){ + return item.name + ": with turns on the stick, expected the route to miss the door; it went in."; + } + } + return true; +} + + +class Test_GridSim : public UnitTest{ +public: + Test_GridSim(std::string name, std::function body) + : UnitTest("PokemonBDSP::AutoStory - Grid sim: " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + +} + + +void add_tests_AutoStory_GridSim(UnitTestDatabase& database){ + database.add("taps, holds, stick offsets, doors, people and trainers as measured", test_moves); + database.add("the table's routes end on their targets", test_table_routes); + database.add("a stick-tap turn misses the Sandgem Center and Jubilife School doors", test_door_routes); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.h new file mode 100644 index 0000000000..16c74d7cce --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.h @@ -0,0 +1,28 @@ +/* BDSP AutoStory Grid Simulation Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_GridSim_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_GridSim_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// The grid simulation (Utils/PokemonBDSP_AutoStory_GridSim.h): the moves +// measured on the console, the story table's routes walked by the route +// walker on it, and walks that missed doors on the console missing them here. +void add_tests_AutoStory_GridSim(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp index d3cdd08b85..cdaa6f0865 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp @@ -96,24 +96,19 @@ void save_failure_screenshot(VideoStream& stream, size_t attempt){ StoryExecutor::StoryExecutor(StoryEnv& env) : m_env(env) + , m_io(env.env.console, env.context) + , m_walks(m_io) {} void StoryExecutor::begin_attempt(const Pokemon::StoryCheckpoint& data){ m_checkpoint = data.id; - // A row starts from its save: after the shoes' row, the save has them. - m_can_run = data.id > std::string(RUNNING_SHOES_ROW); - const StoryWorld* south = story_plan_world("Route202", "Route202"); - m_trainers = south ? story_trainers(*south) : std::vector{}; + m_walks.begin_attempt(data.id); } Outcome StoryExecutor::run(RunState& state, const StoryStep& step){ stream().log(std::format("[{}] {} {}: {}", m_checkpoint, Pokemon::story_step_kind_name(step.kind), step.name, step.why), COLOR_BLUE); try{ - Outcome outcome = run_guarded(state, step); - if (outcome.succeeded() && m_checkpoint == RUNNING_SHOES_ROW && step.name == RUNNING_SHOES_STEP){ - m_can_run = true; - } - return outcome; + return run_guarded(state, step); }catch (OperationFailedException& e){ if (m_stop_rows.contains(m_checkpoint)){ throw; @@ -135,49 +130,6 @@ Outcome StoryExecutor::run_guarded(RunState& state, const StoryStep& step){ return Pokemon::StoryStepExecutor::run(state, step); } -Pose StoryExecutor::walk_to(const Pose& from, const Pose& goal, const StoryStep& step){ - const StoryWorld* maps = story_plan_world(from.map, goal.map); - if (maps == nullptr){ - fail_step(stream(), std::format("{}: no maps join {} and {}.", step.name, from.map, goal.map)); - } - const std::optional costs = story_route_costs(step.variant); - if (!costs){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown route costs: " + step.variant); - } - std::vector start; - for (const TilePos& pos : Pokemon::tiles_of(from)){ - start.push_back(story_to_world(*maps, from.map, pos)); - } - std::vector targets; - for (const TilePos& pos : Pokemon::tiles_of(goal)){ - targets.push_back(story_to_world(*maps, goal.map, pos)); - } - // Only Route 202's trainers are known; the ones fought stay off - // m_trainers until the next attempt. - const bool south = maps == story_plan_world("Route202", "Route202"); - RouteTrainers trainers{ - south ? m_trainers : std::vector{}, - [this](const std::string& trainer){ fight_route_trainer(stream(), context(), trainer); } - }; - const RouteWalkPlan plan{ - [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }, - label_of(step), {}, *costs, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK - }; - const std::vector at = walk_route(stream(), context(), run_from_wild_battle, *maps, start, trainers, plan); - if (south){ - m_trainers = std::move(trainers.sights); - } - std::vector local; - for (const TilePos& pos : at){ - const std::optional tile = story_to_local(*maps, goal.map, pos); - if (!tile){ - fail_step(stream(), std::format("{}: the walk ended off {}.", step.name, goal.map)); - } - local.push_back(*tile); - } - return Pokemon::tile_pose(goal.map, local, Pokemon::facing_of(goal)); -} - Outcome StoryExecutor::new_game(RunState&, const StoryStep&){ play_new_game_intro(m_env.env, context(), m_env.player_name); return Pokemon::outcome_ok(); @@ -190,213 +142,19 @@ Outcome StoryExecutor::options(RunState&, const StoryStep&){ } Outcome StoryExecutor::route(RunState& state, const StoryStep& step){ - if (Pokemon::tiles_of(state.pose).empty()){ - return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); - } - return Pokemon::outcome_ok(walk_to(state.pose, *step.target, step)); -} - -namespace{ - -// A LEGS step "to_dialogue": taps its one leg until a dialogue starts on the -// way, wherever it starts (Dawn's at Sandgem's edge, r35/r36: an exact tile -// and banner raced her scene). The scene's lines are the next step's. -Outcome leg_to_dialogue(VideoStream& stream, ProControllerContext& context, const StoryStep& step, const std::string& checkpoint){ - const Pokemon::StoryLeg& leg = step.legs.front(); - route_turn(stream, context, leg.direction); - const auto [x, y] = dpad_of(leg.direction); - const WalkResult walk = walk_tiles_dpad(stream, context, run_from_wild_battle, {x, y}, (size_t)leg.tiles, step.name); - stream.log(std::format("[{}] {}: taps {} to a dialogue: {} tiles, {}.", checkpoint, step.name, direction_name(leg.direction), walk.moved_chunks, walk_stop_name(walk.stop))); - if (walk.stop == WalkStop::DIALOG){ - return Pokemon::outcome_ok(); - } - // A scene can lock us before its first line: Dawn walks over first (r37). - ShortDialogWatcher dialog(COLOR_CYAN); - if (walk.stop == WalkStop::BLOCKED && wait_until(stream, context, 10000ms, {{dialog}}) == 0){ - return Pokemon::outcome_ok(); - } - return Pokemon::outcome_failed("no_dialogue", step.name); -} - -// A LEGS step "to_map": runs its one leg until the location banner of -// pose_after's map shows, wherever it shows. A straight run along an open -// row needs no tile count (r41, r42: Sandgem's row 11 took us into the lab). -Outcome leg_to_map(VideoStream& stream, ProControllerContext& context, const StoryStep& step, const std::string& checkpoint){ - const Pokemon::StoryLeg& leg = step.legs.front(); - const std::string map = step.pose_after ? step.pose_after->map : ""; - route_turn(stream, context, leg.direction); - const auto [x, y] = dpad_of(leg.direction); - const WalkResult walk = walk_until_dpad(stream, context, run_from_wild_battle, {x, y}, - Milliseconds(250) * leg.tiles + 2000ms, step.name, { - .arrived = [&](const ImageViewRGB32& screen){ return location_banner_matches(read_location_banner(screen), map); }, - .pace = DpadPace::RUN, - }); - stream.log(std::format("[{}] {}: ran {} to {}'s banner: {}.", checkpoint, step.name, direction_name(leg.direction), map, walk_stop_name(walk.stop))); - return walk.stop == WalkStop::ARRIVED ? Pokemon::outcome_ok() : Pokemon::outcome_failed("no_banner", map); -} - + return m_walks.route(state, step); } Outcome StoryExecutor::legs(RunState& state, const StoryStep& step){ - if (step.variant == "to_wall"){ - for (const Pokemon::StoryLeg& leg : step.legs){ - walk_until_stopped(stream(), context(), leg.direction, (size_t)leg.tiles, label_of(step)); - } - return Pokemon::outcome_ok(); - } - if (step.variant == "to_dialogue"){ - return leg_to_dialogue(stream(), context(), step, m_checkpoint); - } - if (step.variant == "to_map"){ - return leg_to_map(stream(), context(), step, m_checkpoint); - } - const bool one_short_ok = step.variant == "one_short_ok"; - if (!one_short_ok && !step.variant.empty()){ - return Pokemon::outcome_failed("unknown_variant", step.variant); - } - std::vector at = Pokemon::tiles_of(state.pose); - for (const Pokemon::StoryLeg& leg : step.legs){ - // Facing another way, a tap only turns (r256): turn first. - route_turn(stream(), context(), leg.direction); - const auto [x, y] = dpad_of(leg.direction); - const size_t tiles = (size_t)leg.tiles; - const WalkResult walk = walk_tiles_dpad(stream(), context(), run_from_wild_battle, {x, y}, tiles, step.name); - stream().log(std::format("[{}] {}: taps {} moved {} of {} tiles.", m_checkpoint, step.name, direction_name(leg.direction), walk.moved_chunks, tiles)); - if (walk.moved_chunks + (one_short_ok ? 1 : 0) < tiles){ - return Pokemon::outcome_failed("short_leg", std::format("{} {} moved {}", direction_name(leg.direction), tiles, walk.moved_chunks)); - } - // Where we may be: the end, or a tile short of it. - std::vector next; - for (const TilePos& start : at){ - TilePos end = start; - for (size_t i = 0; i < tiles; i++){ - if (one_short_ok && i + 1 == tiles){ - next.push_back(end); - } - end = end.next(leg.direction); - } - next.push_back(end); - } - at = std::move(next); - } - return Pokemon::outcome_ok(Pokemon::tile_pose(state.pose.map, at, step.legs.back().direction)); -} - -namespace{ - -// One rule for scenes and map changes: v2's long B mashes, with an end -// check. Press through the text, and keep pressing B while the screen is -// quiet: a scene can pause while someone walks off (Dawn and Barry after -// Rowan leaves, r23), fade dimly, not to black, to another map (r25), or -// wait on a box the detector misses (r26). B never starts a talk on the -// overworld. Done once the overworld has shown, with no text and a still -// screen, for 5 s of presses: after r31's fade home a scripted walk-in ran -// 5 s with no text before Mom spoke. -// -// A step or scene that ends on another map (`fade`) must fade on the way, -// and only the quiet after the fade counts: r30's scene went quiet for 5 s -// before the fade home, and r28 "went out" a tile beside the door and -// walked a whole route in the house. No fade is a map mismatch. -constexpr double FADE_DARKNESS = 40; // brightness 0 to 255; r24's dim fade home goes darker -void settle(VideoStream& stream, ProControllerContext& context, Button button, const std::string& label, bool fade){ - const WallClock none = WallClock::max(); - const WallClock deadline = current_time() + 120s; - ShortDialogDetector dialog; - OverworldDetector overworld; - WallClock quiet_since = none; - double darkest = 255; - VideoSnapshot previous; - while (current_time() < deadline){ - context.wait_for_all_requests(); - const auto frame = stream.video().snapshot(); - const WallClock now = current_time(); - if (frame){ - darkest = std::min(darkest, image_average(*frame.frame).sum() / 3); - } - const bool talking = frame && dialog.detect(frame); - const bool still = frame && previous && walk_screen_change(*previous.frame, *frame.frame) < WALK_TAP_BLOCKED_CHANGE; - previous = frame; - if (!talking && still && overworld.detect(frame) && (!fade || darkest < FADE_DARKNESS)){ - quiet_since = quiet_since == none ? now : quiet_since; - if (now - quiet_since >= 5000ms){ - stream.log(std::format("[Story] {}: settled; darkest frame {:.0f}.", label, darkest)); - return; - } - }else{ - quiet_since = none; - } - pbf_press_button(context, talking ? button : BUTTON_B, 80ms, 1200ms); - } - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - fade && darkest >= FADE_DARKNESS - ? label + ": no fade within 120 s, so we are not where the step goes (map mismatch)." - : label + ": not back on a quiet overworld within 120 s.", - stream); -} - -} - -namespace{ - -// Holds the D-pad toward a door (with B after the shoes) until the screen goes -// dark or a line shows, up to 12 s. Returns whether it went dark. A line -// stops it: holding on under Mom's "Oh, Kosmos!" wasted 12 s (r45). The walker's black-screen watch -// missed the lab's fade into Sandgem (r44, "dialog"), and settle's samples -// 1.3 s apart can fall either side of it, so watch at settle's own darkness. -bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction direction, bool run){ - const DpadPosition dpad = - direction == Direction::NORTH ? DPAD_UP : - direction == Direction::SOUTH ? DPAD_DOWN : - direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; - BlackScreenWatcher dark(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, 3 * FADE_DARKNESS, 60); - ShortDialogWatcher dialog(COLOR_YELLOW); - const int ret = run_until(stream, context, [&](ProControllerContext& context){ - if (run){ - ssf_press_button(context, BUTTON_B, 0ms, 12000ms, 0ms); - } - pbf_press_dpad(context, dpad, 12000ms, 0ms); - }, {{dark}, {dialog}}); - return ret == 0; -} - + return m_walks.legs(state, step); } Outcome StoryExecutor::step(RunState& state, const StoryStep& step){ - route_turn(stream(), context(), step.direction); - // A step through a door: walk (or run) on until the screen goes dark, - // from next to the door or from anywhere in its line (r43: tapping 8 tiles - // down the lab took 7 s), then settle for any scene on arrival (Mom's, - // 00.01; Dawn's tour, 00.04). Without the fade, settle must see it itself - // (r33 was outside, "no fade"). - if (step.pose_after && step.pose_after->map != state.pose.map){ - const bool faded = run_into_door(stream(), context(), step.direction, m_can_run); - stream().log(std::format("[{}] {}: {} through the door: {}.", m_checkpoint, step.name, direction_name(step.direction), faded ? "faded" : "no fade yet")); - settle(stream(), context(), BUTTON_B, label_of(step), !faded); - return Pokemon::outcome_ok(); - } - const auto [x, y] = dpad_of(step.direction); - const WalkResult walk = walk_tiles_dpad(stream(), context(), run_from_wild_battle, {x, y}, 1, step.name); - stream().log(std::format("[{}] {}: a step {}, {}.", m_checkpoint, step.name, direction_name(step.direction), walk_stop_name(walk.stop))); - std::vector at; - for (const TilePos& pos : Pokemon::tiles_of(state.pose)){ - at.push_back(pos.next(step.direction)); - } - return Pokemon::outcome_ok(Pokemon::tile_pose(state.pose.map, at, step.direction)); + return m_walks.step(state, step); } Outcome StoryExecutor::talk(RunState& state, const StoryStep& step){ - // Face whom we talk to: a route ends facing its last leg, not its goal - // (r40 reached Mom facing north). They block the tile, so the tap only turns. - if (const std::optional facing = Pokemon::facing_of(state.pose)){ - route_turn(stream(), context(), *facing); - } - pbf_press_button(context(), BUTTON_A, 80ms, 200ms); - context().wait_for_all_requests(); - ShortDialogWatcher dialog(COLOR_YELLOW); - if (wait_until(stream(), context(), 3000ms, {{dialog}}) != 0){ - fail_step(stream(), label_of(step) + ": nobody answered."); - } - return Pokemon::outcome_ok(); + return m_walks.talk(state, step); } Outcome StoryExecutor::answer(RunState&, const StoryStep& step){ @@ -407,15 +165,7 @@ Outcome StoryExecutor::answer(RunState&, const StoryStep& step){ } Outcome StoryExecutor::mash(RunState& state, const StoryStep& step){ - // The step before may have played the scene already (a door step settles - // its arrival scene), so its first line is not required. - ShortDialogWatcher dialog(COLOR_CYAN); - if (wait_until(stream(), context(), 15000ms, {{dialog}}) != 0){ - stream().log(label_of(step) + ": no line within 15 s; the step before played it.", COLOR_ORANGE); - } - settle(stream(), context(), step.variant == "a" ? BUTTON_A : BUTTON_B, label_of(step), - step.pose_after && step.pose_after->map != state.pose.map); - return Pokemon::outcome_ok(); + return m_walks.mash(state, step); } Outcome StoryExecutor::battle(RunState&, const StoryStep& step){ @@ -444,7 +194,7 @@ Outcome StoryExecutor::heal(RunState&, const StoryStep& step){ // way can leave the route unsure of the column (r59, Jubilife). Below // Sandgem's door the lineup read 0.7 tile off and stepped us off it (r48). route_turn(stream(), context(), Direction::NORTH); - const bool in = run_into_door(stream(), context(), Direction::NORTH, m_can_run); + const bool in = m_io.run_into_door(Direction::NORTH, m_walks.can_run()); stream().log(std::format("[{}] {}: north into the Center: {}.", m_checkpoint, step.name, in ? "faded" : "no door; lining up by sight")); if (in){ pbf_wait(context(), 1500ms); @@ -466,9 +216,9 @@ Outcome StoryExecutor::heal(RunState&, const StoryStep& step){ // Out the same way: south until the fade. The walk out's indoor check // read "not a room" a step from the counter and stopped inside (r50, r59). route_turn(stream(), context(), Direction::SOUTH); - const bool out = run_into_door(stream(), context(), Direction::SOUTH, m_can_run); + const bool out = m_io.run_into_door(Direction::SOUTH, m_walks.can_run()); stream().log(std::format("[{}] {}: south out of the Center: {}.", m_checkpoint, step.name, out ? "faded" : "no fade yet")); - settle(stream(), context(), BUTTON_B, label_of(step), !out); + m_io.settle(BUTTON_B, label_of(step), !out); // r143a's heal said it had walked out while still inside. context().wait_for_all_requests(); VideoSnapshot screen = stream().video().snapshot(); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h index 88dbb00c09..f56ddbdb19 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h @@ -34,6 +34,8 @@ #include "Pokemon/AutoStory/Pokemon_StorySegments.h" #include "Pokemon/AutoStory/Pokemon_StorySteps.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -104,11 +106,6 @@ class StoryExecutor : public Pokemon::StoryStepExecutor{ const std::string& checkpoint() const{ return m_checkpoint; } - // Walks from the tiles of `from` on its map to any of `goal`'s tiles, - // fighting the trainers who see us this attempt. Returns where it left - // us, as a pose on `goal`'s map. - Pokemon::Pose walk_to(const Pokemon::Pose& from, const Pokemon::Pose& goal, const Pokemon::StoryStep& step); - // The intro of a new game, from the title screen to the bedroom. virtual Pokemon::Outcome new_game(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; // verify_tutorial_settings(): fast text, Autosave off. @@ -148,12 +145,10 @@ class StoryExecutor : public Pokemon::StoryStepExecutor{ Pokemon::Outcome run_guarded(Pokemon::RunState& state, const Pokemon::StoryStep& step); StoryEnv& m_env; + ConsoleStoryStepIO m_io; + // The steps that walk and talk (ROUTE, LEGS, STEP, TALK, MASH). + StoryWalkSteps m_walks; std::string m_checkpoint; - // Whether the player has the Running Shoes: the pace routes are timed at. - bool m_can_run = false; - // Route 202's trainers who can still see us, in story_plan_world()'s - // world tiles; all of them again at each attempt. - std::vector m_trainers; std::map m_failures; std::map m_run_counts; std::set m_stop_rows; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp new file mode 100644 index 0000000000..a10d802ffe --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -0,0 +1,392 @@ +/* BDSP AutoStory Story Sim Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Rows of the story table run as the program runs them (the segment + * runner, make_story_segment()), with the program's own walking steps + * (StoryWalkSteps: ROUTE, LEGS, STEP, TALK, MASH) on the grid simulation. + * After each walking step the simulated player must stand, on the grid, + * on a tile the table gives; a step through a door must have warped. + * + * Events, battles, shops and saves are stubs: a dialogue they open is + * closed, and the table's pose_after puts the player where they end. A + * heal checks that a walk north from where we stand enters a door. A scene + * starts when the player steps onto its trigger (SimTrigger). Rooms with no + * map (the Trainers' School) are passed over. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Utils/PokemonBDSP_AutoStory_GridSim.h" +#include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_StorySim_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::Outcome; +using Pokemon::Pose; +using Pokemon::RunState; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + + +// StoryStepIO on the simulation. +class SimStoryStepIO : public StoryStepIO{ +public: + SimStoryStepIO(GridSim& sim, std::vector& notes) + : m_sim(sim) + , m_route(sim, notes) + {} + + virtual RouteIO& route() override{ + return m_route; + } + virtual void fight(const std::string&) override{ + m_sim.end_dialogue(); + } + virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string& label) override{ + m_sim.tap(direction, ROUTE_TURN_TAP, false); + const Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); + const SimMove move = m_sim.hold(direction, limit, SimPace::WALK); + if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ + m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); + } + } + virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override{ + for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ + const SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + if (story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos))){ + return true; + } + if (move.distance == 0 || move.stop != SimStop::DONE){ + return false; + } + } + return false; + } + virtual bool run_into_door(Direction direction, bool run) override{ + return m_sim.hold(direction, 12000ms, run ? SimPace::RUN : SimPace::WALK).stop == SimStop::WARP; + } + // A scene may take us to another map (Mom walks us out, 00.04): with a + // dialogue open the stub scene plays it. Otherwise only a door fades. + virtual void settle(Button, const std::string& label, bool fade) override{ + if (fade && !m_sim.player().warped && !m_sim.player().dialog){ + m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); + } + m_sim.end_dialogue(); + } + +private: + GridSim& m_sim; + GridSimRouteIO m_route; +}; + + +// A scene's trigger the simulation fires from row `row` on, once the step +// `after` has run ("" from the row's start), on `map`'s `tiles`. +struct RowTrigger{ + std::string row; + std::string after; + std::string map; + SimTrigger trigger; +}; + +std::vector column(int x, int y0, int y1){ + std::vector tiles; + for (int y = y0; y <= y1; y++){ + tiles.push_back({x, y}); + } + return tiles; +} +std::vector row_of(int y, int x0, int x1){ + std::vector tiles; + for (int x = x0; x <= x1; x++){ + tiles.push_back({x, y}); + } + return tiles; +} + +// The coord events of 00.04 to 00.05c, from the decomp as the table cites +// them: Mom's call above the door after she heals us (r45, r46), Dawn's +// catching tutorial on Route 202, and the Poketch president on Jubilife's +// row 40. +std::vector story_triggers(){ + const auto trigger = [](std::string row, std::string after, std::string map, std::string name, std::vector tiles){ + return RowTrigger{.row = std::move(row), .after = std::move(after), .map = std::move(map), + .trigger = SimTrigger{.name = std::move(name), .tiles = std::move(tiles)}}; + }; + return { + trigger("00.04", "mom_heals_us", "PlayerHouse1F", "moms_call", {TilePos{6, 9}}), + trigger("00.04", "", "Route202", "catch_tutorial", column(21, 25, 29)), + trigger("00.05b", "", "JubilifeCity", "president", row_of(40, 44, 48)), + }; +} + + +// The program's walking steps on the simulation, the rest stubbed. +class SimExecutor : public Pokemon::StoryStepExecutor{ +public: + explicit SimExecutor(Logger& logger) + : m_logger(logger) + , m_sim({}, {0, 0}, Direction::NORTH, true) + , m_io(m_sim, m_notes) + , m_walks(m_io) + { + // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). + m_house = *story_plan_world("PlayerHouse1F", "PlayerHouse1F"); + m_house.block({7, 7}); + } + + const std::string& error() const{ + return m_error; + } + virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ + m_row = data.id; + m_walks.begin_attempt(data.id); + arm(""); + } + virtual Outcome run(RunState& state, const StoryStep& step) override; + +protected: + virtual Outcome route(RunState& state, const StoryStep& step) override{ return m_walks.route(state, step); } + virtual Outcome legs(RunState& state, const StoryStep& step) override{ return m_walks.legs(state, step); } + virtual Outcome step(RunState& state, const StoryStep& step) override{ return m_walks.step(state, step); } + virtual Outcome talk(RunState& state, const StoryStep& step) override{ return m_walks.talk(state, step); } + virtual Outcome mash(RunState& state, const StoryStep& step) override{ return m_walks.mash(state, step); } + virtual Outcome heal(RunState& state, const StoryStep& step) override; + virtual Outcome new_game(RunState&, const StoryStep&) override{ return stub(); } + virtual Outcome options(RunState&, const StoryStep&) override{ return stub(); } + virtual Outcome answer(RunState&, const StoryStep&) override{ return stub(); } + virtual Outcome battle(RunState&, const StoryStep&) override{ return stub(); } + virtual Outcome train(RunState&, const StoryStep&) override{ return stub(); } + virtual Outcome shop(RunState&, const StoryStep&) override{ return stub(); } + virtual Outcome save(RunState&, const StoryStep&) override{ return stub(); } + virtual Outcome game(RunState&, const StoryStep&) override{ return stub(); } + +private: + // A step the simulation does not play: its dialogue opened and closed. + Outcome stub(){ + m_sim.end_dialogue(); + return Pokemon::outcome_ok(); + } + const StoryWorld* sim_world(const std::string& map) const; + SimWorld setup(const StoryWorld* world) const; + void arm(const std::string& after); + bool sync(const Pose& pose); + std::string check(const StoryStep& step, const Outcome& outcome) const; + Outcome run_step(RunState& state, const StoryStep& step); + + Logger& m_logger; + std::vector m_notes; + GridSim m_sim; + SimStoryStepIO m_io; + StoryWalkSteps m_walks; + StoryWorld m_house; + std::string m_row; + std::vector m_armed; + // Whether the player has been put on a map yet. + bool m_placed = false; + // Whether the step running now is on a room with no map. + bool m_passed_over = false; + std::string m_error; +}; + +// The world the player walks on for `map`: the planner's, with what the +// console showed that the maps lack. Nothing for a room with no map. +const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ + const StoryWorld* world = story_plan_world(map, map); + if (world == story_plan_world("PlayerHouse1F", "PlayerHouse1F") && m_row >= "00.04"){ + return &m_house; + } + return world; +} + +SimWorld SimExecutor::setup(const StoryWorld* world) const{ + SimWorld out{.world = world, .trainers = story_trainers(*world)}; + for (const RowTrigger& armed : m_armed){ + if (sim_world(armed.map) != world){ + continue; + } + SimTrigger trigger{.name = armed.trigger.name}; + for (const TilePos& pos : armed.trigger.tiles){ + trigger.tiles.push_back(story_to_world(*world, armed.map, pos)); + } + out.triggers.push_back(std::move(trigger)); + } + return out; +} + +// Arms the triggers of this row that start after `after`. +void SimExecutor::arm(const std::string& after){ + size_t armed = 0; + for (const RowTrigger& trigger : story_triggers()){ + if (trigger.row == m_row && trigger.after == after){ + m_armed.push_back(trigger); + armed++; + } + } + const SimPlayer& player = m_sim.player(); + if (armed > 0 && m_placed && on_grid(player.pos) && !player.dialog){ + m_sim.place(setup(&m_sim.world()), nearest_tile(player.pos), player.facing); + } +} + +// Puts the player on `pose` unless they stand on one of its tiles already. +// Returns whether the pose is on a map the simulation has. +bool SimExecutor::sync(const Pose& pose){ + const std::vector tiles = Pokemon::tiles_of(pose); + const StoryWorld* world = pose.map.empty() ? nullptr : sim_world(pose.map); + if (world == nullptr || tiles.empty()){ + return false; + } + const SimPlayer& player = m_sim.player(); + const std::optional local = !m_placed || &m_sim.world() != world + ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); + if (local && on_grid(player.pos) && std::find(tiles.begin(), tiles.end(), *local) != tiles.end()){ + return true; + } + m_sim.place(setup(world), story_to_world(*world, pose.map, tiles.front()), Pokemon::facing_of(pose)); + m_placed = true; + return true; +} + +Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ + if (sync(state.pose) && m_sim.hold(Direction::NORTH, 3000ms, SimPace::RUN).stop != SimStop::WARP){ + return Pokemon::outcome_failed("no_door", step.name + ": no door north of " + to_string(m_sim.player().pos)); + } + return Pokemon::outcome_ok(); +} + +// Why a walking step did not end where the table says, or "". +std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome) const{ + const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP; + const std::optional expected = step.pose_after ? step.pose_after : outcome.pose; + if (!walks || !expected || Pokemon::tiles_of(*expected).empty() || !m_placed){ + return ""; + } + const SimPlayer& player = m_sim.player(); + const std::optional local = story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos)); + if (!local){ + return player.warped ? "" : std::format("ended on {} at {}, not on {}.", describe(m_sim.world(), nearest_tile(player.pos)), + to_string(player.pos), expected->map); + } + const std::vector tiles = Pokemon::tiles_of(*expected); + if (!on_grid(player.pos) || std::find(tiles.begin(), tiles.end(), *local) == tiles.end()){ + return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), nearest_tile(player.pos)), + Pokemon::to_string(*expected)); + } + return ""; +} + +Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ + if (story_events().contains(step.variant)){ + return stub(); + } + // A scene goes on from where the step before left us. + const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || + step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK; + if (walks && !sync(state.pose)){ + m_logger.log(std::format("[{}] {}: no map for {}; passed over.", m_row, step.name, Pokemon::to_string(state.pose))); + m_passed_over = true; + return Pokemon::outcome_ok(); + } + return Pokemon::StoryStepExecutor::run(state, step); +} + +Outcome SimExecutor::run(RunState& state, const StoryStep& step){ + Outcome outcome; + m_passed_over = false; + try{ + outcome = run_step(state, step); + }catch (const GridSimFailure& e){ + outcome = Pokemon::outcome_failed("sim_failure", e.message); + } + const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; + if (!mismatch.empty()){ + outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); + } + m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); + if (!outcome.succeeded() && m_error.empty()){ + m_error = m_row + " " + Pokemon::to_string(outcome); + } + arm(step.name); + return outcome; +} + + +// Runs `range` of the table on the simulation, stopping at the first failure. +UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ + SimExecutor executor(logger); + std::set saved; + Pokemon::Segment segment = make_story_segment(story_checkpoints(), executor, saved); + Pokemon::SegmentPolicy policy; + policy.stop_at_first_failure = true; + Pokemon::SegmentHooks hooks; + hooks.reload = [](RunState&){ return Pokemon::outcome_ok(); }; + hooks.log = [&logger](const std::string& line){ logger.log(line); }; + RunState state; + const Pokemon::SegmentReport report = Pokemon::run_segment(state, segment, range, policy, hooks); + if (!report.completed){ + return std::format("stopped at {} {}: {}", report.failed_checkpoint, report.failed_event, executor.error()); + } + return true; +} + + +class Test_StorySim : public UnitTest{ +public: + Test_StorySim(std::string name, std::string from, std::string to) + : UnitTest("PokemonBDSP::AutoStory - Story sim: " + std::move(name)) + , m_from(std::move(from)) + , m_to(std::move(to)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return run_rows(logger, {.from = m_from, .to = m_to}); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::string m_from; + std::string m_to; +}; + +} + + +void add_tests_AutoStory_StorySim(UnitTestDatabase& database){ + database.add("00.04 to 00.04d: home, the catch, Sandgem's Center, Route 202", "00.04", "00.04d"); + database.add("00.05 to 00.05c: Jubilife's Center, School, clowns and Poketch", "00.05", "00.05c"); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.h new file mode 100644 index 0000000000..dfa12e07be --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.h @@ -0,0 +1,28 @@ +/* BDSP AutoStory Story Sim Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StorySim_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StorySim_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// The story table's rows run by the program's own walking steps +// (StoryWalkSteps) on the grid simulation: each walk must end where the +// table says the player is. +void add_tests_AutoStory_StorySim(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp new file mode 100644 index 0000000000..e999b15bb3 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -0,0 +1,146 @@ +/* BDSP AutoStory - Story step IO + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP_AutoStory_Talks.h" +#include "PokemonBDSP_AutoStory_Walks.h" +#include "PokemonBDSP_AutoStory_WildBattle.h" +#include "PokemonBDSP_AutoStory_StoryStepIO.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; +using Pokemon::Direction; + + +namespace{ + +// One rule for scenes and map changes: v2's long B mashes, with an end +// check. Press through the text, and keep pressing B while the screen is +// quiet: a scene can pause while someone walks off (Dawn and Barry after +// Rowan leaves, r23), fade dimly, not to black, to another map (r25), or +// wait on a box the detector misses (r26). B never starts a talk on the +// overworld. Done once the overworld has shown, with no text and a still +// screen, for 5 s of presses: after r31's fade home a scripted walk-in ran +// 5 s with no text before Mom spoke. +// +// A step or scene that ends on another map (`fade`) must fade on the way, +// and only the quiet after the fade counts: r30's scene went quiet for 5 s +// before the fade home, and r28 "went out" a tile beside the door and +// walked a whole route in the house. No fade is a map mismatch. +constexpr double FADE_DARKNESS = 40; // brightness 0 to 255; r24's dim fade home goes darker +void settle(VideoStream& stream, ProControllerContext& context, Button button, const std::string& label, bool fade){ + const WallClock none = WallClock::max(); + const WallClock deadline = current_time() + 120s; + ShortDialogDetector dialog; + OverworldDetector overworld; + WallClock quiet_since = none; + double darkest = 255; + VideoSnapshot previous; + while (current_time() < deadline){ + context.wait_for_all_requests(); + const auto frame = stream.video().snapshot(); + const WallClock now = current_time(); + if (frame){ + darkest = std::min(darkest, image_average(*frame.frame).sum() / 3); + } + const bool talking = frame && dialog.detect(frame); + const bool still = frame && previous && walk_screen_change(*previous.frame, *frame.frame) < WALK_TAP_BLOCKED_CHANGE; + previous = frame; + if (!talking && still && overworld.detect(frame) && (!fade || darkest < FADE_DARKNESS)){ + quiet_since = quiet_since == none ? now : quiet_since; + if (now - quiet_since >= 5000ms){ + stream.log(std::format("[Story] {}: settled; darkest frame {:.0f}.", label, darkest)); + return; + } + }else{ + quiet_since = none; + } + pbf_press_button(context, talking ? button : BUTTON_B, 80ms, 1200ms); + } + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + fade && darkest >= FADE_DARKNESS + ? label + ": no fade within 120 s, so we are not where the step goes (map mismatch)." + : label + ": not back on a quiet overworld within 120 s.", + stream); +} + +// Holds the D-pad toward a door (with B after the shoes) until the screen goes +// dark or a line shows, up to 12 s. Returns whether it went dark. A line +// stops it: holding on under Mom's "Oh, Kosmos!" wasted 12 s (r45). The walker's black-screen watch +// missed the lab's fade into Sandgem (r44, "dialog"), and settle's samples +// 1.3 s apart can fall either side of it, so watch at settle's own darkness. +bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction direction, bool run){ + const DpadPosition dpad = + direction == Direction::NORTH ? DPAD_UP : + direction == Direction::SOUTH ? DPAD_DOWN : + direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; + BlackScreenWatcher dark(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, 3 * FADE_DARKNESS, 60); + ShortDialogWatcher dialog(COLOR_YELLOW); + const int ret = run_until(stream, context, [&](ProControllerContext& context){ + if (run){ + ssf_press_button(context, BUTTON_B, 0ms, 12000ms, 0ms); + } + pbf_press_dpad(context, dpad, 12000ms, 0ms); + }, {{dark}, {dialog}}); + return ret == 0; +} + +} + + +ConsoleStoryStepIO::ConsoleStoryStepIO(VideoStream& stream, ProControllerContext& context) + : m_stream(stream) + , m_context(context) + , m_escape(run_from_wild_battle) + , m_route(stream, context, m_escape) +{} + +void ConsoleStoryStepIO::fight(const std::string& trainer){ + fight_route_trainer(m_stream, m_context, trainer); +} + +void ConsoleStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ + PokemonBDSP::walk_until_stopped(m_stream, m_context, direction, tiles, label); +} + +bool ConsoleStoryStepIO::run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string& label){ + const auto [x, y] = dpad_of(direction); + const WalkResult walk = walk_until_dpad(m_stream, m_context, run_from_wild_battle, {x, y}, limit, label, { + .arrived = [&](const ImageViewRGB32& screen){ return location_banner_matches(read_location_banner(screen), map); }, + .pace = DpadPace::RUN, + }); + m_stream.log(std::format("[Story] {}: ran {} to {}'s banner: {}.", label, direction_name(direction), map, walk_stop_name(walk.stop))); + return walk.stop == WalkStop::ARRIVED; +} + +bool ConsoleStoryStepIO::run_into_door(Direction direction, bool run){ + return PokemonBDSP::run_into_door(m_stream, m_context, direction, run); +} + +void ConsoleStoryStepIO::settle(Button button, const std::string& label, bool fade){ + PokemonBDSP::settle(m_stream, m_context, button, label, fade); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h new file mode 100644 index 0000000000..34e6826931 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h @@ -0,0 +1,78 @@ +/* BDSP AutoStory - Story step IO + * + * From: https://github.com/PokemonAutomation/ + * + * What the story's walking steps (StoryWalkSteps) do on the console beyond + * the route walker's RouteIO: fights, walks until stopped, runs into doors + * and the settle after a scene. Tests run the steps on a simulation; + * ConsoleStoryStepIO is the console. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryStepIO_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryStepIO_H + +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerButtons.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class StoryStepIO{ +public: + virtual ~StoryStepIO() = default; + + // The route walker's console: walks, presses, dialogue watches, the log. + virtual RouteIO& route() = 0; + // Fights a trainer whose dialogue has opened (fight_route_trainer()). + virtual void fight(const std::string& trainer) = 0; + // walk_until_stopped(): `direction` until something stops us, for at + // most `tiles` tiles' time. Fails on a door or a dialogue. + virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) = 0; + // Runs `direction` on the D-pad until the location banner of `map` (a + // JSON map's name) shows, for at most `limit`. Returns whether it showed. + virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string& label) = 0; + // Holds the D-pad toward a door (running with `run`) until the screen + // goes dark or a line shows. Returns whether it went dark. + virtual bool run_into_door(Pokemon::Direction direction, bool run) = 0; + // Presses through any text until the overworld is quiet; with `fade`, a + // fade must come first (a map change). Fails otherwise. + virtual void settle(Button button, const std::string& label, bool fade) = 0; +}; + + +// The console. +class ConsoleStoryStepIO : public StoryStepIO{ +public: + ConsoleStoryStepIO(VideoStream& stream, ProControllerContext& context); + + virtual RouteIO& route() override{ + return m_route; + } + virtual void fight(const std::string& trainer) override; + virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; + virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string& label) override; + virtual bool run_into_door(Pokemon::Direction direction, bool run) override; + virtual void settle(Button button, const std::string& label, bool fade) override; + +private: + VideoStream& m_stream; + ProControllerContext& m_context; + WildBattleEscape m_escape; + ConsoleRouteIO m_route; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp new file mode 100644 index 0000000000..f7eb637af7 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -0,0 +1,250 @@ +/* BDSP AutoStory - Story walk steps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Exceptions.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::Outcome; +using Pokemon::Pose; +using Pokemon::RunState; +using Pokemon::StoryStep; +using Pokemon::TilePos; + + +namespace{ + +// "to_catch_grass" as "to catch grass", for the logs. +std::string label_of(const StoryStep& step){ + std::string label = step.name; + std::replace(label.begin(), label.end(), '_', ' '); + return label; +} + +// Fails the step (fail_step() on the console). +[[noreturn]] void fail(RouteIO& io, const std::string& message){ + io.note(message, RouteNote::FAILURE); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "RouteIO::note() returned from a failure: " + message); +} + +} + + +void StoryWalkSteps::begin_attempt(const std::string& row){ + m_row = row; + // A row starts from its save: after the shoes' row, the save has them. + m_can_run = row > std::string(RUNNING_SHOES_ROW); + const StoryWorld* south = story_plan_world("Route202", "Route202"); + m_trainers = south ? story_trainers(*south) : std::vector{}; +} + +void StoryWalkSteps::turn(Direction direction){ + m_io.route().note(std::string("[Route] Turning ") + direction_name(direction) + ".", RouteNote::LOG); + m_io.route().press(route_turn_tap(direction)); +} + +void StoryWalkSteps::log(const std::string& text){ + m_io.route().note(text, RouteNote::LOG); +} + +Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep& step){ + const StoryWorld* maps = story_plan_world(from.map, goal.map); + if (maps == nullptr){ + fail(m_io.route(), std::format("{}: no maps join {} and {}.", step.name, from.map, goal.map)); + } + const std::optional costs = story_route_costs(step.variant); + if (!costs){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown route costs: " + step.variant); + } + std::vector start; + for (const TilePos& pos : Pokemon::tiles_of(from)){ + start.push_back(story_to_world(*maps, from.map, pos)); + } + std::vector targets; + for (const TilePos& pos : Pokemon::tiles_of(goal)){ + targets.push_back(story_to_world(*maps, goal.map, pos)); + } + // Only Route 202's trainers are known; the ones fought stay off + // m_trainers until the next attempt. + const bool south = maps == story_plan_world("Route202", "Route202"); + RouteTrainers trainers{ + south ? m_trainers : std::vector{}, + [this](const std::string& trainer){ m_io.fight(trainer); } + }; + const RouteWalkPlan plan{ + [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }, + label_of(step), {}, *costs, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK + }; + const std::vector at = walk_route(m_io.route(), *maps, start, trainers, plan); + if (south){ + m_trainers = std::move(trainers.sights); + } + std::vector local; + for (const TilePos& pos : at){ + const std::optional tile = story_to_local(*maps, goal.map, pos); + if (!tile){ + fail(m_io.route(), std::format("{}: the walk ended off {}.", step.name, goal.map)); + } + local.push_back(*tile); + } + return Pokemon::tile_pose(goal.map, local, Pokemon::facing_of(goal)); +} + +Outcome StoryWalkSteps::route(RunState& state, const StoryStep& step){ + if (Pokemon::tiles_of(state.pose).empty()){ + return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); + } + return Pokemon::outcome_ok(walk_to(state.pose, *step.target, step)); +} + +// A LEGS step "to_dialogue": taps its one leg until a dialogue starts on the +// way, wherever it starts (Dawn's at Sandgem's edge, r35/r36: an exact tile +// and banner raced her scene). The scene's lines are the next step's. +Outcome StoryWalkSteps::leg_to_dialogue(const StoryStep& step){ + const Pokemon::StoryLeg& leg = step.legs.front(); + turn(leg.direction); + const WalkResult walk = m_io.route().walk_taps(leg.direction, (size_t)leg.tiles, step.name); + log(std::format("[{}] {}: taps {} to a dialogue: {} tiles, {}.", m_row, step.name, direction_name(leg.direction), walk.moved_chunks, walk_stop_name(walk.stop))); + if (walk.stop == WalkStop::DIALOG){ + return Pokemon::outcome_ok(); + } + // A scene can lock us before its first line: Dawn walks over first (r37). + if (walk.stop == WalkStop::BLOCKED && m_io.route().dialog_within(10000ms, COLOR_CYAN)){ + return Pokemon::outcome_ok(); + } + return Pokemon::outcome_failed("no_dialogue", step.name); +} + +// A LEGS step "to_map": runs its one leg until the location banner of +// pose_after's map shows, wherever it shows. A straight run along an open +// row needs no tile count (r41, r42: Sandgem's row 11 took us into the lab). +Outcome StoryWalkSteps::leg_to_map(const StoryStep& step){ + const Pokemon::StoryLeg& leg = step.legs.front(); + const std::string map = step.pose_after ? step.pose_after->map : ""; + turn(leg.direction); + const bool arrived = m_io.run_until_map(leg.direction, Milliseconds(250) * leg.tiles + 2000ms, map, step.name); + return arrived ? Pokemon::outcome_ok() : Pokemon::outcome_failed("no_banner", map); +} + +// Each leg in D-pad taps, turning first; "one_short_ok" lets a leg end a +// tile short. +Outcome StoryWalkSteps::tap_legs(const Pose& from, const StoryStep& step){ + const bool one_short_ok = step.variant == "one_short_ok"; + std::vector at = Pokemon::tiles_of(from); + for (const Pokemon::StoryLeg& leg : step.legs){ + // Facing another way, a tap only turns (r256): turn first. + turn(leg.direction); + const size_t tiles = (size_t)leg.tiles; + const WalkResult walk = m_io.route().walk_taps(leg.direction, tiles, step.name); + log(std::format("[{}] {}: taps {} moved {} of {} tiles.", m_row, step.name, direction_name(leg.direction), walk.moved_chunks, tiles)); + if (walk.moved_chunks + (one_short_ok ? 1 : 0) < tiles){ + return Pokemon::outcome_failed("short_leg", std::format("{} {} moved {}", direction_name(leg.direction), tiles, walk.moved_chunks)); + } + // Where we may be: the end, or a tile short of it. + std::vector next; + for (const TilePos& start : at){ + TilePos end = start; + for (size_t i = 0; i < tiles; i++){ + if (one_short_ok && i + 1 == tiles){ + next.push_back(end); + } + end = end.next(leg.direction); + } + next.push_back(end); + } + at = std::move(next); + } + return Pokemon::outcome_ok(Pokemon::tile_pose(from.map, at, step.legs.back().direction)); +} + +Outcome StoryWalkSteps::legs(RunState& state, const StoryStep& step){ + if (step.variant == "to_wall"){ + for (const Pokemon::StoryLeg& leg : step.legs){ + m_io.walk_until_stopped(leg.direction, (size_t)leg.tiles, label_of(step)); + } + return Pokemon::outcome_ok(); + } + if (step.variant == "to_dialogue"){ + return leg_to_dialogue(step); + } + if (step.variant == "to_map"){ + return leg_to_map(step); + } + if (step.variant != "one_short_ok" && !step.variant.empty()){ + return Pokemon::outcome_failed("unknown_variant", step.variant); + } + return tap_legs(state.pose, step); +} + +Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ + turn(step.direction); + // A step through a door: walk (or run) on until the screen goes dark, + // from next to the door or from anywhere in its line (r43: tapping 8 tiles + // down the lab took 7 s), then settle for any scene on arrival (Mom's, + // 00.01; Dawn's tour, 00.04). Without the fade, settle must see it itself + // (r33 was outside, "no fade"). + if (step.pose_after && step.pose_after->map != state.pose.map){ + const bool faded = m_io.run_into_door(step.direction, m_can_run); + log(std::format("[{}] {}: {} through the door: {}.", m_row, step.name, direction_name(step.direction), faded ? "faded" : "no fade yet")); + m_io.settle(BUTTON_B, label_of(step), !faded); + return Pokemon::outcome_ok(); + } + const WalkResult walk = m_io.route().walk_taps(step.direction, 1, step.name); + log(std::format("[{}] {}: a step {}, {}.", m_row, step.name, direction_name(step.direction), walk_stop_name(walk.stop))); + std::vector at; + for (const TilePos& pos : Pokemon::tiles_of(state.pose)){ + at.push_back(pos.next(step.direction)); + } + return Pokemon::outcome_ok(Pokemon::tile_pose(state.pose.map, at, step.direction)); +} + +Outcome StoryWalkSteps::talk(RunState& state, const StoryStep& step){ + // Face whom we talk to: a route ends facing its last leg, not its goal + // (r40 reached Mom facing north). They block the tile, so the tap only turns. + if (const std::optional facing = Pokemon::facing_of(state.pose)){ + turn(*facing); + } + m_io.route().press({.kind = RouteInputKind::BUTTON_A, .direction = Direction::NORTH, .hold = 80ms, .release = 200ms, + .count = 1, .end = RouteInputEnd::DONE}); + if (!m_io.route().dialog_within(3000ms, COLOR_YELLOW)){ + fail(m_io.route(), label_of(step) + ": nobody answered."); + } + return Pokemon::outcome_ok(); +} + +Outcome StoryWalkSteps::mash(RunState& state, const StoryStep& step){ + // The step before may have played the scene already (a door step settles + // its arrival scene), so its first line is not required. + if (!m_io.route().dialog_within(15000ms, COLOR_CYAN)){ + m_io.route().note(label_of(step) + ": no line within 15 s; the step before played it.", RouteNote::WARNING); + } + m_io.settle(step.variant == "a" ? BUTTON_A : BUTTON_B, label_of(step), + step.pose_after && step.pose_after->map != state.pose.map); + if (m_row == RUNNING_SHOES_ROW && step.name == RUNNING_SHOES_STEP){ + m_can_run = true; + } + return Pokemon::outcome_ok(); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h new file mode 100644 index 0000000000..b883eeae01 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -0,0 +1,71 @@ +/* BDSP AutoStory - Story walk steps + * + * From: https://github.com/PokemonAutomation/ + * + * The story steps that walk and talk (ROUTE, LEGS, STEP, TALK, MASH), on a + * StoryStepIO: StoryExecutor runs them on the console, the story's + * simulation tests on a simulated player. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryWalkSteps_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryWalkSteps_H + +#include +#include +#include "Pokemon/AutoStory/Pokemon_StorySteps.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP_AutoStory_StoryStepIO.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class StoryWalkSteps{ +public: + explicit StoryWalkSteps(StoryStepIO& io) + : m_io(io) + {} + + // A new attempt of the row `row`: every trainer can see us again, and + // the pace is the row's save's (a run after the Running Shoes). + void begin_attempt(const std::string& row); + // Whether the player has the Running Shoes: the pace routes are timed at. + bool can_run() const{ + return m_can_run; + } + + // Walks the planned route to `step.target`. Variant: the plan's costs. + Pokemon::Outcome route(Pokemon::RunState& state, const Pokemon::StoryStep& step); + // See StoryExecutor::legs(). + Pokemon::Outcome legs(Pokemon::RunState& state, const Pokemon::StoryStep& step); + // One D-pad step, or a run through a door when the step changes map. + Pokemon::Outcome step(Pokemon::RunState& state, const Pokemon::StoryStep& step); + // A at what we face; a dialogue must open. + Pokemon::Outcome talk(Pokemon::RunState& state, const Pokemon::StoryStep& step); + // Text to a quiet overworld; the Running Shoes' scene gives the shoes. + Pokemon::Outcome mash(Pokemon::RunState& state, const Pokemon::StoryStep& step); + +private: + Pokemon::Pose walk_to(const Pokemon::Pose& from, const Pokemon::Pose& goal, const Pokemon::StoryStep& step); + Pokemon::Outcome tap_legs(const Pokemon::Pose& from, const Pokemon::StoryStep& step); + Pokemon::Outcome leg_to_dialogue(const Pokemon::StoryStep& step); + Pokemon::Outcome leg_to_map(const Pokemon::StoryStep& step); + void turn(Pokemon::Direction direction); + void log(const std::string& text); + + StoryStepIO& m_io; + std::string m_row; + bool m_can_run = false; + // Route 202's trainers who can still see us, in story_plan_world()'s + // world tiles; all of them again at each attempt. + std::vector m_trainers; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.cpp new file mode 100644 index 0000000000..302b175634 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.cpp @@ -0,0 +1,361 @@ +/* BDSP AutoStory - Grid simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP_AutoStory_GridSim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::TileKind; +using Pokemon::TilePos; + + +namespace{ + +int floor_div(int value, int by){ + return value >= 0 ? value / by : -((-value + by - 1) / by); +} + +bool across(Direction direction){ + return direction == Direction::EAST || direction == Direction::WEST; +} +// +1 toward the east or south, -1 toward the west or north. +int sign_of(Direction direction){ + return direction == Direction::EAST || direction == Direction::SOUTH ? 1 : -1; +} +int& along(SimPos& pos, Direction direction){ + return across(direction) ? pos.x : pos.y; +} +int along(const SimPos& pos, Direction direction){ + return across(direction) ? pos.x : pos.y; +} +int sideways(const SimPos& pos, Direction direction){ + return across(direction) ? pos.y : pos.x; +} +TilePos tile_at(Direction direction, int along_tile, int side_tile){ + return across(direction) ? TilePos{along_tile, side_tile} : TilePos{side_tile, along_tile}; +} + +// The tiles a player at `pos` moves into with their next tile toward +// `direction`: one on the grid, two off it. `pos` is on the grid along +// `direction`. +std::vector tiles_ahead(const SimPos& pos, Direction direction){ + const int next = along(pos, direction) / SIM_TILE + sign_of(direction); + const int side = sideways(pos, direction); + std::vector tiles{tile_at(direction, next, floor_div(side, SIM_TILE))}; + if (side % SIM_TILE != 0){ + tiles.push_back(tile_at(direction, next, floor_div(side, SIM_TILE) + 1)); + } + return tiles; +} + +bool is_door(const StoryWorld& world, const TilePos& pos){ + const std::optional tile = world.tile(pos); + return tile && *tile == TileKind::DOOR && !world.occupied(pos); +} + +Milliseconds per_tile(Direction direction, SimPace pace, bool can_run){ + return route_ms_per_tile(direction, pace == SimPace::RUN && can_run ? MoveSpeed::RUN : MoveSpeed::WALK); +} + +} + + +SimPos sim_pos(const TilePos& tile){ + return {tile.x * SIM_TILE, tile.y * SIM_TILE}; +} +bool on_grid(const SimPos& pos){ + return pos.x % SIM_TILE == 0 && pos.y % SIM_TILE == 0; +} +TilePos nearest_tile(const SimPos& pos){ + return {floor_div(pos.x + SIM_TILE / 2, SIM_TILE), floor_div(pos.y + SIM_TILE / 2, SIM_TILE)}; +} +std::string to_string(const SimPos& pos){ + return std::format("({:g}, {:g})", pos.x / (double)SIM_TILE, pos.y / (double)SIM_TILE); +} + +const char* sim_stop_name(SimStop stop){ + switch (stop){ + case SimStop::DONE: + return "done"; + case SimStop::BLOCKED: + return "blocked"; + case SimStop::DIALOG: + return "dialog"; + case SimStop::WARP: + return "warp"; + case SimStop::LIMIT: + return "limit"; + } + return "?"; +} + + +GridSim::GridSim(SimWorld world, const TilePos& start, Direction facing, bool can_run) + : m_world(std::move(world)) +{ + m_player.pos = sim_pos(start); + m_player.facing = facing; + m_player.can_run = can_run; +} + +void GridSim::place(SimWorld world, const TilePos& start, std::optional facing){ + m_world = std::move(world); + m_player.pos = sim_pos(start); + if (facing){ + m_player.facing = *facing; + } + m_player.dialog = false; + m_player.trainer.reset(); + m_player.warped.reset(); +} + +// Moves into the next tile toward `direction`, `part` of the way (a whole +// tile or less), from a position on the grid along it; adds what it moved +// to `moved`. A ledge hops two whole tiles and a door warps, however far +// the press goes. Nothing if the player may go on, else why the move ended. +std::optional GridSim::enter_next(Direction direction, int part, int& moved){ + const StoryWorld& world = *m_world.world; + const std::vector ahead = tiles_ahead(m_player.pos, direction); + if (ahead.size() == 1){ + const TilePos from = nearest_tile(m_player.pos); + const std::optional landing = PokemonBDSP::step(world, from, direction); + if (landing && *landing != ahead[0]){ + part = 2 * SIM_TILE; + }else if (!landing && is_door(world, ahead[0])){ + m_player.pos = sim_pos(ahead[0]); + m_player.warped = ahead[0]; + moved += SIM_TILE; + return SimStop::WARP; + }else if (!landing){ + return SimStop::BLOCKED; + } + } + // Off the grid, both tiles must be open: a door frame or a corner stops us. + for (const TilePos& pos : ahead){ + if (ahead.size() > 1 && !standable(world, pos)){ + return SimStop::BLOCKED; + } + } + along(m_player.pos, direction) += sign_of(direction) * part; + moved += part; + return std::nullopt; +} + +// On reaching a whole tile: a scene's trigger or a trainer's sight stops us. +std::optional GridSim::arrive(){ + const TilePos tile = nearest_tile(m_player.pos); + for (const SimTrigger& trigger : m_world.triggers){ + const bool fired = std::find(m_player.fired.begin(), m_player.fired.end(), trigger.name) != m_player.fired.end(); + if (!fired && std::find(trigger.tiles.begin(), trigger.tiles.end(), tile) != trigger.tiles.end()){ + m_player.fired.push_back(trigger.name); + m_player.dialog = true; + return SimStop::DIALOG; + } + } + for (const TrainerSight& trainer : m_world.trainers){ + const bool fought = std::find(m_player.fought.begin(), m_player.fought.end(), trainer.name) != m_player.fought.end(); + const std::vector sight = sight_tiles(*m_world.world, trainer); + if (!fought && std::find(sight.begin(), sight.end(), tile) != sight.end()){ + m_player.dialog = true; + m_player.trainer = trainer.name; + return SimStop::DIALOG; + } + } + return std::nullopt; +} + +// Moves up to `distance` toward `direction`. +SimMove GridSim::advance(Direction direction, int distance){ + m_player.facing = direction; + if (m_player.dialog){ + return {.stop = SimStop::DIALOG}; + } + int moved = 0; + while (moved < distance){ + const int offset = along(m_player.pos, direction) % SIM_TILE; + if (offset != 0){ + // Part of a tile to the next whole one: no new tile is entered. + const int to_whole = sign_of(direction) > 0 ? SIM_TILE - offset : offset; + const int part = std::min(to_whole, distance - moved); + along(m_player.pos, direction) += sign_of(direction) * part; + moved += part; + }else if (const std::optional stop = enter_next(direction, std::min(SIM_TILE, distance - moved), moved)){ + return {.stop = *stop, .distance = moved}; + } + if (along(m_player.pos, direction) % SIM_TILE == 0){ + if (const std::optional stop = arrive()){ + return {.stop = *stop, .distance = moved}; + } + } + } + return {.stop = SimStop::DONE, .distance = moved}; +} + +SimMove GridSim::tap(Direction direction, Milliseconds hold, bool stick){ + const Milliseconds tile_time = route_ms_per_tile(direction, MoveSpeed::WALK); + if (!stick && hold < 100ms){ + m_player.facing = direction; + return {.stop = m_player.dialog ? SimStop::DIALOG : SimStop::DONE, .time = hold}; + } + // The stick moves as far as it is held; the D-pad whole tiles. + int distance = (int)(hold.count() * SIM_TILE / tile_time.count()); + if (!stick){ + distance = std::max(1, (int)((hold + tile_time / 2) / tile_time)) * SIM_TILE; + } + SimMove move = advance(direction, distance); + move.time = hold; + return move; +} + +SimMove GridSim::hold(Direction direction, Milliseconds limit, SimPace pace){ + const Milliseconds tile_time = per_tile(direction, pace, m_player.can_run); + const int64_t tiles = limit < ROUTE_START_DELAY ? 0 : (limit - ROUTE_START_DELAY) / tile_time; + int moved = 0; + SimStop stop = SimStop::LIMIT; + while (moved < tiles * SIM_TILE){ + const SimMove step = advance(direction, SIM_TILE); + moved += step.distance; + if (step.stop != SimStop::DONE){ + stop = step.stop; + break; + } + } + if (stop == SimStop::LIMIT){ + return {.stop = stop, .distance = moved, .time = limit}; + } + // A stop is seen once the screen has held still a while. + const Milliseconds seen = stop == SimStop::BLOCKED ? 800ms : 0ms; + return {.stop = stop, .distance = moved, .time = ROUTE_START_DELAY + tile_time * moved / SIM_TILE + seen}; +} + +bool GridSim::press_a(){ + if (m_player.dialog){ + return true; + } + const StoryWorld& world = *m_world.world; + const TilePos faced = nearest_tile(m_player.pos).next(m_player.facing); + const std::optional tile = world.tile(faced); + m_player.dialog = world.occupied(faced) != StoryWorld::NOBODY || (tile && *tile == TileKind::SIGN); + for (const TrainerSight& trainer : m_world.trainers){ + if (m_player.dialog && trainer.pos == faced){ + m_player.trainer = trainer.name; + } + } + return m_player.dialog; +} + +void GridSim::end_dialogue(){ + if (m_player.trainer){ + m_player.fought.push_back(*m_player.trainer); + } + m_player.trainer.reset(); + m_player.dialog = false; +} + + +bool sim_can_step(const GridSim& sim, Direction direction){ + GridSim probe = sim; + const SimMove move = probe.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + return move.distance > 0; +} + + +namespace{ + +WalkStop walk_stop(SimStop stop){ + switch (stop){ + case SimStop::BLOCKED: + return WalkStop::BLOCKED; + case SimStop::DIALOG: + return WalkStop::DIALOG; + case SimStop::WARP: + return WalkStop::TRANSITION; + case SimStop::DONE: + case SimStop::LIMIT: + return WalkStop::LIMIT; + } + return WalkStop::LIMIT; +} + +} + +WalkResult GridSimRouteIO::walk_to_wall(const RouteWallWalk& walk){ + const SimPace pace = walk.options.pace == DpadPace::RUN ? SimPace::RUN : SimPace::WALK; + const SimMove move = m_sim.hold(walk.direction, walk.limit, pace); + m_notes.push_back(std::format("[Sim] {}: held {} to {} at {}.", walk.label, direction_name(walk.direction), + sim_stop_name(move.stop), to_string(m_sim.player().pos))); + return {.stop = walk_stop(move.stop), .walked = move.time, .wild_battles = 0, .moved_chunks = (size_t)(move.distance / SIM_TILE)}; +} + +// A tap a tile, as walk_tiles_dpad() taps: two taps in a row that move +// nothing end the walk. +WalkResult GridSimRouteIO::walk_taps(Direction direction, size_t tiles, const std::string& label){ + WalkResult result{.stop = WalkStop::LIMIT, .walked = 0ms, .wild_battles = 0, .moved_chunks = 0}; + size_t still = 0; + for (size_t tap = 0; tap < tiles && result.stop == WalkStop::LIMIT; tap++){ + const SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + result.walked += 800ms; + still = move.distance > 0 ? 0 : still + 1; + result.moved_chunks += move.distance > 0 ? 1 : 0; + if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ + result.stop = walk_stop(move.stop); + }else if (still >= 2){ + result.stop = WalkStop::BLOCKED; + } + } + m_notes.push_back(std::format("[Sim] {}: {} taps {}, {} moved, {} at {}.", label, tiles, direction_name(direction), + result.moved_chunks, walk_stop_name(result.stop), to_string(m_sim.player().pos))); + return result; +} + +void GridSimRouteIO::press(const RouteInput& input){ + for (size_t press = 0; press < input.count; press++){ + switch (input.kind){ + case RouteInputKind::DPAD: + m_sim.tap(input.direction, input.hold, false); + break; + case RouteInputKind::STICK: + m_sim.tap(input.direction, input.hold, true); + break; + case RouteInputKind::BUTTON_A: + m_sim.press_a(); + break; + case RouteInputKind::WAIT: + case RouteInputKind::PAUSE: + break; + } + } +} + +bool GridSimRouteIO::dialog_within(Milliseconds, Color){ + return m_sim.player().dialog; +} + +bool GridSimRouteIO::holding_against_wall(Direction direction, const std::string&){ + return !sim_can_step(m_sim, direction); +} + +void GridSimRouteIO::look(const std::function&){} + +void GridSimRouteIO::note(const std::string& text, RouteNote kind){ + m_notes.push_back(text); + if (kind == RouteNote::FAILURE){ + throw GridSimFailure{text}; + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.h new file mode 100644 index 0000000000..4cb6b329fc --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.h @@ -0,0 +1,181 @@ +/* BDSP AutoStory - Grid simulation + * + * From: https://github.com/PokemonAutomation/ + * + * A player walking on a story world, by the movement measured on the + * console, so walks that go wrong only on the Switch go wrong in tests: + * + * - A D-pad tap of 40 to 80 ms only turns; 160 ms steps a whole tile. + * - The D-pad held walks whole tiles until something stops it. + * - A stick tap moves part of a tile (100 ms about 0.6 tile across), and + * later D-pad moves keep that offset: the player is off the tile grid. + * - Walls, signs and people on their tiles stop the player. Off the grid + * the player covers two tiles, and both must be open: a door frame or + * a tree corner stops a player a part of a tile off. + * - Walking onto a door warps, but only from its exact column or row. + * - A trainer whose sight line the player steps into stops the walk with + * their dialogue; so does a scene's trigger tile. + * + * Positions are in thousandths of a tile, so parts of tiles add up exactly. + * GridSimRouteIO is the walker's RouteIO on a GridSim. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_GridSim_H +#define PokemonAutomation_PokemonBDSP_AutoStory_GridSim_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" +#include "PokemonBDSP_AutoStory_RouteIO.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// A tile, in the simulation's units. +inline constexpr int SIM_TILE = 1000; + +// A world position in thousandths of a tile: the player covers the square +// from (x, y) to (x + SIM_TILE, y + SIM_TILE). +struct SimPos{ + int x = 0; + int y = 0; + bool operator==(const SimPos& other) const = default; +}; +SimPos sim_pos(const Pokemon::TilePos& tile); +// Whether the player stands exactly on a tile. +bool on_grid(const SimPos& pos); +// The tile the player mostly stands on. +Pokemon::TilePos nearest_tile(const SimPos& pos); +// "(12.375, 5)". +std::string to_string(const SimPos& pos); + +// A scene that starts when the player steps onto one of `tiles` (a coord +// event): its dialogue opens and the player stops. It fires once. +struct SimTrigger{ + std::string name; + std::vector tiles; +}; + +// Where the simulated player walks: the world (which must outlive the +// simulation), its trainers and its scene triggers, in world tiles. +struct SimWorld{ + const StoryWorld* world = nullptr; + std::vector trainers = {}; + std::vector triggers = {}; +}; + +enum class SimStop{ + DONE, // the input finished + BLOCKED, // stopped by a wall, a person, or a door off its column + DIALOG, // a trainer saw us or a scene started; the player is frozen + WARP, // stepped onto a door + LIMIT, // a held walk ran out of time +}; +const char* sim_stop_name(SimStop stop); + +// What one input did. +struct SimMove{ + SimStop stop = SimStop::DONE; + int distance = 0; // thousandths of a tile + Milliseconds time = Milliseconds(0); +}; + +// The player as the simulation has them. +struct SimPlayer{ + SimPos pos; + Pokemon::Direction facing = Pokemon::Direction::NORTH; + // Whether B runs: the Running Shoes (00.03). + bool can_run = false; + // A dialogue is open: a trainer's, a scene's or a talk's. + bool dialog = false; + // The trainer whose dialogue is open, if one is. + std::optional trainer; + // The door the last warp stepped onto. + std::optional warped; + std::vector fought = {}; + std::vector fired = {}; +}; + +// How long a held walk takes per tile in `direction`. +enum class SimPace{ + WALK, + RUN, // B held: a run once the player has the Running Shoes +}; + +class GridSim{ +public: + GridSim(SimWorld world, const Pokemon::TilePos& start, Pokemon::Direction facing, bool can_run); + + // One press toward `direction`: the D-pad or the stick, held for `hold`. + SimMove tap(Pokemon::Direction direction, Milliseconds hold, bool stick); + // Holds toward `direction` until something stops the player or `limit` + // runs out. Moves whole tiles, from wherever the player stands. + SimMove hold(Pokemon::Direction direction, Milliseconds limit, SimPace pace); + // A: talks to a person or a sign on the faced tile. Returns whether a + // dialogue is open. + bool press_a(); + // The open dialogue ends: a trainer's battle is won and they see us no more. + void end_dialogue(); + // Puts the player on `start` of `world`: after a warp or a scene. + void place(SimWorld world, const Pokemon::TilePos& start, std::optional facing); + + const SimPlayer& player() const{ + return m_player; + } + const StoryWorld& world() const{ + return *m_world.world; + } + +private: + SimMove advance(Pokemon::Direction direction, int distance); + std::optional enter_next(Pokemon::Direction direction, int part, int& moved); + std::optional arrive(); + + SimWorld m_world; + SimPlayer m_player; +}; + +// Whether the player could take a step toward `direction` from where they stand. +bool sim_can_step(const GridSim& sim, Pokemon::Direction direction); + + +// The walker's RouteIO on a GridSim. A failure throws GridSimFailure. +class GridSimRouteIO : public RouteIO{ +public: + // Every line noted goes to `notes`, which must outlive this. + GridSimRouteIO(GridSim& sim, std::vector& notes) + : m_sim(sim) + , m_notes(notes) + {} + + virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override; + virtual WalkResult walk_taps(Pokemon::Direction direction, size_t tiles, const std::string& label) override; + virtual void press(const RouteInput& input) override; + virtual bool dialog_within(Milliseconds wait, Color color) override; + virtual bool holding_against_wall(Pokemon::Direction direction, const std::string& label) override; + virtual void look(const std::function& at) override; + virtual void note(const std::string& text, RouteNote kind) override; + +private: + GridSim& m_sim; + std::vector& m_notes; +}; + +// What GridSimRouteIO throws for RouteNote::FAILURE. +struct GridSimFailure{ + std::string message; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index e0425f314a..c781e6b2c0 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1558,6 +1558,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.h + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.cpp + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.h Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp @@ -1682,8 +1684,14 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Settings.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Talks.cpp @@ -1702,6 +1710,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp From fd349b3ebbcab1d2ceeaec3d4517969e2827131a Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 02:13:14 -0800 Subject: [PATCH 002/166] BDSP AutoStory sim: scenes from the maps' coord events The story maps list their coord events ("coord_events": the decomp's zone_event triggers, from pret/pokeplatinum's events files, and Mom's call as measured on the console). story_coord_events() reads them, and the story sim arms each while its story variable holds, so a step onto a trigger tile starts its scene in the simulation. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_AutoStory_CoordEvents.cpp | 109 ++++++++++++++++++ .../Data/PokemonBDSP_AutoStory_CoordEvents.h | 50 ++++++++ .../Programs/AutoStory/Maps/JubilifeCity.json | 4 + .../AutoStory/Maps/PlayerHouse1F.json | 4 + .../Programs/AutoStory/Maps/Route202.json | 3 + .../Programs/AutoStory/Maps/SandgemTown.json | 3 + .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 98 ++++++++++++---- SerialPrograms/cmake/SourceFiles.cmake | 2 + 8 files changed, 248 insertions(+), 25 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp new file mode 100644 index 0000000000..3a500b0a54 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp @@ -0,0 +1,109 @@ +/* BDSP AutoStory - Coord events + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP_AutoStory_CoordEvents.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::TilePos; + + +namespace{ + +int read_int(const JsonObject& object, const std::string& key, const std::string& where){ + const JsonValue* value = object.get_value(key); + if (value == nullptr || !value->is_integer()){ + throw ParseException(where + key + " is missing or not an integer."); + } + return (int)value->to_integer_default(); +} + +std::string read_string(const JsonObject& object, const std::string& key, const std::string& where){ + const JsonValue* value = object.get_value(key); + const std::string* text = value == nullptr ? nullptr : value->to_string(); + if (text == nullptr){ + throw ParseException(where + key + " is missing or not a string."); + } + return *text; +} + +CoordEvent read_event(const JsonObject& object, const std::string& where){ + CoordEvent event{ + .name = read_string(object, "name", where), + .tiles = {}, + .var = read_string(object, "var", where), + .value = read_int(object, "value", where), + .source = read_string(object, "source", where), + }; + const int x = read_int(object, "x", where); + const int y = read_int(object, "y", where); + const int width = read_int(object, "width", where); + const int length = read_int(object, "length", where); + if (width < 1 || length < 1){ + throw ParseException(where + "width and length must be at least 1."); + } + for (int row = y; row < y + length; row++){ + for (int col = x; col < x + width; col++){ + event.tiles.push_back({col, row}); + } + } + return event; +} + +std::vector read_events(const std::string& name, const std::string& json){ + std::vector events; + const JsonValue root = parse_json(json); + const JsonObject* object = root.to_object(); + const JsonValue* list = object == nullptr ? nullptr : object->get_value("coord_events"); + if (list == nullptr){ + return events; + } + const JsonArray* array = list->to_array(); + if (array == nullptr){ + throw ParseException(name + ".json: coord_events is not an array."); + } + for (size_t c = 0; c < array->size(); c++){ + const std::string where = std::format("{}.json: coord_events[{}].", name, c); + const JsonObject* item = (*array)[c].to_object(); + if (item == nullptr){ + throw ParseException(where + " is not an object."); + } + events.push_back(read_event(*item, where)); + } + return events; +} + +} + + +const std::vector& story_coord_events(std::string_view map){ + static const std::map, std::less<>> by_map = []{ + std::map, std::less<>> out; + for (const auto& [name, json] : bdsp_map_json()){ + out.emplace(name, read_events(name, json)); + } + return out; + }(); + if (auto iter = by_map.find(map); iter != by_map.end()){ + return iter->second; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No BDSP story map named \"{}\".", map)); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h new file mode 100644 index 0000000000..2c38f3c9df --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h @@ -0,0 +1,50 @@ +/* BDSP AutoStory - Coord events + * + * From: https://github.com/PokemonAutomation/ + * + * The scene triggers of the story maps: stepping onto one of an event's + * tiles while its story variable holds `value` starts its script. They are + * the decomp's coord events (zone_event), read from a map's + * "coord_events", which the shared map schema leaves to the game: + * + * "coord_events": [{"name": "catch_tutorial", "x": 21, "y": 25, "width": 1, "length": 5, + * "var": "VAR_ROUTE_202_STATE", "value": 0, "source": "..."}, ...] + * + * A trigger seen on the console that the decomp does not have names the run + * in `source`. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_CoordEvents_H +#define PokemonAutomation_PokemonBDSP_AutoStory_CoordEvents_H + +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +struct CoordEvent{ + std::string name; + // The map's own tiles: `width` columns from x, `length` rows from y. + std::vector tiles; + std::string var; + int value = 0; + std::string source; +}; + +// The coord events of the map `map` (a JSON map's name), none if it lists +// none. Throws InternalProgramError for an unknown map, and ParseException +// for an event that does not parse. +const std::vector& story_coord_events(std::string_view map); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json index 71aed1d875..9b7952fa7c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/JubilifeCity.json @@ -135,5 +135,9 @@ {"name": "clown_tv_station", "kind": "npc", "x": 36, "y": 16}, {"name": "kid_with_nds_29", "kind": "npc", "x": 52, "y": 46}, {"name": "kid_with_nds_30", "kind": "npc", "x": 54, "y": 46} + ], + "coord_events": [ + {"name": "dawn_at_the_steps", "x": 45, "y": 60, "width": 4, "length": 1, "var": "VAR_JUBILIFE_CITY_STATE", "value": 0, "source": "pret/pokeplatinum res/field/events/events_jubilife_city.json coord_events[0] (173, 796), script 2"}, + {"name": "poketch_president", "x": 44, "y": 40, "width": 5, "length": 1, "var": "VAR_POKETCH_CAMPAIGN_STATE", "value": 1, "source": "pret/pokeplatinum res/field/events/events_jubilife_city.json coord_events[4] (172, 776), script 17"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json index 2a7a89546d..4fd4f96d58 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/PlayerHouse1F.json @@ -25,5 +25,9 @@ ], "objects": [ {"name": "mom_0", "kind": "npc", "x": 7, "y": 8, "facing": "north"} + ], + "coord_events": [ + {"name": "moms_warning", "x": 6, "y": 10, "width": 1, "length": 1, "var": "VAR_PLAYER_HOUSE_STATE", "value": 1, "source": "pret/pokeplatinum res/field/events/events_twinleaf_town_player_house_1f.json coord_events[0] (6, 10), script 5"}, + {"name": "moms_call", "x": 6, "y": 9, "width": 1, "length": 1, "var": "CONSOLE_MOMS_CALL", "value": 0, "source": "console r45, r46 (2026-11-01): after her heal Mom calls us back as we step above the door; no coord event in the decomp"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json index e52d694739..23f8ef2d6c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/Route202.json @@ -137,5 +137,8 @@ {"x": 19, "y": 29, "glyph": "#", "measured_by": "r253, 2026-11-01"}, {"x": 20, "y": 29, "glyph": "#", "measured_by": "r253, 2026-11-01"}, {"x": 21, "y": 30, "glyph": "#", "measured_by": "r254, 2026-11-01"} + ], + "coord_events": [ + {"name": "catch_tutorial", "x": 21, "y": 25, "width": 1, "length": 5, "var": "VAR_ROUTE_202_STATE", "value": 0, "source": "pret/pokeplatinum res/field/events/events_route_202.json coord_events[0] (180, 825), script 6"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json index 4f7a4e61b4..3f05806a7d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Maps/SandgemTown.json @@ -51,5 +51,8 @@ }, "objects": [ {"name": "youngster_0", "kind": "npc", "x": 27, "y": 23, "wander": {"x0": 26, "y0": 22, "x1": 28, "y1": 24}} + ], + "coord_events": [ + {"name": "dawn_walks_us_to_the_lab", "x": 4, "y": 10, "width": 1, "length": 6, "var": "VAR_SANDGEM_TOWN_STATE", "value": 0, "source": "pret/pokeplatinum res/field/events/events_sandgem_town.json coord_events[0] (164, 842), script 2"} ] } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp index a10d802ffe..3d2e618f32 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -11,7 +11,8 @@ * Events, battles, shops and saves are stubs: a dialogue they open is * closed, and the table's pose_after puts the player where they end. A * heal checks that a walk north from where we stand enters a door. A scene - * starts when the player steps onto its trigger (SimTrigger). Rooms with no + * starts when the player steps onto one of the maps' coord events while + * its story variable holds (story_vars()). Rooms with no * map (the Trainers' School) are passed over. * */ @@ -27,6 +28,8 @@ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Pokemon/AutoStory/Pokemon_StorySegments.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Data/PokemonBDSP_AutoStory_CoordEvents.h" +#include "Data/PokemonBDSP_AutoStory_Maps.h" #include "Utils/PokemonBDSP_AutoStory_GridSim.h" #include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP_AutoStory_Events.h" @@ -115,35 +118,51 @@ struct RowTrigger{ SimTrigger trigger; }; -std::vector column(int x, int y0, int y1){ - std::vector tiles; - for (int y = y0; y <= y1; y++){ - tiles.push_back({x, y}); - } - return tiles; +// When a story variable holds the value its coord events wait for: from +// row `row` on, once the step `after` has run ("" from the row's start). +struct VarState{ + std::string var; + int value; + std::string row; + std::string after; +}; + +// The story variables of 00.04 to 00.05c: Dawn's catching tutorial waits on +// Route 202 from 00.04's start, Mom calls us back once she has healed us, +// and the Poketch president waits on Jubilife's row 40 in 00.05b. +std::vector story_vars(){ + return { + {.var = "VAR_ROUTE_202_STATE", .value = 0, .row = "00.04", .after = ""}, + {.var = "CONSOLE_MOMS_CALL", .value = 0, .row = "00.04", .after = "mom_heals_us"}, + {.var = "VAR_POKETCH_CAMPAIGN_STATE", .value = 1, .row = "00.05b", .after = ""}, + }; } -std::vector row_of(int y, int x0, int x1){ - std::vector tiles; - for (int x = x0; x <= x1; x++){ - tiles.push_back({x, y}); + +// The maps' coord events (story_coord_events()) whose variable holds. +std::optional var_state(const CoordEvent& event){ + for (const VarState& state : story_vars()){ + if (state.var == event.var && state.value == event.value){ + return state; + } } - return tiles; + return std::nullopt; +} + +RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ + return {.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; } -// The coord events of 00.04 to 00.05c, from the decomp as the table cites -// them: Mom's call above the door after she heals us (r45, r46), Dawn's -// catching tutorial on Route 202, and the Poketch president on Jubilife's -// row 40. std::vector story_triggers(){ - const auto trigger = [](std::string row, std::string after, std::string map, std::string name, std::vector tiles){ - return RowTrigger{.row = std::move(row), .after = std::move(after), .map = std::move(map), - .trigger = SimTrigger{.name = std::move(name), .tiles = std::move(tiles)}}; - }; - return { - trigger("00.04", "mom_heals_us", "PlayerHouse1F", "moms_call", {TilePos{6, 9}}), - trigger("00.04", "", "Route202", "catch_tutorial", column(21, 25, 29)), - trigger("00.05b", "", "JubilifeCity", "president", row_of(40, 44, 48)), - }; + std::vector triggers; + for (const auto& [map, json] : bdsp_map_json()){ + for (const CoordEvent& event : story_coord_events(map)){ + const std::optional state = var_state(event); + if (state){ + triggers.push_back(row_trigger(map, event, *state)); + } + } + } + return triggers; } @@ -357,6 +376,34 @@ UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ } +// Every coord event has ground the player can step onto, and the ones +// the story's variables arm are there. +class Test_CoordEvents : public UnitTest{ +public: + Test_CoordEvents() + : UnitTest("PokemonBDSP::AutoStory - Story sim: the maps' coord events are on open ground or doors") + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + for (const auto& [map, json] : bdsp_map_json()){ + const StoryWorld* world = story_plan_world(map, map); + for (const CoordEvent& event : world == nullptr ? std::vector{} : story_coord_events(map)){ + const auto open = [&](const TilePos& pos){ + const TilePos tile = story_to_world(*world, map, pos); + return standable(*world, tile) || world->tile(tile) == Pokemon::TileKind::DOOR; + }; + // The decomp's boxes may run into walls (Sandgem's (4, 10..15)). + if (!std::ranges::any_of(event.tiles, open)){ + return std::format("{} {}: no tile is open ground or a door.", map, event.name); + } + } + } + const size_t armed = story_triggers().size(); + return armed == story_vars().size() ? UnitTestResult(true) + : UnitTestResult(std::format("Expected {} coord events armed by the story's variables, found {}.", story_vars().size(), armed)); + } +}; + + class Test_StorySim : public UnitTest{ public: Test_StorySim(std::string name, std::string from, std::string to) @@ -381,6 +428,7 @@ class Test_StorySim : public UnitTest{ void add_tests_AutoStory_StorySim(UnitTestDatabase& database){ + database.add(); database.add("00.04 to 00.04d: home, the catch, Sandgem's Center, Route 202", "00.04", "00.04d"); database.add("00.05 to 00.05c: Jubilife's Center, School, clowns and Poketch", "00.05", "00.05c"); } diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index c781e6b2c0..6840ca42f7 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1700,6 +1700,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walks.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_WildBattle.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_WildBattle.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp From c32d50cd858cff9f138692e087871a189f7811fd Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 07:39:44 -0800 Subject: [PATCH 003/166] BDSP AutoStory sim: miss each fade and banner in turn (#162) The story sim's StoryStepIO can now miss the Nth door fade (run_into_door reports no fade though the player warped; the settle after it sees none either, as on the console once the fade is over) or the Nth map banner (run_until_map). A new test runs 00.04 to 00.05c once per fade and banner the clean run makes, and requires each miss to be got over or to stop the run in the step that missed: a later failure means the miss went unseen. Today all four (3 fades, 1 banner) stop in their own step. A missed fade costs settle()'s 120 s and a failed attempt. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 131 ++++++++++++++++-- 1 file changed, 122 insertions(+), 9 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 3d2e618f32..e339b8832c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" @@ -57,12 +58,29 @@ using Pokemon::StoryStepKind; using Pokemon::TilePos; +// Which detections the simulation misses on purpose (#162): the `fade`th +// door fade (run_into_door(), from 0) or the `banner`th map banner +// (run_until_map()) of the run goes unseen, though the player did go +// through. The console missed both (r75, r81). +// The counts and flags below are the run's: how many fades and banners it +// looked for, whether a miss happened since the executor last looked, and +// whether a missed fade is still unseen. +struct SimMisses{ + std::optional fade; + std::optional banner; + size_t fades = 0; + size_t banners = 0; + bool missed = false; + bool fade_unseen = false; +}; + // StoryStepIO on the simulation. class SimStoryStepIO : public StoryStepIO{ public: - SimStoryStepIO(GridSim& sim, std::vector& notes) + SimStoryStepIO(GridSim& sim, std::vector& notes, SimMisses& misses) : m_sim(sim) , m_route(sim, notes) + , m_misses(misses) {} virtual RouteIO& route() override{ @@ -80,9 +98,14 @@ class SimStoryStepIO : public StoryStepIO{ } } virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override{ + const bool miss = m_misses.banner == m_misses.banners++; for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ const SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); if (story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos))){ + if (miss){ + m_misses.missed = true; + continue; + } return true; } if (move.distance == 0 || move.stop != SimStop::DONE){ @@ -92,20 +115,30 @@ class SimStoryStepIO : public StoryStepIO{ return false; } virtual bool run_into_door(Direction direction, bool run) override{ - return m_sim.hold(direction, 12000ms, run ? SimPace::RUN : SimPace::WALK).stop == SimStop::WARP; + const bool warped = m_sim.hold(direction, 12000ms, run ? SimPace::RUN : SimPace::WALK).stop == SimStop::WARP; + if (warped && m_misses.fade == m_misses.fades++){ + m_misses.missed = true; + m_misses.fade_unseen = true; + return false; + } + return warped; } // A scene may take us to another map (Mom walks us out, 00.04): with a // dialogue open the stub scene plays it. Otherwise only a door fades. + // A fade missed on the way in stays missed: it was over before settle() + // looked, which then fails as it does on the console after 120 s. virtual void settle(Button, const std::string& label, bool fade) override{ - if (fade && !m_sim.player().warped && !m_sim.player().dialog){ + if (fade && ((!m_sim.player().warped && !m_sim.player().dialog) || m_misses.fade_unseen)){ m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); } + m_misses.fade_unseen = false; m_sim.end_dialogue(); } private: GridSim& m_sim; GridSimRouteIO m_route; + SimMisses& m_misses; }; @@ -169,10 +202,11 @@ std::vector story_triggers(){ // The program's walking steps on the simulation, the rest stubbed. class SimExecutor : public Pokemon::StoryStepExecutor{ public: - explicit SimExecutor(Logger& logger) + explicit SimExecutor(Logger& logger, SimMisses misses = {}) : m_logger(logger) + , m_misses(misses) , m_sim({}, {0, 0}, Direction::NORTH, true) - , m_io(m_sim, m_notes) + , m_io(m_sim, m_notes, m_misses) , m_walks(m_io) { // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). @@ -183,6 +217,17 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ const std::string& error() const{ return m_error; } + const SimMisses& misses() const{ + return m_misses; + } + // The row and step where an injected miss happened, and where the run + // first failed: "" if none. + const std::string& missed_step() const{ + return m_missed_step; + } + const std::string& failed_step() const{ + return m_failed_step; + } virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ m_row = data.id; m_walks.begin_attempt(data.id); @@ -221,6 +266,7 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ Logger& m_logger; std::vector m_notes; + SimMisses m_misses; GridSim m_sim; SimStoryStepIO m_io; StoryWalkSteps m_walks; @@ -232,6 +278,8 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ // Whether the step running now is on a room with no map. bool m_passed_over = false; std::string m_error; + std::string m_missed_step; + std::string m_failed_step; }; // The world the player walks on for `map`: the planner's, with what the @@ -349,17 +397,20 @@ Outcome SimExecutor::run(RunState& state, const StoryStep& step){ outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); } m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); + if (std::exchange(m_misses.missed, false) && m_missed_step.empty()){ + m_missed_step = m_row + " " + step.name; + } if (!outcome.succeeded() && m_error.empty()){ m_error = m_row + " " + Pokemon::to_string(outcome); + m_failed_step = m_row + " " + step.name; } arm(step.name); return outcome; } -// Runs `range` of the table on the simulation, stopping at the first failure. -UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ - SimExecutor executor(logger); +// Runs `range` of the table on `executor`, stopping at the first failure. +Pokemon::SegmentReport run_rows_on(SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range){ std::set saved; Pokemon::Segment segment = make_story_segment(story_checkpoints(), executor, saved); Pokemon::SegmentPolicy policy; @@ -368,7 +419,13 @@ UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ hooks.reload = [](RunState&){ return Pokemon::outcome_ok(); }; hooks.log = [&logger](const std::string& line){ logger.log(line); }; RunState state; - const Pokemon::SegmentReport report = Pokemon::run_segment(state, segment, range, policy, hooks); + return Pokemon::run_segment(state, segment, range, policy, hooks); +} + +// Runs `range` of the table on the simulation, stopping at the first failure. +UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ + SimExecutor executor(logger); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, range); if (!report.completed){ return std::format("stopped at {} {}: {}", report.failed_checkpoint, report.failed_event, executor.error()); } @@ -404,6 +461,61 @@ class Test_CoordEvents : public UnitTest{ }; +// A detection the console can miss, missed in turn at each place the run +// makes it (#162). Each miss must either be got over (the run completes, +// every walk ending on its tiles) or stop the run in the step that missed: +// a miss that lets the run go on and fail later went unseen, and a later +// step started from somewhere it did not expect. +class Test_StorySimMisses : public UnitTest{ +public: + Test_StorySimMisses(std::string name, std::string from, std::string to) + : UnitTest("PokemonBDSP::AutoStory - Story sim, detector misses: " + std::move(name)) + , m_range{.from = std::move(from), .to = std::move(to)} + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + SimExecutor clean(logger); + if (!run_rows_on(clean, logger, m_range).completed){ + return "the run fails without misses: " + clean.error(); + } + std::vector runs; + for (size_t i = 0; i < clean.misses().fades; i++){ + runs.push_back({.fade = i}); + } + for (size_t i = 0; i < clean.misses().banners; i++){ + runs.push_back({.banner = i}); + } + logger.log(std::format("{} fades and {} banners to miss.", clean.misses().fades, clean.misses().banners)); + std::vector unseen; + for (const SimMisses& misses : runs){ + SimExecutor executor(logger, misses); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, m_range); + const std::string what = misses.fade ? std::format("fade {}", *misses.fade) : std::format("banner {}", *misses.banner); + logger.log(std::format("Missed {} in {}: {}.", what, executor.missed_step(), + report.completed ? "got over it" : "stopped in " + executor.failed_step() + ": " + executor.error())); + if (!report.completed && executor.failed_step() != executor.missed_step()){ + unseen.push_back(std::format("{} missed in {}, failed later in {}: {}", + what, executor.missed_step(), executor.failed_step(), executor.error())); + } + } + if (!unseen.empty()){ + std::string out = "Misses that went unseen:"; + for (const std::string& line : unseen){ + out += "\n " + line; + } + return out; + } + return true; + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + Pokemon::SegmentRange m_range; +}; + + class Test_StorySim : public UnitTest{ public: Test_StorySim(std::string name, std::string from, std::string to) @@ -431,6 +543,7 @@ void add_tests_AutoStory_StorySim(UnitTestDatabase& database){ database.add(); database.add("00.04 to 00.04d: home, the catch, Sandgem's Center, Route 202", "00.04", "00.04d"); database.add("00.05 to 00.05c: Jubilife's Center, School, clowns and Poketch", "00.05", "00.05c"); + database.add("00.04 to 00.05c", "00.04", "00.05c"); } From d5818159fa9af98dc08cd94e03fa36922444dd50 Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 3 Nov 2026 00:14:16 -0800 Subject: [PATCH 004/166] BDSP AutoStory sim: run the whole table, check every row's end The story sim ran only 00.04 to 00.05c. It now runs 00.00 to 01.11, the whole table and each row alone, with the program's own walking steps; scenes, events, battles and shops end where the table says. Each row must start where the row before left the player, and every walking step with a declared or worked-out end is checked against it in world tiles (a leg out of Twinleaf ends on Route 201's tiles). What it needed: the story variables of the coord events the table walks onto (00.01 to 00.03, 01.01 to 01.07), the houses' stairs as doors, Barry in Oreburgh's Center door until his lines (01.03), and B running only once the shoes' scene has given them (Route 201 timed a walk as a run). A tap or hold through a door or cave mouth that misses the fade now goes on onto the step's far side, and a banner reads three tiles into its map ("a tile or a few past the border"). The exit tests run r75's and r81's old open-ended walks that way: they end in Route 203's pond pocket (52, 9) and on Route 204's cliff (20, 30), and the end-tile check fails them; the table's taps to the banner never end there, whatever is missed. The detector-miss test covers the whole table (20 fades, 8 banners), each miss on its own row and the next. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 620 ++++++++++++++---- .../Utils/PokemonBDSP_AutoStory_GridSim.cpp | 5 +- .../Utils/PokemonBDSP_AutoStory_GridSim.h | 7 +- 3 files changed, 497 insertions(+), 135 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp index e8b368a84b..18835105ff 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -13,13 +13,22 @@ * heal checks that a walk north from where we stand enters a door. A scene * starts when the player steps onto one of the maps' coord events while * its story variable holds (story_vars()). Rooms with no - * map (the Trainers' School) are passed over. + * map (the Trainers' School) are passed over. Each row must start where + * the row before left the player. + * + * A tap or hold through a door or cave mouth stops on its tile, as the + * console stops at the fade; a hold that does not see the fade goes on + * onto the step's pose_after and on along it, and a location banner reads + * only a few tiles into its map (SIM_BANNER_TILES). The exit tests run + * r75's and r81's old open-ended walks that way. * */ #include #include #include +#include +#include #include #include #include @@ -74,13 +83,46 @@ struct SimMisses{ bool fade_unseen = false; }; -// StoryStepIO on the simulation. +// How many tiles a held walk goes on into a map before its location +// banner reads: "it shows a tile or a few past the border" (the table's +// route_201_by_the_path(), measured on the console). Standing still, it +// reads at once. Through a cave mouth the fade comes first, and a hold +// whose fade went unseen goes on the same way (r75, r81). +constexpr size_t SIM_BANNER_TILES = 3; + +// What a run on the simulation did. +struct SimRun{ + // The first failure, as "row outcome", or "". + std::string error; + // The rows and steps where an injected miss happened and where the run + // first failed, as "row step": "" if none. + std::string missed_step; + std::string failed_step; + // Walking steps that end where nothing says, as "row step". + std::vector unchecked; + // Each row run, with the fades and banners looked for before it. + struct RowStart{ + std::string row; + size_t fades; + size_t banners; + }; + std::vector rows; + // Where the player stood after the last step, if placed. + const StoryWorld* world = nullptr; + TilePos end; +}; + +// StoryStepIO on the simulation. A walk through a door or a cave mouth +// stops on its tile, as the console stops at the fade; a hold that misses +// the fade carries on, onto `far_side()` (the step's pose_after: the +// sim's maps have no warps' destinations) and on along it. class SimStoryStepIO : public StoryStepIO{ public: - SimStoryStepIO(GridSim& sim, std::vector& notes, SimMisses& misses) + SimStoryStepIO(GridSim& sim, std::vector& notes, SimMisses& misses, std::function far_side) : m_sim(sim) , m_route(sim, notes) , m_misses(misses) + , m_far_side(std::move(far_side)) {} virtual RouteIO& route() override{ @@ -89,58 +131,16 @@ class SimStoryStepIO : public StoryStepIO{ virtual void fight(const std::string&) override{ m_sim.end_dialogue(); } - virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string& label) override{ - m_sim.tap(direction, ROUTE_TURN_TAP, false); - const Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); - const SimMove move = m_sim.hold(direction, limit, SimPace::WALK); - if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ - m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); - } - } - virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override{ - const bool miss = m_misses.banner == m_misses.banners++; - for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ - const SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); - if (story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos))){ - if (miss){ - m_misses.missed = true; - continue; - } - return true; - } - if (move.distance == 0 || move.stop != SimStop::DONE){ - return false; - } - } - return false; - } + virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string& label) override; + virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; virtual bool run_into_door(Direction direction, bool run) override{ const bool warped = m_sim.hold(direction, 12000ms, run ? SimPace::RUN : SimPace::WALK).stop == SimStop::WARP; - if (warped && m_misses.fade == m_misses.fades++){ - m_misses.missed = true; + if (warped && fade_missed()){ m_misses.fade_unseen = true; return false; } return warped; } - // A banner miss: the fade was seen, the banner not within 8 s, so the - // step fails there, as on the console. - virtual std::optional tap_to_banner(Direction direction, const std::string&, size_t max_taps) override{ - for (size_t tap = 1; tap <= max_taps; tap++){ - const SimMove move = m_sim.tap(direction, 160ms, false); - if (move.stop == SimStop::WARP){ - if (m_misses.banner == m_misses.banners++){ - m_misses.missed = true; - return std::nullopt; - } - return tap; - } - if (move.stop == SimStop::DIALOG){ - return std::nullopt; - } - } - return std::nullopt; - } // A scene may take us to another map (Mom walks us out, 00.04): with a // dialogue open the stub scene plays it. Otherwise only a door fades. // A fade missed on the way in stays missed: it was over before settle() @@ -152,13 +152,92 @@ class SimStoryStepIO : public StoryStepIO{ m_misses.fade_unseen = false; m_sim.end_dialogue(); } + virtual std::optional tap_to_banner(Direction direction, const std::string& map, size_t max_taps) override; private: + // Whether the run misses this fade or this banner (SimMisses). + bool fade_missed(){ + const bool miss = m_misses.fade == m_misses.fades++; + m_misses.missed |= miss; + return miss; + } + bool banner_missed(){ + const bool miss = m_misses.banner == m_misses.banners++; + m_misses.missed |= miss; + return miss; + } + bool on_map(const std::string& map) const{ + return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); + } + GridSim& m_sim; GridSimRouteIO m_route; SimMisses& m_misses; + std::function m_far_side; }; +// A hold until something stops us. A door stops it at the fade, which +// fails the step; a fade missed lets the hold go on past the mouth (r81's +// timed walk south out of the Ravaged Path, onto Route 204's cliff). +void SimStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ + m_sim.tap(direction, ROUTE_TURN_TAP, false); + Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); + SimMove move = m_sim.hold(direction, limit, SimPace::WALK); + if (move.stop == SimStop::WARP && fade_missed() && m_far_side()){ + limit -= std::min(limit, move.time); + move = m_sim.hold(direction, limit, SimPace::WALK); + } + if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ + m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); + } +} + +// The D-pad, a tile at a time, until `map`'s banner reads; through a door +// the walk goes on beyond it (the fade eats no tiles of a hold). +bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&){ + const bool miss = banner_missed(); + size_t on = 0; + for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ + SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + const bool crossed = move.stop == SimStop::WARP && m_far_side(); + const bool stopped = !crossed && (move.distance == 0 || move.stop != SimStop::DONE); + on = on_map(map) ? on + 1 : 0; + if (on > 0 && (on > SIM_BANNER_TILES || stopped) && !miss){ + return true; + } + if (stopped){ + return false; + } + } + return false; +} + +// D-pad taps, each looked at, until the fade and then the banner (the +// console's ConsoleStoryStepIO::tap_to_banner()). Each look stands still, +// so a banner on the far side reads at once. A fade seen ends the taps, +// banner or not; with the fade missed the next look still sees the banner. +std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ + bool crossed = false; + for (size_t tap = 1; tap <= max_taps; tap++){ + const SimMove move = m_sim.tap(direction, 160ms, false); + if (move.stop == SimStop::DIALOG){ + return std::nullopt; + } + bool faded = false; + if (move.stop == SimStop::WARP){ + faded = !fade_missed(); + crossed = m_far_side(); + } + if (crossed && on_map(map) && !banner_missed()){ + return tap; + } + if (faded){ + return std::nullopt; + } + } + return std::nullopt; +} + // A scene's trigger the simulation fires from row `row` on, once the step // `after` has run ("" from the row's start), on `map`'s `tiles`. @@ -178,14 +257,36 @@ struct VarState{ std::string after; }; -// The story variables of 00.04 to 00.05c: Dawn's catching tutorial waits on -// Route 202 from 00.04's start, Mom calls us back once she has healed us, -// and the Poketch president waits on Jubilife's row 40 in 00.05b. +// The story variables whose coord events the table walks onto, from the +// row (and step) the table's reasons give, with the maps' coord events +// (Diamond's zone events; Platinum's for the houses): Barry's doorstep and +// Mom's warning in 00.01, Barry's Route 201 warning, then its pull-back +// row 19 once he has warned us (r14, r16); the lake's entrance in 00.02; +// Rowan's stop and Dawn at Sandgem's edge in 00.03; Dawn's catching +// tutorial on Route 202 from 00.04's start, Mom's call once she has healed +// us; the Poketch president on Jubilife's row 40 in 00.05b; Barry on Route +// 203 in 01.01; the Gate's Hiker and Oreburgh's welcome in 01.02; Barry's +// bump in Oreburgh after Roark in 01.05; and Rowan in Jubilife in 01.07. +// Left out: the Twinleaf guitarist (spent upstairs), Platinum's rival +// steps around our bedroom's start, Dawn at Jubilife's steps (BDSP starts +// her below them: an event), and Floaroma's (10..12, 29) (Diamond only). std::vector story_vars(){ return { + {.var = "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", .value = 0, .row = "00.01", .after = ""}, + {.var = "VAR_PLAYER_HOUSE_STATE", .value = 1, .row = "00.01", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 0, .row = "00.01", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 1, .row = "00.01", .after = "barry_warns_us"}, + {.var = "VAR_VERITY_LAKEFRONT_STATE", .value = 0, .row = "00.02", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 2, .row = "00.03", .after = ""}, + {.var = "VAR_SANDGEM_TOWN_STATE", .value = 0, .row = "00.03", .after = ""}, {.var = "VAR_ROUTE_202_STATE", .value = 0, .row = "00.04", .after = ""}, {.var = "CONSOLE_MOMS_CALL", .value = 0, .row = "00.04", .after = "mom_heals_us"}, {.var = "VAR_POKETCH_CAMPAIGN_STATE", .value = 1, .row = "00.05b", .after = ""}, + {.var = "VAR_ROUTE_203_RIVAL_STATE", .value = 0, .row = "01.01", .after = ""}, + {.var = "VAR_OREBURGH_GATE_1F_HIKER_STATE", .value = 1, .row = "01.02", .after = ""}, + {.var = "VAR_OREBURGH_CITY_STATE", .value = 0, .row = "01.02", .after = ""}, + {.var = "VAR_OREBURGH_CITY_STATE", .value = 2, .row = "01.05", .after = ""}, + {.var = "VAR_JUBILIFE_CITY_STATE", .value = 3, .row = "01.07", .after = ""}, }; } @@ -217,37 +318,64 @@ std::vector story_triggers(){ } +// Someone the maps do not have, who stands on `tile` of `map` and is +// talked to there or walked round: from row `row` on if `until` is "", +// else in `row` until its step `until` has run. +struct SimPerson{ + std::string name; + std::string map; + TilePos tile; + std::string row; + std::string until; +}; +std::vector sim_people(){ + return { + // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). + {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04", .until = ""}, + // Barry stands in the Center's door until his lines (01.03; Roark + // ignored A until then, r101 and r104). + {.name = "barry", .map = "OreburghCity", .tile = {47, 20}, .row = "01.03", .until = "barrys_lines"}, + }; +} + +// A house's stairs, entered by a step `side` from the map's "stairs" +// point into what the map draws as a wall (the table's 00.01: r8 and r9 +// for ours, r11 for Barry's). +struct SimStairs{ + std::string map; + Direction side; +}; +std::vector sim_stairs(){ + return { + {.map = "PlayerHouse2F", .side = Direction::EAST}, + {.map = "RivalHouse1F", .side = Direction::EAST}, + {.map = "RivalHouse2F", .side = Direction::WEST}, + }; +} + + // The program's walking steps on the simulation, the rest stubbed. class SimExecutor : public Pokemon::StoryStepExecutor{ public: explicit SimExecutor(Logger& logger, SimMisses misses = {}) : m_logger(logger) , m_misses(misses) - , m_sim({}, {0, 0}, Direction::NORTH, true) - , m_io(m_sim, m_notes, m_misses) + , m_sim({}, {0, 0}, Direction::NORTH, false) + , m_io(m_sim, m_notes, m_misses, [this]{ return cross(); }) , m_walks(m_io) - { - // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). - m_house = *story_plan_world("PlayerHouse1F", "PlayerHouse1F"); - m_house.block({7, 7}); - } + {} - const std::string& error() const{ - return m_error; - } const SimMisses& misses() const{ return m_misses; } - // The row and step where an injected miss happened, and where the run - // first failed: "" if none. - const std::string& missed_step() const{ - return m_missed_step; - } - const std::string& failed_step() const{ - return m_failed_step; + const SimRun& result() const{ + return m_result; } virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ m_row = data.id; + m_start_mismatch = data.start ? off_pose(*data.start) : ""; + m_ran.clear(); + m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); m_walks.begin_attempt(data.id); arm(""); } @@ -279,7 +407,9 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ SimWorld setup(const StoryWorld* world) const; void arm(const std::string& after); bool sync(const Pose& pose, const StoryWorld* on = nullptr); - std::string check(const StoryStep& step, const Outcome& outcome) const; + bool cross(); + std::string off_pose(const Pose& pose) const; + std::string check(const StoryStep& step, const Outcome& outcome); Outcome run_step(RunState& state, const StoryStep& step); Logger& m_logger; @@ -288,30 +418,57 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ GridSim m_sim; SimStoryStepIO m_io; StoryWalkSteps m_walks; - StoryWorld m_house; + // The planner's worlds with sim_people() on them, by world and who. + mutable std::map, std::unique_ptr> m_peopled; + // The steps of this row that have run. + std::set m_ran; std::string m_row; std::vector m_armed; + // Where the step running now ends, if it says: a door's far side. + std::optional m_far; + // Why the player is not on this row's start, or "". + std::string m_start_mismatch; // Whether the player has been put on a map yet. bool m_placed = false; // Whether the step running now is on a room with no map. bool m_passed_over = false; - std::string m_error; - std::string m_missed_step; - std::string m_failed_step; + SimRun m_result; }; // The world the player walks on for `map`: the planner's, with what the // console showed that the maps lack. Nothing for a room with no map. const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ const StoryWorld* world = story_plan_world(map, map); - if (world == story_plan_world("PlayerHouse1F", "PlayerHouse1F") && m_row >= "00.04"){ - return &m_house; + std::vector here; + std::string who; + for (const SimPerson& person : sim_people()){ + const bool now = person.until.empty() ? m_row >= person.row : m_row == person.row && !m_ran.contains(person.until); + if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ + here.push_back(person); + who += person.name + ";"; + } } - return world; + if (here.empty()){ + return world; + } + std::unique_ptr& peopled = m_peopled[{world, who}]; + if (!peopled){ + peopled = std::make_unique(*world); + for (const SimPerson& person : here){ + peopled->block(story_to_world(*world, person.map, person.tile)); + } + } + return peopled.get(); } SimWorld SimExecutor::setup(const StoryWorld* world) const{ - SimWorld out{.world = world, .trainers = story_trainers(*world)}; + // B runs once the shoes' scene has given them: the scene ends at home. + SimWorld out{.world = world, .trainers = story_trainers(*world), .can_run = m_walks.can_run()}; + for (const SimStairs& stairs : sim_stairs()){ + if (sim_world(stairs.map) == world){ + out.doors.push_back(story_to_world(*world, stairs.map, map_point(stairs.map, "stairs").next(stairs.side))); + } + } for (const RowTrigger& armed : m_armed){ if (sim_world(armed.map) != world){ continue; @@ -340,8 +497,9 @@ void SimExecutor::arm(const std::string& after){ } } -// Puts the player on `pose` unless they stand on one of its tiles already. -// Returns whether the pose is on a map the simulation has. +// Puts the player on `pose`, on the world `on` if given, unless they stand +// on one of its tiles already. Returns whether the pose is on a map the +// simulation has. bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ const std::vector tiles = Pokemon::tiles_of(pose); const StoryWorld* world = on != nullptr ? on : pose.map.empty() ? nullptr : sim_world(pose.map); @@ -359,6 +517,39 @@ bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ return true; } +// Through a door or a cave mouth onto the step's far side, the player's +// facing kept: a hold goes on from there. +bool SimExecutor::cross(){ + const StoryWorld* world = m_far ? sim_world(m_far->map) : nullptr; + const std::vector tiles = m_far ? Pokemon::tiles_of(*m_far) : std::vector{}; + if (world == nullptr || tiles.empty()){ + return false; + } + m_sim.place(setup(world), story_to_world(*world, m_far->map, tiles.front()), std::nullopt); + return true; +} + +// Why the player does not stand on one of `pose`'s tiles, or "" if they +// do or the simulation cannot tell (no map, or not placed yet). +std::string SimExecutor::off_pose(const Pose& pose) const{ + const std::vector tiles = Pokemon::tiles_of(pose); + if (!m_placed || tiles.empty() || sim_world(pose.map) == nullptr){ + return ""; + } + const SimPlayer& player = m_sim.player(); + const TilePos at = nearest_tile(player.pos); + // In world tiles: a pose a leg worked out from the map it started on + // may lie past that map's edge, on the next map (Twinleaf's exit). + // story_to_world() throws for a map not on the player's world. + try{ + const auto there = [&](const TilePos& tile){ return story_to_world(m_sim.world(), pose.map, tile) == at; }; + if (on_grid(player.pos) && std::ranges::any_of(tiles, there)){ + return ""; + } + }catch (const InternalProgramError&){} + return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), at), Pokemon::to_string(pose)); +} + Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ if (sync(state.pose) && m_sim.hold(Direction::NORTH, 3000ms, SimPace::RUN).stop != SimStop::WARP){ return Pokemon::outcome_failed("no_door", step.name + ": no door north of " + to_string(m_sim.player().pos)); @@ -366,39 +557,42 @@ Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ return Pokemon::outcome_ok(); } -// Why a walking step did not end where the table says, or "". -std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome) const{ +// Why a walking step did not end where the table says, or "". A step +// through a door the simulation did not cross is not checked: the sim's +// maps have no warps' destinations. +std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP; const std::optional expected = step.pose_after ? step.pose_after : outcome.pose; - if (!walks || !expected || Pokemon::tiles_of(*expected).empty() || !m_placed){ + if (!walks || !m_placed){ return ""; } - const SimPlayer& player = m_sim.player(); - const std::optional local = story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos)); - if (!local){ - return player.warped ? "" : std::format("ended on {} at {}, not on {}.", describe(m_sim.world(), nearest_tile(player.pos)), - to_string(player.pos), expected->map); + if (!expected || Pokemon::tiles_of(*expected).empty()){ + m_result.unchecked.push_back(m_row + " " + step.name); + return ""; } - const std::vector tiles = Pokemon::tiles_of(*expected); - if (!on_grid(player.pos) || std::find(tiles.begin(), tiles.end(), *local) == tiles.end()){ - return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), nearest_tile(player.pos)), - Pokemon::to_string(*expected)); + const SimPlayer& player = m_sim.player(); + if (player.warped && !story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos))){ + return ""; } - return ""; + return off_pose(*expected); } Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ + if (!m_start_mismatch.empty()){ + return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); + } + m_far = step.pose_after; if (story_events().contains(step.variant)){ return stub(); } - // A scene goes on from where the step before left us. + // A scene goes on from where the step before left us. A route walks + // on the world it plans on (Jubilife alone has no Route 204 north of it). const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK; - // A route walks on the world it plans on (Jubilife alone has no Route - // 204 north of it); the house keeps Mom where the console showed her. const StoryWorld* on = step.kind == StoryStepKind::ROUTE && step.target && !state.pose.map.empty() ? story_plan_world(state.pose.map, step.target->map) : nullptr; - if (on != nullptr && on == story_plan_world("PlayerHouse1F", "PlayerHouse1F")){ + // A world of one map is sim_world()'s, with its people. + if (on != nullptr && on == story_plan_world(state.pose.map, state.pose.map)){ on = nullptr; } if (walks && !sync(state.pose, on)){ @@ -421,23 +615,39 @@ Outcome SimExecutor::run(RunState& state, const StoryStep& step){ if (!mismatch.empty()){ outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); } + // What the simulation does not play (scenes, events, battles) ends + // where the table says it does. + if (outcome.succeeded() && step.pose_after){ + sync(*step.pose_after); + } m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); - if (std::exchange(m_misses.missed, false) && m_missed_step.empty()){ - m_missed_step = m_row + " " + step.name; + if (std::exchange(m_misses.missed, false) && m_result.missed_step.empty()){ + m_result.missed_step = m_row + " " + step.name; } - if (!outcome.succeeded() && m_error.empty()){ - m_error = m_row + " " + Pokemon::to_string(outcome); - m_failed_step = m_row + " " + step.name; + if (!outcome.succeeded() && m_result.error.empty()){ + // The walker's last notes, to see why. + for (size_t i = m_notes.size() - std::min(m_notes.size(), 40); i < m_notes.size(); i++){ + m_logger.log(std::format("[{}] note: {}", m_row, m_notes[i])); + } + m_result.error = m_row + " " + Pokemon::to_string(outcome); + m_result.failed_step = m_row + " " + step.name; } + m_result.world = m_placed ? &m_sim.world() : nullptr; + m_result.end = nearest_tile(m_sim.player().pos); + m_ran.insert(step.name); arm(step.name); return outcome; } -// Runs `range` of the table on `executor`, stopping at the first failure. -Pokemon::SegmentReport run_rows_on(SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range){ +// Runs `range` of `rows` (the table unless given) on `executor`, stopping +// at the first failure. +Pokemon::SegmentReport run_rows_on( + SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, + const std::vector& rows = story_checkpoints() +){ std::set saved; - Pokemon::Segment segment = make_story_segment(story_checkpoints(), executor, saved); + Pokemon::Segment segment = make_story_segment(rows, executor, saved); Pokemon::SegmentPolicy policy; policy.stop_at_first_failure = true; Pokemon::SegmentHooks hooks; @@ -451,12 +661,143 @@ Pokemon::SegmentReport run_rows_on(SimExecutor& executor, Logger& logger, const UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ SimExecutor executor(logger); const Pokemon::SegmentReport report = run_rows_on(executor, logger, range); + for (const std::string& step : executor.result().unchecked){ + logger.log("No end to check after " + step + "."); + } if (!report.completed){ - return std::format("stopped at {} {}: {}", report.failed_checkpoint, report.failed_event, executor.error()); + return std::format("stopped at {} {}: {}", report.failed_checkpoint, report.failed_event, executor.result().error); } return true; } +// The table with row `row`'s step of `step`'s name replaced by `step`. +std::vector table_with(const std::string& row, const StoryStep& step){ + std::vector rows = story_checkpoints(); + for (StoryCheckpoint& checkpoint : rows){ + for (StoryStep& old : checkpoint.steps){ + if (checkpoint.id == row && old.name == step.name){ + old = step; + return rows; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + step.name + " in " + row); +} + +bool ends_on(const SimRun& run, const Pose& pose){ + const std::vector tiles = Pokemon::tiles_of(pose); + const std::optional local = run.world ? story_to_local(*run.world, pose.map, run.end) : std::nullopt; + return local && std::find(tiles.begin(), tiles.end(), *local) != tiles.end(); +} +std::string end_of(const SimRun& run){ + return run.world ? describe(*run.world, run.end) : "nowhere"; +} + + +// A way out of a map that a hold walked on past (r75, r81), against the +// table's tap to the banner. The old step, with `misses`, must end on +// `overshoot`, caught there by the end-tile check. The table's step must +// never end there, whichever one fade or banner of the row is missed: it +// ends on its tile or stops in that step. +class Test_StorySimExit : public UnitTest{ +public: + Test_StorySimExit(std::string name, std::string row, StoryStep old_step, SimMisses misses, Pose overshoot) + : UnitTest("PokemonBDSP::AutoStory - Story sim, exits: " + std::move(name)) + , m_row(std::move(row)) + , m_old(std::move(old_step)) + , m_misses(std::move(misses)) + , m_overshoot(std::move(overshoot)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + const std::string old = old_form(logger); + return old.empty() ? table_form(logger) : UnitTestResult(old); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + // Why the old step did not go wrong as on the console, or "". + std::string old_form(Logger& logger) const{ + SimExecutor executor(logger, m_misses); + const std::vector rows = table_with(m_row, m_old); + run_rows_on(executor, logger, {.from = m_row, .to = m_row}, rows); + const SimRun& run = executor.result(); + logger.log(std::format("The old {}: {}, ended on {}.", m_old.name, run.error, end_of(run))); + if (run.failed_step != m_row + " " + m_old.name || !ends_on(run, m_overshoot)){ + return std::format("the old {} should end on {} and fail there; it ended on {}: {}", + m_old.name, Pokemon::to_string(m_overshoot), end_of(run), run.error.empty() ? "no failure" : run.error); + } + return ""; + } + UnitTestResult table_form(Logger& logger) const{ + SimExecutor clean(logger); + if (!run_rows_on(clean, logger, {.from = m_row, .to = m_row}).completed){ + return "the table's row fails without misses: " + clean.result().error; + } + std::vector runs; + for (size_t i = 0; i < clean.misses().fades; i++){ + runs.push_back({.fade = i}); + } + for (size_t i = 0; i < clean.misses().banners; i++){ + runs.push_back({.banner = i}); + } + for (const SimMisses& misses : runs){ + SimExecutor executor(logger, misses); + run_rows_on(executor, logger, {.from = m_row, .to = m_row}); + if (ends_on(executor.result(), m_overshoot)){ + return std::format("the table's {} ended on {} with a miss in {}.", m_old.name, end_of(executor.result()), + executor.result().missed_step); + } + } + return true; + } + + std::string m_row; + StoryStep m_old; + SimMisses m_misses; + Pose m_overshoot; +}; + +// r75: out of the Oreburgh Gate as a run west until Route 203's banner +// (the old event west_until_transition()). The banner reads a few tiles +// in: the run ends west of the Gate's warp tile (55, 9), in the pocket by +// the pond (Route 203's x 49 to 54, rows 6 to 13). +StoryStep r75_old_gate_exit(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "out_of_oreburgh_gate"; + step.legs = {{.direction = Direction::WEST, .tiles = 8}}; + step.variant = "to_map"; + step.pose_after = Pokemon::tile_pose("Route203", {TilePos{55, 9}}, Direction::WEST); + return step; +} +Pose r75_pond_pocket(){ + std::vector tiles; + for (int y = 6; y <= 13; y++){ + for (int x = 49; x <= 54; x++){ + tiles.push_back({x, y}); + } + } + return Pokemon::tile_pose("Route203", tiles); +} +// r81: out of the Ravaged Path as a timed walk south (the old event's +// 4 s walk_dir()), its fade missed: on past cave_exit (20, 26) to the +// cliff, column 20 down to row 30. +StoryStep r81_old_cave_exit(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "out_of_the_ravaged_path"; + step.legs = {{.direction = Direction::SOUTH, .tiles = 4}}; + step.variant = "to_wall"; + step.pose_after = Pokemon::tile_pose("Route204North", {TilePos{20, 26}}, Direction::SOUTH); + return step; +} +Pose r81_below_the_mouth(){ + return Pokemon::tile_pose("Route204North", {TilePos{20, 27}, TilePos{20, 28}, TilePos{20, 29}, TilePos{20, 30}}); +} + // Every coord event has ground the player can step onto, and the ones // the story's variables arm are there. @@ -490,7 +831,8 @@ class Test_CoordEvents : public UnitTest{ // makes it (#162). Each miss must either be got over (the run completes, // every walk ending on its tiles) or stop the run in the step that missed: // a miss that lets the run go on and fail later went unseen, and a later -// step started from somewhere it did not expect. +// step started from somewhere it did not expect. Each miss runs its own +// row and the next, which checks where the row left us. class Test_StorySimMisses : public UnitTest{ public: Test_StorySimMisses(std::string name, std::string from, std::string to) @@ -501,42 +843,50 @@ class Test_StorySimMisses : public UnitTest{ try{ SimExecutor clean(logger); if (!run_rows_on(clean, logger, m_range).completed){ - return "the run fails without misses: " + clean.error(); - } - std::vector runs; - for (size_t i = 0; i < clean.misses().fades; i++){ - runs.push_back({.fade = i}); - } - for (size_t i = 0; i < clean.misses().banners; i++){ - runs.push_back({.banner = i}); + return "the run fails without misses: " + clean.result().error; } logger.log(std::format("{} fades and {} banners to miss.", clean.misses().fades, clean.misses().banners)); std::vector unseen; - for (const SimMisses& misses : runs){ - SimExecutor executor(logger, misses); - const Pokemon::SegmentReport report = run_rows_on(executor, logger, m_range); - const std::string what = misses.fade ? std::format("fade {}", *misses.fade) : std::format("banner {}", *misses.banner); - logger.log(std::format("Missed {} in {}: {}.", what, executor.missed_step(), - report.completed ? "got over it" : "stopped in " + executor.failed_step() + ": " + executor.error())); - if (!report.completed && executor.failed_step() != executor.missed_step()){ - unseen.push_back(std::format("{} missed in {}, failed later in {}: {}", - what, executor.missed_step(), executor.failed_step(), executor.error())); + for (size_t i = 0; i < clean.misses().fades + clean.misses().banners; i++){ + const std::string line = miss(logger, clean.result(), i < clean.misses().fades, i < clean.misses().fades ? i : i - clean.misses().fades); + if (!line.empty()){ + unseen.push_back(line); } } - if (!unseen.empty()){ - std::string out = "Misses that went unseen:"; - for (const std::string& line : unseen){ - out += "\n " + line; - } - return out; + std::string out = "Misses that went unseen:"; + for (const std::string& line : unseen){ + out += "\n " + line; } - return true; + return unseen.empty() ? UnitTestResult(true) : UnitTestResult(out); }catch (Exception& e){ return std::string(e.name()) + ": " + e.message(); } } private: + // Misses the `index`th fade (or banner) of the clean run `clean` in its + // row. Returns how it went unseen, or "". + static std::string miss(Logger& logger, const SimRun& clean, bool fade, size_t index){ + size_t k = 0; + while (k + 1 < clean.rows.size() && (fade ? clean.rows[k + 1].fades : clean.rows[k + 1].banners) <= index){ + k++; + } + const SimRun::RowStart& start = clean.rows[k]; + SimMisses misses; + (fade ? misses.fade : misses.banner) = index - (fade ? start.fades : start.banners); + SimExecutor executor(logger, misses); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, + {.from = start.row, .to = clean.rows[std::min(k + 1, clean.rows.size() - 1)].row}); + const SimRun& run = executor.result(); + const std::string what = std::format("{} {}", fade ? "fade" : "banner", index); + logger.log(std::format("Missed {} in {}: {}.", what, run.missed_step, + report.completed ? "got over it" : "stopped in " + run.failed_step + ": " + run.error)); + if (report.completed || run.failed_step == run.missed_step){ + return ""; + } + return std::format("{} missed in {}, failed later in {}: {}", what, run.missed_step, run.failed_step, run.error); + } + Pokemon::SegmentRange m_range; }; @@ -566,9 +916,13 @@ class Test_StorySim : public UnitTest{ void add_tests_AutoStory_StorySim(UnitTestDatabase& database){ database.add(); - database.add("00.04 to 00.04d: home, the catch, Sandgem's Center, Route 202", "00.04", "00.04d"); - database.add("00.05 to 00.05c: Jubilife's Center, School, clowns and Poketch", "00.05", "00.05c"); - database.add("00.04 to 00.05c", "00.04", "00.05c"); + database.add("00.00 to 01.11", "00.00", "01.11"); + database.add("00.00 to 01.11: the whole table, from the new game to Floaroma", "00.00", "01.11"); + for (const StoryCheckpoint& row : story_checkpoints()){ + database.add(std::format("row {}", row.id), row.id, row.id); + } + database.add("r75, out of the Oreburgh Gate", "01.05", r75_old_gate_exit(), SimMisses{}, r75_pond_pocket()); + database.add("r81, out of the Ravaged Path", "01.09", r81_old_cave_exit(), SimMisses{.fade = 0}, r81_below_the_mouth()); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.cpp index 302b175634..ab0bc9134b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.cpp @@ -117,6 +117,9 @@ void GridSim::place(SimWorld world, const TilePos& start, std::optional GridSim::enter_next(Direction direction, int part, int& m const std::optional landing = PokemonBDSP::step(world, from, direction); if (landing && *landing != ahead[0]){ part = 2 * SIM_TILE; - }else if (!landing && is_door(world, ahead[0])){ + }else if (!landing && (is_door(world, ahead[0]) || std::find(m_world.doors.begin(), m_world.doors.end(), ahead[0]) != m_world.doors.end())){ m_player.pos = sim_pos(ahead[0]); m_player.warped = ahead[0]; moved += SIM_TILE; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.h index 4cb6b329fc..f28b20d067 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.h @@ -64,11 +64,16 @@ struct SimTrigger{ }; // Where the simulated player walks: the world (which must outlive the -// simulation), its trainers and its scene triggers, in world tiles. +// simulation), its trainers and its scene triggers, in world tiles; and +// the tiles that warp like doors though the maps draw them as walls (a +// house's stairs, entered from beside them); and, if the caller knows, +// whether B runs from here on (the Running Shoes, 00.03). struct SimWorld{ const StoryWorld* world = nullptr; std::vector trainers = {}; std::vector triggers = {}; + std::vector doors = {}; + std::optional can_run = std::nullopt; }; enum class SimStop{ From a9b57b2e2acc019726159fc775981e74d5a9eb27 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 5 Nov 2026 22:43:05 -0800 Subject: [PATCH 005/166] BDSP AutoStory sim: align with PR #231 lint conventions --- .../PokemonBDSP_AutoStory_CoordEvents.cpp | 8 +- .../Data/PokemonBDSP_AutoStory_CoordEvents.h | 7 +- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 54 +- .../PokemonBDSP_AutoStory_GridSim_Tests.h | 6 +- .../PokemonBDSP_AutoStory_StoryExecutor.cpp | 6 +- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 1852 ++++++++--------- .../PokemonBDSP_AutoStory_StorySim_Tests.h | 6 +- .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 8 +- .../PokemonBDSP_AutoStory_StoryStepIO.h | 7 +- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 8 +- .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 7 +- .../Utils/PokemonBDSP_AutoStory_GridSim.cpp | 10 +- .../Utils/PokemonBDSP_AutoStory_GridSim.h | 10 +- 13 files changed, 1006 insertions(+), 983 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp index 3a500b0a54..c3fe3fea36 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp @@ -85,7 +85,7 @@ std::vector read_events(const std::string& name, const std::string& return events; } -} +} // namespace const std::vector& story_coord_events(std::string_view map){ @@ -104,6 +104,6 @@ const std::vector& story_coord_events(std::string_view map){ -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h index 2c38f3c9df..51f2d8514a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h @@ -28,6 +28,7 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ +// Coordinate-triggered event parsed from BDSP map data. struct CoordEvent{ std::string name; // The map's own tiles: `width` columns from x, `length` rows from y. @@ -44,7 +45,7 @@ const std::vector& story_coord_events(std::string_view map); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 8d5d49b517..785c6a9638 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -384,35 +384,63 @@ UnitTestResult test_door_routes(Logger& logger){ } +struct AutoStoryGridSimInput{ + std::string name; + std::function body; +}; + +struct AutoStoryGridSimExpectation{ +}; + +struct AutoStoryGridSimCase{ + AutoStoryGridSimInput input; + AutoStoryGridSimExpectation expectation; +}; + class Test_GridSim : public UnitTest{ public: - Test_GridSim(std::string name, std::function body) - : UnitTest("PokemonBDSP::AutoStory - Grid sim: " + std::move(name)) - , m_body(std::move(body)) + explicit Test_GridSim(AutoStoryGridSimCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Grid sim: " + test_case.input.name) + , m_case(std::move(test_case)) {} virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ try{ - return m_body(logger); + return m_case.input.body(logger); }catch (Exception& e){ return std::string(e.name()) + ": " + e.message(); } } private: - std::function m_body; + AutoStoryGridSimCase m_case; }; -} - +} // namespace + + +const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { + { + .input = {"taps, holds, stick offsets, doors, people and trainers as measured", test_moves}, + .expectation = {}, + }, + { + .input = {"the table's routes end on their targets", test_table_routes}, + .expectation = {}, + }, + { + .input = {"a stick-tap turn misses the Sandgem Center and Jubilife School doors", test_door_routes}, + .expectation = {}, + }, +}; void add_tests_AutoStory_GridSim(UnitTestDatabase& database){ - database.add("taps, holds, stick offsets, doors, people and trainers as measured", test_moves); - database.add("the table's routes end on their targets", test_table_routes); - database.add("a stick-tap turn misses the Sandgem Center and Jubilife School doors", test_door_routes); + for (const auto& item : AUTO_STORY_GRID_SIM_CASES){ + database.add(item); + } } -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.h index 16c74d7cce..d80dd04f8b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.h @@ -22,7 +22,7 @@ void add_tests_AutoStory_GridSim(UnitTestDatabase& database); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp index 9008d1f9f1..5b8f8ef3dd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp @@ -320,6 +320,6 @@ Pokemon::Segment make_story_segment( -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 18835105ff..af21d4bf85 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -1,932 +1,920 @@ -/* BDSP AutoStory Story Sim Tests - * - * From: https://github.com/PokemonAutomation/ - * - * Rows of the story table run as the program runs them (the segment - * runner, make_story_segment()), with the program's own walking steps - * (StoryWalkSteps: ROUTE, LEGS, STEP, TALK, MASH) on the grid simulation. - * After each walking step the simulated player must stand, on the grid, - * on a tile the table gives; a step through a door must have warped. - * - * Events, battles, shops and saves are stubs: a dialogue they open is - * closed, and the table's pose_after puts the player where they end. A - * heal checks that a walk north from where we stand enters a door. A scene - * starts when the player steps onto one of the maps' coord events while - * its story variable holds (story_vars()). Rooms with no - * map (the Trainers' School) are passed over. Each row must start where - * the row before left the player. - * - * A tap or hold through a door or cave mouth stops on its tile, as the - * console stops at the fade; a hold that does not see the fade goes on - * onto the step's pose_after and on along it, and a location banner reads - * only a few tiles into its map (SIM_BANNER_TILES). The exit tests run - * r75's and r81's old open-ended walks that way. - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" -#include "Pokemon/AutoStory/Pokemon_StorySegments.h" -#include "Pokemon/AutoStory/Pokemon_TilePose.h" -#include "Data/PokemonBDSP_AutoStory_CoordEvents.h" -#include "Data/PokemonBDSP_AutoStory_Maps.h" -#include "Utils/PokemonBDSP_AutoStory_GridSim.h" -#include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" -#include "PokemonBDSP_AutoStory_Events.h" -#include "PokemonBDSP_AutoStory_StoryExecutor.h" -#include "PokemonBDSP_AutoStory_StoryPlaces.h" -#include "PokemonBDSP_AutoStory_StoryStepIO.h" -#include "PokemonBDSP_AutoStory_StoryTable.h" -#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" -#include "PokemonBDSP_AutoStory_StorySim_Tests.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -namespace{ - -using namespace std::chrono_literals; -using Pokemon::Direction; -using Pokemon::Outcome; -using Pokemon::Pose; -using Pokemon::RunState; -using Pokemon::StoryStep; -using Pokemon::StoryStepKind; -using Pokemon::TilePos; - - -// Which detections the simulation misses on purpose (#162): the `fade`th -// door fade (run_into_door(), from 0) or the `banner`th map banner -// (run_until_map()) of the run goes unseen, though the player did go -// through. The console missed both (r75, r81). -// The counts and flags below are the run's: how many fades and banners it -// looked for, whether a miss happened since the executor last looked, and -// whether a missed fade is still unseen. -struct SimMisses{ - std::optional fade; - std::optional banner; - size_t fades = 0; - size_t banners = 0; - bool missed = false; - bool fade_unseen = false; -}; - -// How many tiles a held walk goes on into a map before its location -// banner reads: "it shows a tile or a few past the border" (the table's -// route_201_by_the_path(), measured on the console). Standing still, it -// reads at once. Through a cave mouth the fade comes first, and a hold -// whose fade went unseen goes on the same way (r75, r81). -constexpr size_t SIM_BANNER_TILES = 3; - -// What a run on the simulation did. -struct SimRun{ - // The first failure, as "row outcome", or "". - std::string error; - // The rows and steps where an injected miss happened and where the run - // first failed, as "row step": "" if none. - std::string missed_step; - std::string failed_step; - // Walking steps that end where nothing says, as "row step". - std::vector unchecked; - // Each row run, with the fades and banners looked for before it. - struct RowStart{ - std::string row; - size_t fades; - size_t banners; - }; - std::vector rows; - // Where the player stood after the last step, if placed. - const StoryWorld* world = nullptr; - TilePos end; -}; - -// StoryStepIO on the simulation. A walk through a door or a cave mouth -// stops on its tile, as the console stops at the fade; a hold that misses -// the fade carries on, onto `far_side()` (the step's pose_after: the -// sim's maps have no warps' destinations) and on along it. -class SimStoryStepIO : public StoryStepIO{ -public: - SimStoryStepIO(GridSim& sim, std::vector& notes, SimMisses& misses, std::function far_side) - : m_sim(sim) - , m_route(sim, notes) - , m_misses(misses) - , m_far_side(std::move(far_side)) - {} - - virtual RouteIO& route() override{ - return m_route; - } - virtual void fight(const std::string&) override{ - m_sim.end_dialogue(); - } - virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string& label) override; - virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; - virtual bool run_into_door(Direction direction, bool run) override{ - const bool warped = m_sim.hold(direction, 12000ms, run ? SimPace::RUN : SimPace::WALK).stop == SimStop::WARP; - if (warped && fade_missed()){ - m_misses.fade_unseen = true; - return false; - } - return warped; - } - // A scene may take us to another map (Mom walks us out, 00.04): with a - // dialogue open the stub scene plays it. Otherwise only a door fades. - // A fade missed on the way in stays missed: it was over before settle() - // looked, which then fails as it does on the console after 120 s. - virtual void settle(Button, const std::string& label, bool fade) override{ - if (fade && ((!m_sim.player().warped && !m_sim.player().dialog) || m_misses.fade_unseen)){ - m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); - } - m_misses.fade_unseen = false; - m_sim.end_dialogue(); - } - virtual std::optional tap_to_banner(Direction direction, const std::string& map, size_t max_taps) override; - -private: - // Whether the run misses this fade or this banner (SimMisses). - bool fade_missed(){ - const bool miss = m_misses.fade == m_misses.fades++; - m_misses.missed |= miss; - return miss; - } - bool banner_missed(){ - const bool miss = m_misses.banner == m_misses.banners++; - m_misses.missed |= miss; - return miss; - } - bool on_map(const std::string& map) const{ - return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); - } - - GridSim& m_sim; - GridSimRouteIO m_route; - SimMisses& m_misses; - std::function m_far_side; -}; - -// A hold until something stops us. A door stops it at the fade, which -// fails the step; a fade missed lets the hold go on past the mouth (r81's -// timed walk south out of the Ravaged Path, onto Route 204's cliff). -void SimStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ - m_sim.tap(direction, ROUTE_TURN_TAP, false); - Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); - SimMove move = m_sim.hold(direction, limit, SimPace::WALK); - if (move.stop == SimStop::WARP && fade_missed() && m_far_side()){ - limit -= std::min(limit, move.time); - move = m_sim.hold(direction, limit, SimPace::WALK); - } - if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ - m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); - } -} - -// The D-pad, a tile at a time, until `map`'s banner reads; through a door -// the walk goes on beyond it (the fade eats no tiles of a hold). -bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&){ - const bool miss = banner_missed(); - size_t on = 0; - for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ - SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); - const bool crossed = move.stop == SimStop::WARP && m_far_side(); - const bool stopped = !crossed && (move.distance == 0 || move.stop != SimStop::DONE); - on = on_map(map) ? on + 1 : 0; - if (on > 0 && (on > SIM_BANNER_TILES || stopped) && !miss){ - return true; - } - if (stopped){ - return false; - } - } - return false; -} - -// D-pad taps, each looked at, until the fade and then the banner (the -// console's ConsoleStoryStepIO::tap_to_banner()). Each look stands still, -// so a banner on the far side reads at once. A fade seen ends the taps, -// banner or not; with the fade missed the next look still sees the banner. -std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ - bool crossed = false; - for (size_t tap = 1; tap <= max_taps; tap++){ - const SimMove move = m_sim.tap(direction, 160ms, false); - if (move.stop == SimStop::DIALOG){ - return std::nullopt; - } - bool faded = false; - if (move.stop == SimStop::WARP){ - faded = !fade_missed(); - crossed = m_far_side(); - } - if (crossed && on_map(map) && !banner_missed()){ - return tap; - } - if (faded){ - return std::nullopt; - } - } - return std::nullopt; -} - - -// A scene's trigger the simulation fires from row `row` on, once the step -// `after` has run ("" from the row's start), on `map`'s `tiles`. -struct RowTrigger{ - std::string row; - std::string after; - std::string map; - SimTrigger trigger; -}; - -// When a story variable holds the value its coord events wait for: from -// row `row` on, once the step `after` has run ("" from the row's start). -struct VarState{ - std::string var; - int value; - std::string row; - std::string after; -}; - -// The story variables whose coord events the table walks onto, from the -// row (and step) the table's reasons give, with the maps' coord events -// (Diamond's zone events; Platinum's for the houses): Barry's doorstep and -// Mom's warning in 00.01, Barry's Route 201 warning, then its pull-back -// row 19 once he has warned us (r14, r16); the lake's entrance in 00.02; -// Rowan's stop and Dawn at Sandgem's edge in 00.03; Dawn's catching -// tutorial on Route 202 from 00.04's start, Mom's call once she has healed -// us; the Poketch president on Jubilife's row 40 in 00.05b; Barry on Route -// 203 in 01.01; the Gate's Hiker and Oreburgh's welcome in 01.02; Barry's -// bump in Oreburgh after Roark in 01.05; and Rowan in Jubilife in 01.07. -// Left out: the Twinleaf guitarist (spent upstairs), Platinum's rival -// steps around our bedroom's start, Dawn at Jubilife's steps (BDSP starts -// her below them: an event), and Floaroma's (10..12, 29) (Diamond only). -std::vector story_vars(){ - return { - {.var = "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", .value = 0, .row = "00.01", .after = ""}, - {.var = "VAR_PLAYER_HOUSE_STATE", .value = 1, .row = "00.01", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 0, .row = "00.01", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 1, .row = "00.01", .after = "barry_warns_us"}, - {.var = "VAR_VERITY_LAKEFRONT_STATE", .value = 0, .row = "00.02", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 2, .row = "00.03", .after = ""}, - {.var = "VAR_SANDGEM_TOWN_STATE", .value = 0, .row = "00.03", .after = ""}, - {.var = "VAR_ROUTE_202_STATE", .value = 0, .row = "00.04", .after = ""}, - {.var = "CONSOLE_MOMS_CALL", .value = 0, .row = "00.04", .after = "mom_heals_us"}, - {.var = "VAR_POKETCH_CAMPAIGN_STATE", .value = 1, .row = "00.05b", .after = ""}, - {.var = "VAR_ROUTE_203_RIVAL_STATE", .value = 0, .row = "01.01", .after = ""}, - {.var = "VAR_OREBURGH_GATE_1F_HIKER_STATE", .value = 1, .row = "01.02", .after = ""}, - {.var = "VAR_OREBURGH_CITY_STATE", .value = 0, .row = "01.02", .after = ""}, - {.var = "VAR_OREBURGH_CITY_STATE", .value = 2, .row = "01.05", .after = ""}, - {.var = "VAR_JUBILIFE_CITY_STATE", .value = 3, .row = "01.07", .after = ""}, - }; -} - -// The maps' coord events (story_coord_events()) whose variable holds. -std::optional var_state(const CoordEvent& event){ - for (const VarState& state : story_vars()){ - if (state.var == event.var && state.value == event.value){ - return state; - } - } - return std::nullopt; -} - -RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ - return {.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; -} - -std::vector story_triggers(){ - std::vector triggers; - for (const auto& [map, json] : bdsp_map_json()){ - for (const CoordEvent& event : story_coord_events(map)){ - const std::optional state = var_state(event); - if (state){ - triggers.push_back(row_trigger(map, event, *state)); - } - } - } - return triggers; -} - - -// Someone the maps do not have, who stands on `tile` of `map` and is -// talked to there or walked round: from row `row` on if `until` is "", -// else in `row` until its step `until` has run. -struct SimPerson{ - std::string name; - std::string map; - TilePos tile; - std::string row; - std::string until; -}; -std::vector sim_people(){ - return { - // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). - {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04", .until = ""}, - // Barry stands in the Center's door until his lines (01.03; Roark - // ignored A until then, r101 and r104). - {.name = "barry", .map = "OreburghCity", .tile = {47, 20}, .row = "01.03", .until = "barrys_lines"}, - }; -} - -// A house's stairs, entered by a step `side` from the map's "stairs" -// point into what the map draws as a wall (the table's 00.01: r8 and r9 -// for ours, r11 for Barry's). -struct SimStairs{ - std::string map; - Direction side; -}; -std::vector sim_stairs(){ - return { - {.map = "PlayerHouse2F", .side = Direction::EAST}, - {.map = "RivalHouse1F", .side = Direction::EAST}, - {.map = "RivalHouse2F", .side = Direction::WEST}, - }; -} - - -// The program's walking steps on the simulation, the rest stubbed. -class SimExecutor : public Pokemon::StoryStepExecutor{ -public: - explicit SimExecutor(Logger& logger, SimMisses misses = {}) - : m_logger(logger) - , m_misses(misses) - , m_sim({}, {0, 0}, Direction::NORTH, false) - , m_io(m_sim, m_notes, m_misses, [this]{ return cross(); }) - , m_walks(m_io) - {} - - const SimMisses& misses() const{ - return m_misses; - } - const SimRun& result() const{ - return m_result; - } - virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ - m_row = data.id; - m_start_mismatch = data.start ? off_pose(*data.start) : ""; - m_ran.clear(); - m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); - m_walks.begin_attempt(data.id); - arm(""); - } - virtual Outcome run(RunState& state, const StoryStep& step) override; - -protected: - virtual Outcome route(RunState& state, const StoryStep& step) override{ return m_walks.route(state, step); } - virtual Outcome legs(RunState& state, const StoryStep& step) override{ return m_walks.legs(state, step); } - virtual Outcome step(RunState& state, const StoryStep& step) override{ return m_walks.step(state, step); } - virtual Outcome talk(RunState& state, const StoryStep& step) override{ return m_walks.talk(state, step); } - virtual Outcome mash(RunState& state, const StoryStep& step) override{ return m_walks.mash(state, step); } - virtual Outcome heal(RunState& state, const StoryStep& step) override; - virtual Outcome new_game(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome options(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome answer(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome battle(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome train(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome shop(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome save(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome game(RunState&, const StoryStep&) override{ return stub(); } - -private: - // A step the simulation does not play: its dialogue opened and closed. - Outcome stub(){ - m_sim.end_dialogue(); - return Pokemon::outcome_ok(); - } - const StoryWorld* sim_world(const std::string& map) const; - SimWorld setup(const StoryWorld* world) const; - void arm(const std::string& after); - bool sync(const Pose& pose, const StoryWorld* on = nullptr); - bool cross(); - std::string off_pose(const Pose& pose) const; - std::string check(const StoryStep& step, const Outcome& outcome); - Outcome run_step(RunState& state, const StoryStep& step); - - Logger& m_logger; - std::vector m_notes; - SimMisses m_misses; - GridSim m_sim; - SimStoryStepIO m_io; - StoryWalkSteps m_walks; - // The planner's worlds with sim_people() on them, by world and who. - mutable std::map, std::unique_ptr> m_peopled; - // The steps of this row that have run. - std::set m_ran; - std::string m_row; - std::vector m_armed; - // Where the step running now ends, if it says: a door's far side. - std::optional m_far; - // Why the player is not on this row's start, or "". - std::string m_start_mismatch; - // Whether the player has been put on a map yet. - bool m_placed = false; - // Whether the step running now is on a room with no map. - bool m_passed_over = false; - SimRun m_result; -}; - -// The world the player walks on for `map`: the planner's, with what the -// console showed that the maps lack. Nothing for a room with no map. -const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ - const StoryWorld* world = story_plan_world(map, map); - std::vector here; - std::string who; - for (const SimPerson& person : sim_people()){ - const bool now = person.until.empty() ? m_row >= person.row : m_row == person.row && !m_ran.contains(person.until); - if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ - here.push_back(person); - who += person.name + ";"; - } - } - if (here.empty()){ - return world; - } - std::unique_ptr& peopled = m_peopled[{world, who}]; - if (!peopled){ - peopled = std::make_unique(*world); - for (const SimPerson& person : here){ - peopled->block(story_to_world(*world, person.map, person.tile)); - } - } - return peopled.get(); -} - -SimWorld SimExecutor::setup(const StoryWorld* world) const{ - // B runs once the shoes' scene has given them: the scene ends at home. - SimWorld out{.world = world, .trainers = story_trainers(*world), .can_run = m_walks.can_run()}; - for (const SimStairs& stairs : sim_stairs()){ - if (sim_world(stairs.map) == world){ - out.doors.push_back(story_to_world(*world, stairs.map, map_point(stairs.map, "stairs").next(stairs.side))); - } - } - for (const RowTrigger& armed : m_armed){ - if (sim_world(armed.map) != world){ - continue; - } - SimTrigger trigger{.name = armed.trigger.name}; - for (const TilePos& pos : armed.trigger.tiles){ - trigger.tiles.push_back(story_to_world(*world, armed.map, pos)); - } - out.triggers.push_back(std::move(trigger)); - } - return out; -} - -// Arms the triggers of this row that start after `after`. -void SimExecutor::arm(const std::string& after){ - size_t armed = 0; - for (const RowTrigger& trigger : story_triggers()){ - if (trigger.row == m_row && trigger.after == after){ - m_armed.push_back(trigger); - armed++; - } - } - const SimPlayer& player = m_sim.player(); - if (armed > 0 && m_placed && on_grid(player.pos) && !player.dialog){ - m_sim.place(setup(&m_sim.world()), nearest_tile(player.pos), player.facing); - } -} - -// Puts the player on `pose`, on the world `on` if given, unless they stand -// on one of its tiles already. Returns whether the pose is on a map the -// simulation has. -bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ - const std::vector tiles = Pokemon::tiles_of(pose); - const StoryWorld* world = on != nullptr ? on : pose.map.empty() ? nullptr : sim_world(pose.map); - if (world == nullptr || tiles.empty()){ - return false; - } - const SimPlayer& player = m_sim.player(); - const std::optional local = !m_placed || &m_sim.world() != world - ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); - if (local && on_grid(player.pos) && std::find(tiles.begin(), tiles.end(), *local) != tiles.end()){ - return true; - } - m_sim.place(setup(world), story_to_world(*world, pose.map, tiles.front()), Pokemon::facing_of(pose)); - m_placed = true; - return true; -} - -// Through a door or a cave mouth onto the step's far side, the player's -// facing kept: a hold goes on from there. -bool SimExecutor::cross(){ - const StoryWorld* world = m_far ? sim_world(m_far->map) : nullptr; - const std::vector tiles = m_far ? Pokemon::tiles_of(*m_far) : std::vector{}; - if (world == nullptr || tiles.empty()){ - return false; - } - m_sim.place(setup(world), story_to_world(*world, m_far->map, tiles.front()), std::nullopt); - return true; -} - -// Why the player does not stand on one of `pose`'s tiles, or "" if they -// do or the simulation cannot tell (no map, or not placed yet). -std::string SimExecutor::off_pose(const Pose& pose) const{ - const std::vector tiles = Pokemon::tiles_of(pose); - if (!m_placed || tiles.empty() || sim_world(pose.map) == nullptr){ - return ""; - } - const SimPlayer& player = m_sim.player(); - const TilePos at = nearest_tile(player.pos); - // In world tiles: a pose a leg worked out from the map it started on - // may lie past that map's edge, on the next map (Twinleaf's exit). - // story_to_world() throws for a map not on the player's world. - try{ - const auto there = [&](const TilePos& tile){ return story_to_world(m_sim.world(), pose.map, tile) == at; }; - if (on_grid(player.pos) && std::ranges::any_of(tiles, there)){ - return ""; - } - }catch (const InternalProgramError&){} - return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), at), Pokemon::to_string(pose)); -} - -Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ - if (sync(state.pose) && m_sim.hold(Direction::NORTH, 3000ms, SimPace::RUN).stop != SimStop::WARP){ - return Pokemon::outcome_failed("no_door", step.name + ": no door north of " + to_string(m_sim.player().pos)); - } - return Pokemon::outcome_ok(); -} - -// Why a walking step did not end where the table says, or "". A step -// through a door the simulation did not cross is not checked: the sim's -// maps have no warps' destinations. -std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ - const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP; - const std::optional expected = step.pose_after ? step.pose_after : outcome.pose; - if (!walks || !m_placed){ - return ""; - } - if (!expected || Pokemon::tiles_of(*expected).empty()){ - m_result.unchecked.push_back(m_row + " " + step.name); - return ""; - } - const SimPlayer& player = m_sim.player(); - if (player.warped && !story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos))){ - return ""; - } - return off_pose(*expected); -} - -Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ - if (!m_start_mismatch.empty()){ - return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); - } - m_far = step.pose_after; - if (story_events().contains(step.variant)){ - return stub(); - } - // A scene goes on from where the step before left us. A route walks - // on the world it plans on (Jubilife alone has no Route 204 north of it). - const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || - step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK; - const StoryWorld* on = step.kind == StoryStepKind::ROUTE && step.target && !state.pose.map.empty() - ? story_plan_world(state.pose.map, step.target->map) : nullptr; - // A world of one map is sim_world()'s, with its people. - if (on != nullptr && on == story_plan_world(state.pose.map, state.pose.map)){ - on = nullptr; - } - if (walks && !sync(state.pose, on)){ - m_logger.log(std::format("[{}] {}: no map for {}; passed over.", m_row, step.name, Pokemon::to_string(state.pose))); - m_passed_over = true; - return Pokemon::outcome_ok(); - } - return Pokemon::StoryStepExecutor::run(state, step); -} - -Outcome SimExecutor::run(RunState& state, const StoryStep& step){ - Outcome outcome; - m_passed_over = false; - try{ - outcome = run_step(state, step); - }catch (const GridSimFailure& e){ - outcome = Pokemon::outcome_failed("sim_failure", e.message); - } - const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; - if (!mismatch.empty()){ - outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); - } - // What the simulation does not play (scenes, events, battles) ends - // where the table says it does. - if (outcome.succeeded() && step.pose_after){ - sync(*step.pose_after); - } - m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); - if (std::exchange(m_misses.missed, false) && m_result.missed_step.empty()){ - m_result.missed_step = m_row + " " + step.name; - } - if (!outcome.succeeded() && m_result.error.empty()){ - // The walker's last notes, to see why. - for (size_t i = m_notes.size() - std::min(m_notes.size(), 40); i < m_notes.size(); i++){ - m_logger.log(std::format("[{}] note: {}", m_row, m_notes[i])); - } - m_result.error = m_row + " " + Pokemon::to_string(outcome); - m_result.failed_step = m_row + " " + step.name; - } - m_result.world = m_placed ? &m_sim.world() : nullptr; - m_result.end = nearest_tile(m_sim.player().pos); - m_ran.insert(step.name); - arm(step.name); - return outcome; -} - - -// Runs `range` of `rows` (the table unless given) on `executor`, stopping -// at the first failure. -Pokemon::SegmentReport run_rows_on( - SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, - const std::vector& rows = story_checkpoints() -){ - std::set saved; - Pokemon::Segment segment = make_story_segment(rows, executor, saved); - Pokemon::SegmentPolicy policy; - policy.stop_at_first_failure = true; - Pokemon::SegmentHooks hooks; - hooks.reload = [](RunState&){ return Pokemon::outcome_ok(); }; - hooks.log = [&logger](const std::string& line){ logger.log(line); }; - RunState state; - return Pokemon::run_segment(state, segment, range, policy, hooks); -} - -// Runs `range` of the table on the simulation, stopping at the first failure. -UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ - SimExecutor executor(logger); - const Pokemon::SegmentReport report = run_rows_on(executor, logger, range); - for (const std::string& step : executor.result().unchecked){ - logger.log("No end to check after " + step + "."); - } - if (!report.completed){ - return std::format("stopped at {} {}: {}", report.failed_checkpoint, report.failed_event, executor.result().error); - } - return true; -} - -// The table with row `row`'s step of `step`'s name replaced by `step`. -std::vector table_with(const std::string& row, const StoryStep& step){ - std::vector rows = story_checkpoints(); - for (StoryCheckpoint& checkpoint : rows){ - for (StoryStep& old : checkpoint.steps){ - if (checkpoint.id == row && old.name == step.name){ - old = step; - return rows; - } - } - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + step.name + " in " + row); -} - -bool ends_on(const SimRun& run, const Pose& pose){ - const std::vector tiles = Pokemon::tiles_of(pose); - const std::optional local = run.world ? story_to_local(*run.world, pose.map, run.end) : std::nullopt; - return local && std::find(tiles.begin(), tiles.end(), *local) != tiles.end(); -} -std::string end_of(const SimRun& run){ - return run.world ? describe(*run.world, run.end) : "nowhere"; -} - - -// A way out of a map that a hold walked on past (r75, r81), against the -// table's tap to the banner. The old step, with `misses`, must end on -// `overshoot`, caught there by the end-tile check. The table's step must -// never end there, whichever one fade or banner of the row is missed: it -// ends on its tile or stops in that step. -class Test_StorySimExit : public UnitTest{ -public: - Test_StorySimExit(std::string name, std::string row, StoryStep old_step, SimMisses misses, Pose overshoot) - : UnitTest("PokemonBDSP::AutoStory - Story sim, exits: " + std::move(name)) - , m_row(std::move(row)) - , m_old(std::move(old_step)) - , m_misses(std::move(misses)) - , m_overshoot(std::move(overshoot)) - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - try{ - const std::string old = old_form(logger); - return old.empty() ? table_form(logger) : UnitTestResult(old); - }catch (Exception& e){ - return std::string(e.name()) + ": " + e.message(); - } - } - -private: - // Why the old step did not go wrong as on the console, or "". - std::string old_form(Logger& logger) const{ - SimExecutor executor(logger, m_misses); - const std::vector rows = table_with(m_row, m_old); - run_rows_on(executor, logger, {.from = m_row, .to = m_row}, rows); - const SimRun& run = executor.result(); - logger.log(std::format("The old {}: {}, ended on {}.", m_old.name, run.error, end_of(run))); - if (run.failed_step != m_row + " " + m_old.name || !ends_on(run, m_overshoot)){ - return std::format("the old {} should end on {} and fail there; it ended on {}: {}", - m_old.name, Pokemon::to_string(m_overshoot), end_of(run), run.error.empty() ? "no failure" : run.error); - } - return ""; - } - UnitTestResult table_form(Logger& logger) const{ - SimExecutor clean(logger); - if (!run_rows_on(clean, logger, {.from = m_row, .to = m_row}).completed){ - return "the table's row fails without misses: " + clean.result().error; - } - std::vector runs; - for (size_t i = 0; i < clean.misses().fades; i++){ - runs.push_back({.fade = i}); - } - for (size_t i = 0; i < clean.misses().banners; i++){ - runs.push_back({.banner = i}); - } - for (const SimMisses& misses : runs){ - SimExecutor executor(logger, misses); - run_rows_on(executor, logger, {.from = m_row, .to = m_row}); - if (ends_on(executor.result(), m_overshoot)){ - return std::format("the table's {} ended on {} with a miss in {}.", m_old.name, end_of(executor.result()), - executor.result().missed_step); - } - } - return true; - } - - std::string m_row; - StoryStep m_old; - SimMisses m_misses; - Pose m_overshoot; -}; - -// r75: out of the Oreburgh Gate as a run west until Route 203's banner -// (the old event west_until_transition()). The banner reads a few tiles -// in: the run ends west of the Gate's warp tile (55, 9), in the pocket by -// the pond (Route 203's x 49 to 54, rows 6 to 13). -StoryStep r75_old_gate_exit(){ - StoryStep step; - step.kind = StoryStepKind::LEGS; - step.name = "out_of_oreburgh_gate"; - step.legs = {{.direction = Direction::WEST, .tiles = 8}}; - step.variant = "to_map"; - step.pose_after = Pokemon::tile_pose("Route203", {TilePos{55, 9}}, Direction::WEST); - return step; -} -Pose r75_pond_pocket(){ - std::vector tiles; - for (int y = 6; y <= 13; y++){ - for (int x = 49; x <= 54; x++){ - tiles.push_back({x, y}); - } - } - return Pokemon::tile_pose("Route203", tiles); -} -// r81: out of the Ravaged Path as a timed walk south (the old event's -// 4 s walk_dir()), its fade missed: on past cave_exit (20, 26) to the -// cliff, column 20 down to row 30. -StoryStep r81_old_cave_exit(){ - StoryStep step; - step.kind = StoryStepKind::LEGS; - step.name = "out_of_the_ravaged_path"; - step.legs = {{.direction = Direction::SOUTH, .tiles = 4}}; - step.variant = "to_wall"; - step.pose_after = Pokemon::tile_pose("Route204North", {TilePos{20, 26}}, Direction::SOUTH); - return step; -} -Pose r81_below_the_mouth(){ - return Pokemon::tile_pose("Route204North", {TilePos{20, 27}, TilePos{20, 28}, TilePos{20, 29}, TilePos{20, 30}}); -} - - -// Every coord event has ground the player can step onto, and the ones -// the story's variables arm are there. -class Test_CoordEvents : public UnitTest{ -public: - Test_CoordEvents() - : UnitTest("PokemonBDSP::AutoStory - Story sim: the maps' coord events are on open ground or doors") - {} - virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - for (const auto& [map, json] : bdsp_map_json()){ - const StoryWorld* world = story_plan_world(map, map); - for (const CoordEvent& event : world == nullptr ? std::vector{} : story_coord_events(map)){ - const auto open = [&](const TilePos& pos){ - const TilePos tile = story_to_world(*world, map, pos); - return standable(*world, tile) || world->tile(tile) == Pokemon::TileKind::DOOR; - }; - // The decomp's boxes may run into walls (Sandgem's (4, 10..15)). - if (!std::ranges::any_of(event.tiles, open)){ - return std::format("{} {}: no tile is open ground or a door.", map, event.name); - } - } - } - const size_t armed = story_triggers().size(); - return armed == story_vars().size() ? UnitTestResult(true) - : UnitTestResult(std::format("Expected {} coord events armed by the story's variables, found {}.", story_vars().size(), armed)); - } -}; - - -// A detection the console can miss, missed in turn at each place the run -// makes it (#162). Each miss must either be got over (the run completes, -// every walk ending on its tiles) or stop the run in the step that missed: -// a miss that lets the run go on and fail later went unseen, and a later -// step started from somewhere it did not expect. Each miss runs its own -// row and the next, which checks where the row left us. -class Test_StorySimMisses : public UnitTest{ -public: - Test_StorySimMisses(std::string name, std::string from, std::string to) - : UnitTest("PokemonBDSP::AutoStory - Story sim, detector misses: " + std::move(name)) - , m_range{.from = std::move(from), .to = std::move(to)} - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - try{ - SimExecutor clean(logger); - if (!run_rows_on(clean, logger, m_range).completed){ - return "the run fails without misses: " + clean.result().error; - } - logger.log(std::format("{} fades and {} banners to miss.", clean.misses().fades, clean.misses().banners)); - std::vector unseen; - for (size_t i = 0; i < clean.misses().fades + clean.misses().banners; i++){ - const std::string line = miss(logger, clean.result(), i < clean.misses().fades, i < clean.misses().fades ? i : i - clean.misses().fades); - if (!line.empty()){ - unseen.push_back(line); - } - } - std::string out = "Misses that went unseen:"; - for (const std::string& line : unseen){ - out += "\n " + line; - } - return unseen.empty() ? UnitTestResult(true) : UnitTestResult(out); - }catch (Exception& e){ - return std::string(e.name()) + ": " + e.message(); - } - } - -private: - // Misses the `index`th fade (or banner) of the clean run `clean` in its - // row. Returns how it went unseen, or "". - static std::string miss(Logger& logger, const SimRun& clean, bool fade, size_t index){ - size_t k = 0; - while (k + 1 < clean.rows.size() && (fade ? clean.rows[k + 1].fades : clean.rows[k + 1].banners) <= index){ - k++; - } - const SimRun::RowStart& start = clean.rows[k]; - SimMisses misses; - (fade ? misses.fade : misses.banner) = index - (fade ? start.fades : start.banners); - SimExecutor executor(logger, misses); - const Pokemon::SegmentReport report = run_rows_on(executor, logger, - {.from = start.row, .to = clean.rows[std::min(k + 1, clean.rows.size() - 1)].row}); - const SimRun& run = executor.result(); - const std::string what = std::format("{} {}", fade ? "fade" : "banner", index); - logger.log(std::format("Missed {} in {}: {}.", what, run.missed_step, - report.completed ? "got over it" : "stopped in " + run.failed_step + ": " + run.error)); - if (report.completed || run.failed_step == run.missed_step){ - return ""; - } - return std::format("{} missed in {}, failed later in {}: {}", what, run.missed_step, run.failed_step, run.error); - } - - Pokemon::SegmentRange m_range; -}; - - -class Test_StorySim : public UnitTest{ -public: - Test_StorySim(std::string name, std::string from, std::string to) - : UnitTest("PokemonBDSP::AutoStory - Story sim: " + std::move(name)) - , m_from(std::move(from)) - , m_to(std::move(to)) - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - try{ - return run_rows(logger, {.from = m_from, .to = m_to}); - }catch (Exception& e){ - return std::string(e.name()) + ": " + e.message(); - } - } - -private: - std::string m_from; - std::string m_to; -}; - -} - - -void add_tests_AutoStory_StorySim(UnitTestDatabase& database){ - database.add(); - database.add("00.00 to 01.11", "00.00", "01.11"); - database.add("00.00 to 01.11: the whole table, from the new game to Floaroma", "00.00", "01.11"); - for (const StoryCheckpoint& row : story_checkpoints()){ - database.add(std::format("row {}", row.id), row.id, row.id); - } - database.add("r75, out of the Oreburgh Gate", "01.05", r75_old_gate_exit(), SimMisses{}, r75_pond_pocket()); - database.add("r81, out of the Ravaged Path", "01.09", r81_old_cave_exit(), SimMisses{.fade = 0}, r81_below_the_mouth()); -} - - - -} -} -} +/* BDSP AutoStory Story Sim Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Rows of the story table run as the program runs them (the segment + * runner, make_story_segment()), with the program's own walking steps + * (StoryWalkSteps: ROUTE, LEGS, STEP, TALK, MASH) on the grid simulation. + * After each walking step the simulated player must stand, on the grid, + * on a tile the table gives; a step through a door must have warped. + * + * Events, battles, shops and saves are stubs: a dialogue they open is + * closed, and the table's pose_after puts the player where they end. A + * heal checks that a walk north from where we stand enters a door. A scene + * starts when the player steps onto one of the maps' coord events while + * its story variable holds (story_vars()). Rooms with no + * map (the Trainers' School) are passed over. Each row must start where + * the row before left the player. + * + * A tap or hold through a door or cave mouth stops on its tile, as the + * console stops at the fade; a hold that does not see the fade goes on + * onto the step's pose_after and on along it, and a location banner reads + * only a few tiles into its map (SIM_BANNER_TILES). The exit tests run + * r75's and r81's old open-ended walks that way. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Data/PokemonBDSP_AutoStory_CoordEvents.h" +#include "Data/PokemonBDSP_AutoStory_Maps.h" +#include "Utils/PokemonBDSP_AutoStory_GridSim.h" +#include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_StorySim_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::Outcome; +using Pokemon::Pose; +using Pokemon::RunState; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + + +// Which detections the simulation misses on purpose (#162): the `fade`th +// door fade (run_into_door(), from 0) or the `banner`th map banner +// (run_until_map()) of the run goes unseen, though the player did go +// through. The console missed both (r75, r81). +// The counts and flags below are the run's: how many fades and banners it +// looked for, whether a miss happened since the executor last looked, and +// whether a missed fade is still unseen. +struct SimMisses{ + std::optional fade; + std::optional banner; + size_t fades = 0; + size_t banners = 0; + bool missed = false; + bool fade_unseen = false; +}; + +// How many tiles a held walk goes on into a map before its location +// banner reads: "it shows a tile or a few past the border" (the table's +// route_201_by_the_path(), measured on the console). Standing still, it +// reads at once. Through a cave mouth the fade comes first, and a hold +// whose fade went unseen goes on the same way (r75, r81). +constexpr size_t SIM_BANNER_TILES = 3; + +// What a run on the simulation did. +struct SimRun{ + // The first failure, as "row outcome", or "". + std::string error; + // The rows and steps where an injected miss happened and where the run + // first failed, as "row step": "" if none. + std::string missed_step; + std::string failed_step; + // Walking steps that end where nothing says, as "row step". + std::vector unchecked; + // Each row run, with the fades and banners looked for before it. + struct RowStart{ + std::string row; + size_t fades; + size_t banners; + }; + std::vector rows; + // Where the player stood after the last step, if placed. + const StoryWorld* world = nullptr; + TilePos end; +}; + +// StoryStepIO on the simulation. A walk through a door or a cave mouth +// stops on its tile, as the console stops at the fade; a hold that misses +// the fade carries on, onto `far_side()` (the step's pose_after: the +// sim's maps have no warps' destinations) and on along it. +class SimStoryStepIO : public StoryStepIO{ +public: + SimStoryStepIO(GridSim& sim, std::vector& notes, SimMisses& misses, std::function far_side) + : m_sim(sim) + , m_route(sim, notes) + , m_misses(misses) + , m_far_side(std::move(far_side)) + {} + + virtual RouteIO& route() override{ + return m_route; + } + virtual void fight(const std::string&) override{ + m_sim.end_dialogue(); + } + virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string& label) override; + virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; + virtual bool run_into_door(Direction direction, bool run) override{ + const bool warped = m_sim.hold(direction, 12000ms, run ? SimPace::RUN : SimPace::WALK).stop == SimStop::WARP; + if (warped && fade_missed()){ + m_misses.fade_unseen = true; + return false; + } + return warped; + } + // A scene may take us to another map (Mom walks us out, 00.04): with a + // dialogue open the stub scene plays it. Otherwise only a door fades. + // A fade missed on the way in stays missed: it was over before settle() + // looked, which then fails as it does on the console after 120 s. + virtual void settle(Button, const std::string& label, bool fade) override{ + if (fade && ((!m_sim.player().warped && !m_sim.player().dialog) || m_misses.fade_unseen)){ + m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); + } + m_misses.fade_unseen = false; + m_sim.end_dialogue(); + } + virtual std::optional tap_to_banner(Direction direction, const std::string& map, size_t max_taps) override; + +private: + // Whether the run misses this fade or this banner (SimMisses). + bool fade_missed(){ + const bool miss = m_misses.fade == m_misses.fades++; + m_misses.missed |= miss; + return miss; + } + bool banner_missed(){ + const bool miss = m_misses.banner == m_misses.banners++; + m_misses.missed |= miss; + return miss; + } + bool on_map(const std::string& map) const{ + return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); + } + + GridSim& m_sim; + GridSimRouteIO m_route; + SimMisses& m_misses; + std::function m_far_side; +}; + +// A hold until something stops us. A door stops it at the fade, which +// fails the step; a fade missed lets the hold go on past the mouth (r81's +// timed walk south out of the Ravaged Path, onto Route 204's cliff). +void SimStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ + m_sim.tap(direction, ROUTE_TURN_TAP, false); + Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); + SimMove move = m_sim.hold(direction, limit, SimPace::WALK); + if (move.stop == SimStop::WARP && fade_missed() && m_far_side()){ + limit -= std::min(limit, move.time); + move = m_sim.hold(direction, limit, SimPace::WALK); + } + if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ + m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); + } +} + +// The D-pad, a tile at a time, until `map`'s banner reads; through a door +// the walk goes on beyond it (the fade eats no tiles of a hold). +bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&){ + const bool miss = banner_missed(); + size_t on = 0; + for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ + SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + const bool crossed = move.stop == SimStop::WARP && m_far_side(); + const bool stopped = !crossed && (move.distance == 0 || move.stop != SimStop::DONE); + on = on_map(map) ? on + 1 : 0; + if (on > 0 && (on > SIM_BANNER_TILES || stopped) && !miss){ + return true; + } + if (stopped){ + return false; + } + } + return false; +} + +// D-pad taps, each looked at, until the fade and then the banner (the +// console's ConsoleStoryStepIO::tap_to_banner()). Each look stands still, +// so a banner on the far side reads at once. A fade seen ends the taps, +// banner or not; with the fade missed the next look still sees the banner. +std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ + bool crossed = false; + for (size_t tap = 1; tap <= max_taps; tap++){ + const SimMove move = m_sim.tap(direction, 160ms, false); + if (move.stop == SimStop::DIALOG){ + return std::nullopt; + } + bool faded = false; + if (move.stop == SimStop::WARP){ + faded = !fade_missed(); + crossed = m_far_side(); + } + if (crossed && on_map(map) && !banner_missed()){ + return tap; + } + if (faded){ + return std::nullopt; + } + } + return std::nullopt; +} + + +// A scene's trigger the simulation fires from row `row` on, once the step +// `after` has run ("" from the row's start), on `map`'s `tiles`. +struct RowTrigger{ + std::string row; + std::string after; + std::string map; + SimTrigger trigger; +}; + +// When a story variable holds the value its coord events wait for: from +// row `row` on, once the step `after` has run ("" from the row's start). +struct VarState{ + std::string var; + int value; + std::string row; + std::string after; +}; + +// The story variables whose coord events the table walks onto, from the +// row (and step) the table's reasons give, with the maps' coord events +// (Diamond's zone events; Platinum's for the houses): Barry's doorstep and +// Mom's warning in 00.01, Barry's Route 201 warning, then its pull-back +// row 19 once he has warned us (r14, r16); the lake's entrance in 00.02; +// Rowan's stop and Dawn at Sandgem's edge in 00.03; Dawn's catching +// tutorial on Route 202 from 00.04's start, Mom's call once she has healed +// us; the Poketch president on Jubilife's row 40 in 00.05b; Barry on Route +// 203 in 01.01; the Gate's Hiker and Oreburgh's welcome in 01.02; Barry's +// bump in Oreburgh after Roark in 01.05; and Rowan in Jubilife in 01.07. +// Left out: the Twinleaf guitarist (spent upstairs), Platinum's rival +// steps around our bedroom's start, Dawn at Jubilife's steps (BDSP starts +// her below them: an event), and Floaroma's (10..12, 29) (Diamond only). +std::vector story_vars(){ + return { + {.var = "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", .value = 0, .row = "00.01", .after = ""}, + {.var = "VAR_PLAYER_HOUSE_STATE", .value = 1, .row = "00.01", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 0, .row = "00.01", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 1, .row = "00.01", .after = "barry_warns_us"}, + {.var = "VAR_VERITY_LAKEFRONT_STATE", .value = 0, .row = "00.02", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 2, .row = "00.03", .after = ""}, + {.var = "VAR_SANDGEM_TOWN_STATE", .value = 0, .row = "00.03", .after = ""}, + {.var = "VAR_ROUTE_202_STATE", .value = 0, .row = "00.04", .after = ""}, + {.var = "CONSOLE_MOMS_CALL", .value = 0, .row = "00.04", .after = "mom_heals_us"}, + {.var = "VAR_POKETCH_CAMPAIGN_STATE", .value = 1, .row = "00.05b", .after = ""}, + {.var = "VAR_ROUTE_203_RIVAL_STATE", .value = 0, .row = "01.01", .after = ""}, + {.var = "VAR_OREBURGH_GATE_1F_HIKER_STATE", .value = 1, .row = "01.02", .after = ""}, + {.var = "VAR_OREBURGH_CITY_STATE", .value = 0, .row = "01.02", .after = ""}, + {.var = "VAR_OREBURGH_CITY_STATE", .value = 2, .row = "01.05", .after = ""}, + {.var = "VAR_JUBILIFE_CITY_STATE", .value = 3, .row = "01.07", .after = ""}, + }; +} + +// The maps' coord events (story_coord_events()) whose variable holds. +std::optional var_state(const CoordEvent& event){ + for (const VarState& state : story_vars()){ + if (state.var == event.var && state.value == event.value){ + return state; + } + } + return std::nullopt; +} + +RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ + return {.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; +} + +std::vector story_triggers(){ + std::vector triggers; + for (const auto& [map, json] : bdsp_map_json()){ + for (const CoordEvent& event : story_coord_events(map)){ + const std::optional state = var_state(event); + if (state){ + triggers.push_back(row_trigger(map, event, *state)); + } + } + } + return triggers; +} + + +// Someone the maps do not have, who stands on `tile` of `map` and is +// talked to there or walked round: from row `row` on if `until` is "", +// else in `row` until its step `until` has run. +struct SimPerson{ + std::string name; + std::string map; + TilePos tile; + std::string row; + std::string until; +}; +std::vector sim_people(){ + return { + // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). + {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04", .until = ""}, + // Barry stands in the Center's door until his lines (01.03; Roark + // ignored A until then, r101 and r104). + {.name = "barry", .map = "OreburghCity", .tile = {47, 20}, .row = "01.03", .until = "barrys_lines"}, + }; +} + +// A house's stairs, entered by a step `side` from the map's "stairs" +// point into what the map draws as a wall (the table's 00.01: r8 and r9 +// for ours, r11 for Barry's). +struct SimStairs{ + std::string map; + Direction side; +}; +std::vector sim_stairs(){ + return { + {.map = "PlayerHouse2F", .side = Direction::EAST}, + {.map = "RivalHouse1F", .side = Direction::EAST}, + {.map = "RivalHouse2F", .side = Direction::WEST}, + }; +} + + +// The program's walking steps on the simulation, the rest stubbed. +class SimExecutor : public Pokemon::StoryStepExecutor{ +public: + explicit SimExecutor(Logger& logger, SimMisses misses = {}) + : m_logger(logger) + , m_misses(misses) + , m_sim({}, {0, 0}, Direction::NORTH, false) + , m_io(m_sim, m_notes, m_misses, [this]{ return cross(); }) + , m_walks(m_io) + {} + + const SimMisses& misses() const{ + return m_misses; + } + const SimRun& result() const{ + return m_result; + } + virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ + m_row = data.id; + m_start_mismatch = data.start ? off_pose(*data.start) : ""; + m_ran.clear(); + m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); + m_walks.begin_attempt(data.id); + arm(""); + } + virtual Outcome run(RunState& state, const StoryStep& step) override; + +protected: + virtual Outcome route(RunState& state, const StoryStep& step) override{ return m_walks.route(state, step); } + virtual Outcome legs(RunState& state, const StoryStep& step) override{ return m_walks.legs(state, step); } + virtual Outcome step(RunState& state, const StoryStep& step) override{ return m_walks.step(state, step); } + virtual Outcome talk(RunState& state, const StoryStep& step) override{ return m_walks.talk(state, step); } + virtual Outcome mash(RunState& state, const StoryStep& step) override{ return m_walks.mash(state, step); } + virtual Outcome heal(RunState& state, const StoryStep& step) override; + virtual Outcome new_game(RunState&, const StoryStep&) override{ return stub(); } + virtual Outcome options(RunState&, const StoryStep&) override{ return stub(); } + virtual Outcome answer(RunState&, const StoryStep&) override{ return stub(); } + virtual Outcome battle(RunState&, const StoryStep&) override{ return stub(); } + virtual Outcome train(RunState&, const StoryStep&) override{ return stub(); } + virtual Outcome shop(RunState&, const StoryStep&) override{ return stub(); } + virtual Outcome save(RunState&, const StoryStep&) override{ return stub(); } + virtual Outcome game(RunState&, const StoryStep&) override{ return stub(); } + +private: + // A step the simulation does not play: its dialogue opened and closed. + Outcome stub(){ + m_sim.end_dialogue(); + return Pokemon::outcome_ok(); + } + const StoryWorld* sim_world(const std::string& map) const; + SimWorld setup(const StoryWorld* world) const; + void arm(const std::string& after); + bool sync(const Pose& pose, const StoryWorld* on = nullptr); + bool cross(); + std::string off_pose(const Pose& pose) const; + std::string check(const StoryStep& step, const Outcome& outcome); + Outcome run_step(RunState& state, const StoryStep& step); + + Logger& m_logger; + std::vector m_notes; + SimMisses m_misses; + GridSim m_sim; + SimStoryStepIO m_io; + StoryWalkSteps m_walks; + // The planner's worlds with sim_people() on them, by world and who. + mutable std::map, std::unique_ptr> m_peopled; + // The steps of this row that have run. + std::set m_ran; + std::string m_row; + std::vector m_armed; + // Where the step running now ends, if it says: a door's far side. + std::optional m_far; + // Why the player is not on this row's start, or "". + std::string m_start_mismatch; + // Whether the player has been put on a map yet. + bool m_placed = false; + // Whether the step running now is on a room with no map. + bool m_passed_over = false; + SimRun m_result; +}; + +// The world the player walks on for `map`: the planner's, with what the +// console showed that the maps lack. Nothing for a room with no map. +const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ + const StoryWorld* world = story_plan_world(map, map); + std::vector here; + std::string who; + for (const SimPerson& person : sim_people()){ + const bool now = person.until.empty() ? m_row >= person.row : m_row == person.row && !m_ran.contains(person.until); + if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ + here.push_back(person); + who += person.name + ";"; + } + } + if (here.empty()){ + return world; + } + std::unique_ptr& peopled = m_peopled[{world, who}]; + if (!peopled){ + peopled = std::make_unique(*world); + for (const SimPerson& person : here){ + peopled->block(story_to_world(*world, person.map, person.tile)); + } + } + return peopled.get(); +} + +SimWorld SimExecutor::setup(const StoryWorld* world) const{ + // B runs once the shoes' scene has given them: the scene ends at home. + SimWorld out{.world = world, .trainers = story_trainers(*world), .can_run = m_walks.can_run()}; + for (const SimStairs& stairs : sim_stairs()){ + if (sim_world(stairs.map) == world){ + out.doors.push_back(story_to_world(*world, stairs.map, map_point(stairs.map, "stairs").next(stairs.side))); + } + } + for (const RowTrigger& armed : m_armed){ + if (sim_world(armed.map) != world){ + continue; + } + SimTrigger trigger{.name = armed.trigger.name}; + for (const TilePos& pos : armed.trigger.tiles){ + trigger.tiles.push_back(story_to_world(*world, armed.map, pos)); + } + out.triggers.push_back(std::move(trigger)); + } + return out; +} + +// Arms the triggers of this row that start after `after`. +void SimExecutor::arm(const std::string& after){ + size_t armed = 0; + for (const RowTrigger& trigger : story_triggers()){ + if (trigger.row == m_row && trigger.after == after){ + m_armed.push_back(trigger); + armed++; + } + } + const SimPlayer& player = m_sim.player(); + if (armed > 0 && m_placed && on_grid(player.pos) && !player.dialog){ + m_sim.place(setup(&m_sim.world()), nearest_tile(player.pos), player.facing); + } +} + +// Puts the player on `pose`, on the world `on` if given, unless they stand +// on one of its tiles already. Returns whether the pose is on a map the +// simulation has. +bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ + const std::vector tiles = Pokemon::tiles_of(pose); + const StoryWorld* world = on != nullptr ? on : pose.map.empty() ? nullptr : sim_world(pose.map); + if (world == nullptr || tiles.empty()){ + return false; + } + const SimPlayer& player = m_sim.player(); + const std::optional local = !m_placed || &m_sim.world() != world + ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); + if (local && on_grid(player.pos) && std::find(tiles.begin(), tiles.end(), *local) != tiles.end()){ + return true; + } + m_sim.place(setup(world), story_to_world(*world, pose.map, tiles.front()), Pokemon::facing_of(pose)); + m_placed = true; + return true; +} + +// Through a door or a cave mouth onto the step's far side, the player's +// facing kept: a hold goes on from there. +bool SimExecutor::cross(){ + const StoryWorld* world = m_far ? sim_world(m_far->map) : nullptr; + const std::vector tiles = m_far ? Pokemon::tiles_of(*m_far) : std::vector{}; + if (world == nullptr || tiles.empty()){ + return false; + } + m_sim.place(setup(world), story_to_world(*world, m_far->map, tiles.front()), std::nullopt); + return true; +} + +// Why the player does not stand on one of `pose`'s tiles, or "" if they +// do or the simulation cannot tell (no map, or not placed yet). +std::string SimExecutor::off_pose(const Pose& pose) const{ + const std::vector tiles = Pokemon::tiles_of(pose); + if (!m_placed || tiles.empty() || sim_world(pose.map) == nullptr){ + return ""; + } + const SimPlayer& player = m_sim.player(); + const TilePos at = nearest_tile(player.pos); + // In world tiles: a pose a leg worked out from the map it started on + // may lie past that map's edge, on the next map (Twinleaf's exit). + // story_to_world() throws for a map not on the player's world. + try{ + const auto there = [&](const TilePos& tile){ return story_to_world(m_sim.world(), pose.map, tile) == at; }; + if (on_grid(player.pos) && std::ranges::any_of(tiles, there)){ + return ""; + } + }catch (const InternalProgramError&){} + return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), at), Pokemon::to_string(pose)); +} + +Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ + if (sync(state.pose) && m_sim.hold(Direction::NORTH, 3000ms, SimPace::RUN).stop != SimStop::WARP){ + return Pokemon::outcome_failed("no_door", step.name + ": no door north of " + to_string(m_sim.player().pos)); + } + return Pokemon::outcome_ok(); +} + +// Why a walking step did not end where the table says, or "". A step +// through a door the simulation did not cross is not checked: the sim's +// maps have no warps' destinations. +std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ + const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP; + const std::optional expected = step.pose_after ? step.pose_after : outcome.pose; + if (!walks || !m_placed){ + return ""; + } + if (!expected || Pokemon::tiles_of(*expected).empty()){ + m_result.unchecked.push_back(m_row + " " + step.name); + return ""; + } + const SimPlayer& player = m_sim.player(); + if (player.warped && !story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos))){ + return ""; + } + return off_pose(*expected); +} + +Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ + if (!m_start_mismatch.empty()){ + return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); + } + m_far = step.pose_after; + if (story_events().contains(step.variant)){ + return stub(); + } + // A scene goes on from where the step before left us. A route walks + // on the world it plans on (Jubilife alone has no Route 204 north of it). + const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || + step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK; + const StoryWorld* on = step.kind == StoryStepKind::ROUTE && step.target && !state.pose.map.empty() + ? story_plan_world(state.pose.map, step.target->map) : nullptr; + // A world of one map is sim_world()'s, with its people. + if (on != nullptr && on == story_plan_world(state.pose.map, state.pose.map)){ + on = nullptr; + } + if (walks && !sync(state.pose, on)){ + m_logger.log(std::format("[{}] {}: no map for {}; passed over.", m_row, step.name, Pokemon::to_string(state.pose))); + m_passed_over = true; + return Pokemon::outcome_ok(); + } + return Pokemon::StoryStepExecutor::run(state, step); +} + +Outcome SimExecutor::run(RunState& state, const StoryStep& step){ + Outcome outcome; + m_passed_over = false; + try{ + outcome = run_step(state, step); + }catch (const GridSimFailure& e){ + outcome = Pokemon::outcome_failed("sim_failure", e.message); + } + const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; + if (!mismatch.empty()){ + outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); + } + // What the simulation does not play (scenes, events, battles) ends + // where the table says it does. + if (outcome.succeeded() && step.pose_after){ + sync(*step.pose_after); + } + m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); + if (std::exchange(m_misses.missed, false) && m_result.missed_step.empty()){ + m_result.missed_step = m_row + " " + step.name; + } + if (!outcome.succeeded() && m_result.error.empty()){ + // The walker's last notes, to see why. + for (size_t i = m_notes.size() - std::min(m_notes.size(), 40); i < m_notes.size(); i++){ + m_logger.log(std::format("[{}] note: {}", m_row, m_notes[i])); + } + m_result.error = m_row + " " + Pokemon::to_string(outcome); + m_result.failed_step = m_row + " " + step.name; + } + m_result.world = m_placed ? &m_sim.world() : nullptr; + m_result.end = nearest_tile(m_sim.player().pos); + m_ran.insert(step.name); + arm(step.name); + return outcome; +} + + +// Runs `range` of `rows` (the table unless given) on `executor`, stopping +// at the first failure. +Pokemon::SegmentReport run_rows_on( + SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, + const std::vector& rows = story_checkpoints() +){ + std::set saved; + Pokemon::Segment segment = make_story_segment(rows, executor, saved); + Pokemon::SegmentPolicy policy; + policy.stop_at_first_failure = true; + Pokemon::SegmentHooks hooks; + hooks.reload = [](RunState&){ return Pokemon::outcome_ok(); }; + hooks.log = [&logger](const std::string& line){ logger.log(line); }; + RunState state; + return Pokemon::run_segment(state, segment, range, policy, hooks); +} + +// Runs `range` of the table on the simulation, stopping at the first failure. +UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ + SimExecutor executor(logger); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, range); + for (const std::string& step : executor.result().unchecked){ + logger.log("No end to check after " + step + "."); + } + if (!report.completed){ + return std::format("stopped at {} {}: {}", report.failed_checkpoint, report.failed_event, executor.result().error); + } + return true; +} + +// The table with row `row`'s step of `step`'s name replaced by `step`. +std::vector table_with(const std::string& row, const StoryStep& step){ + std::vector rows = story_checkpoints(); + for (StoryCheckpoint& checkpoint : rows){ + for (StoryStep& old : checkpoint.steps){ + if (checkpoint.id == row && old.name == step.name){ + old = step; + return rows; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + step.name + " in " + row); +} + +bool ends_on(const SimRun& run, const Pose& pose){ + const std::vector tiles = Pokemon::tiles_of(pose); + const std::optional local = run.world ? story_to_local(*run.world, pose.map, run.end) : std::nullopt; + return local && std::find(tiles.begin(), tiles.end(), *local) != tiles.end(); +} +std::string end_of(const SimRun& run){ + return run.world ? describe(*run.world, run.end) : "nowhere"; +} + + +UnitTestResult run_exit_test(Logger& logger, const std::string& row_id, const StoryStep& old_step, const SimMisses& misses, const Pose& overshoot){ + SimExecutor executor(logger, misses); + const std::vector rows = table_with(row_id, old_step); + run_rows_on(executor, logger, {.from = row_id, .to = row_id}, rows); + const SimRun& run = executor.result(); + logger.log(std::format("The old {}: {}, ended on {}.", old_step.name, run.error, end_of(run))); + if (run.failed_step != row_id + " " + old_step.name || !ends_on(run, overshoot)){ + return std::format("the old {} should end on {} and fail there; it ended on {}: {}", + old_step.name, Pokemon::to_string(overshoot), end_of(run), run.error.empty() ? "no failure" : run.error); + } + SimExecutor clean(logger); + if (!run_rows_on(clean, logger, {.from = row_id, .to = row_id}).completed){ + return "the table's row fails without misses: " + clean.result().error; + } + std::vector runs; + for (size_t i = 0; i < clean.misses().fades; i++){ + runs.push_back({.fade = i}); + } + for (size_t i = 0; i < clean.misses().banners; i++){ + runs.push_back({.banner = i}); + } + for (const SimMisses& m : runs){ + SimExecutor sim(logger, m); + run_rows_on(sim, logger, {.from = row_id, .to = row_id}); + if (ends_on(sim.result(), overshoot)){ + return std::format("the table's {} ended on {} with a miss in {}.", old_step.name, end_of(sim.result()), + sim.result().missed_step); + } + } + return true; +} + +// r75: out of the Oreburgh Gate as a run west until Route 203's banner +// (the old event west_until_transition()). The banner reads a few tiles +// in: the run ends west of the Gate's warp tile (55, 9), in the pocket by +// the pond (Route 203's x 49 to 54, rows 6 to 13). +StoryStep r75_old_gate_exit(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "out_of_oreburgh_gate"; + step.legs = {{.direction = Direction::WEST, .tiles = 8}}; + step.variant = "to_map"; + step.pose_after = Pokemon::tile_pose("Route203", {TilePos{55, 9}}, Direction::WEST); + return step; +} +Pose r75_pond_pocket(){ + std::vector tiles; + for (int y = 6; y <= 13; y++){ + for (int x = 49; x <= 54; x++){ + tiles.push_back({x, y}); + } + } + return Pokemon::tile_pose("Route203", tiles); +} +// r81: out of the Ravaged Path as a timed walk south (the old event's +// 4 s walk_dir()), its fade missed: on past cave_exit (20, 26) to the +// cliff, column 20 down to row 30. +StoryStep r81_old_cave_exit(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "out_of_the_ravaged_path"; + step.legs = {{.direction = Direction::SOUTH, .tiles = 4}}; + step.variant = "to_wall"; + step.pose_after = Pokemon::tile_pose("Route204North", {TilePos{20, 26}}, Direction::SOUTH); + return step; +} +Pose r81_below_the_mouth(){ + return Pokemon::tile_pose("Route204North", {TilePos{20, 27}, TilePos{20, 28}, TilePos{20, 29}, TilePos{20, 30}}); +} + + +UnitTestResult test_coord_events(Logger&){ + for (const auto& [map, json] : bdsp_map_json()){ + const StoryWorld* world = story_plan_world(map, map); + for (const CoordEvent& event : world == nullptr ? std::vector{} : story_coord_events(map)){ + const auto open = [&](const TilePos& pos){ + const TilePos tile = story_to_world(*world, map, pos); + return standable(*world, tile) || world->tile(tile) == Pokemon::TileKind::DOOR; + }; + if (!std::ranges::any_of(event.tiles, open)){ + return std::format("{} {}: no tile is open ground or a door.", map, event.name); + } + } + } + const size_t armed = story_triggers().size(); + return armed == story_vars().size() ? UnitTestResult(true) + : UnitTestResult(std::format("Expected {} coord events armed by the story's variables, found {}.", story_vars().size(), armed)); +} + +std::string miss(Logger& logger, const SimRun& clean, bool fade, size_t index){ + size_t k = 0; + while (k + 1 < clean.rows.size() && (fade ? clean.rows[k + 1].fades : clean.rows[k + 1].banners) <= index){ + k++; + } + const SimRun::RowStart& start = clean.rows[k]; + SimMisses misses; + (fade ? misses.fade : misses.banner) = index - (fade ? start.fades : start.banners); + SimExecutor executor(logger, misses); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, + {.from = start.row, .to = clean.rows[std::min(k + 1, clean.rows.size() - 1)].row}); + const SimRun& run = executor.result(); + const std::string what = std::format("{} {}", fade ? "fade" : "banner", index); + logger.log(std::format("Missed {} in {}: {}.", what, run.missed_step, + report.completed ? "got over it" : "stopped in " + run.failed_step + ": " + run.error)); + if (report.completed || run.failed_step == run.missed_step){ + return ""; + } + return std::format("{} missed in {}, failed later in {}: {}", what, run.missed_step, run.failed_step, run.error); +} + +UnitTestResult test_story_sim_misses(Logger& logger){ + Pokemon::SegmentRange range{.from = "00.00", .to = "01.11"}; + SimExecutor clean(logger); + if (!run_rows_on(clean, logger, range).completed){ + return "the run fails without misses: " + clean.result().error; + } + logger.log(std::format("{} fades and {} banners to miss.", clean.misses().fades, clean.misses().banners)); + std::vector unseen; + for (size_t i = 0; i < clean.misses().fades + clean.misses().banners; i++){ + const std::string line = miss(logger, clean.result(), i < clean.misses().fades, i < clean.misses().fades ? i : i - clean.misses().fades); + if (!line.empty()){ + unseen.push_back(line); + } + } + std::string out = "Misses that went unseen:"; + for (const std::string& line : unseen){ + out += "\n " + line; + } + return unseen.empty() ? UnitTestResult(true) : UnitTestResult(out); +} + +UnitTestResult test_story_sim_whole_table(Logger& logger){ + return run_rows(logger, {.from = "00.00", .to = "01.11"}); +} + +UnitTestResult test_story_sim_each_row(Logger& logger){ + for (const StoryCheckpoint& row : story_checkpoints()){ + const auto res = run_rows(logger, {.from = row.id, .to = row.id}); + if (res.result != UnitTestResult::PASSED){ + return std::format("Row {} failed: {}", row.id, res.message); + } + } + return true; +} + +UnitTestResult test_exit_gate(Logger& logger){ + return run_exit_test(logger, "01.05", r75_old_gate_exit(), SimMisses{}, r75_pond_pocket()); +} + +UnitTestResult test_exit_ravaged_path(Logger& logger){ + return run_exit_test(logger, "01.09", r81_old_cave_exit(), SimMisses{.fade = 0}, r81_below_the_mouth()); +} + +struct AutoStoryStorySimInput{ + std::string name; + std::function body; +}; + +struct AutoStoryStorySimExpectation{ +}; + +struct AutoStoryStorySimCase{ + AutoStoryStorySimInput input; + AutoStoryStorySimExpectation expectation; +}; + +class Test_AutoStoryStorySim : public UnitTest{ +public: + explicit Test_AutoStoryStorySim(AutoStoryStorySimCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Story sim: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + AutoStoryStorySimCase m_case; +}; + +} // namespace + + +const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { + { + .input = {"the maps' coord events are on open ground or doors", test_coord_events}, + .expectation = {}, + }, + { + .input = {"detector misses from 00.00 to 01.11", test_story_sim_misses}, + .expectation = {}, + }, + { + .input = {"00.00 to 01.11: the whole table, from the new game to Floaroma", test_story_sim_whole_table}, + .expectation = {}, + }, + { + .input = {"each row from 00.00 to 01.11 in isolation", test_story_sim_each_row}, + .expectation = {}, + }, + { + .input = {"r75, out of the Oreburgh Gate", test_exit_gate}, + .expectation = {}, + }, + { + .input = {"r81, out of the Ravaged Path", test_exit_ravaged_path}, + .expectation = {}, + }, +}; + +void add_tests_AutoStory_StorySim(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_STORY_SIM_CASES){ + database.add(item); + } +} + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.h index dfa12e07be..bc1ed57d3a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.h @@ -22,7 +22,7 @@ void add_tests_AutoStory_StorySim(UnitTestDatabase& database); -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index 8e92652ef0..275717d800 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -145,7 +145,7 @@ TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const } } -} +} // namespace ConsoleStoryStepIO::ConsoleStoryStepIO(VideoStream& stream, ProControllerContext& context) @@ -211,6 +211,6 @@ void ConsoleStoryStepIO::settle(Button button, const std::string& label, bool fa -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h index 60691c86b0..a6175834ac 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h @@ -27,6 +27,7 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ +// Abstract interface for story step input/output operations. class StoryStepIO{ public: virtual ~StoryStepIO() = default; @@ -80,7 +81,7 @@ class ConsoleStoryStepIO : public StoryStepIO{ -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index 8fc3c7c3c5..067a6281af 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -44,7 +44,7 @@ std::string label_of(const StoryStep& step){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "RouteIO::note() returned from a failure: " + message); } -} +} // namespace void StoryWalkSteps::begin_attempt(const std::string& row){ @@ -259,6 +259,6 @@ Outcome StoryWalkSteps::mash(RunState& state, const StoryStep& step){ -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index 8c21209913..fa89abaf14 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -23,6 +23,7 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ +// Executes walking and movement-related story steps via StoryStepIO. class StoryWalkSteps{ public: explicit StoryWalkSteps(StoryStepIO& io) @@ -68,7 +69,7 @@ class StoryWalkSteps{ -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.cpp index ab0bc9134b..fd90d56444 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.cpp @@ -67,7 +67,7 @@ Milliseconds per_tile(Direction direction, SimPace pace, bool can_run){ return route_ms_per_tile(direction, pace == SimPace::RUN && can_run ? MoveSpeed::RUN : MoveSpeed::WALK); } -} +} // namespace SimPos sim_pos(const TilePos& tile){ @@ -290,7 +290,7 @@ WalkStop walk_stop(SimStop stop){ return WalkStop::LIMIT; } -} +} // namespace WalkResult GridSimRouteIO::walk_to_wall(const RouteWallWalk& walk){ const SimPace pace = walk.options.pace == DpadPace::RUN ? SimPace::RUN : SimPace::WALK; @@ -359,6 +359,6 @@ void GridSimRouteIO::note(const std::string& text, RouteNote kind){ -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.h index f28b20d067..727aac0518 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.h @@ -48,6 +48,7 @@ struct SimPos{ int y = 0; bool operator==(const SimPos& other) const = default; }; +// Converts a TilePos to its fixed-point fractional simulation coordinate. SimPos sim_pos(const Pokemon::TilePos& tile); // Whether the player stands exactly on a tile. bool on_grid(const SimPos& pos); @@ -76,6 +77,7 @@ struct SimWorld{ std::optional can_run = std::nullopt; }; +// Reason why simulated player movement stopped. enum class SimStop{ DONE, // the input finished BLOCKED, // stopped by a wall, a person, or a door off its column @@ -83,6 +85,7 @@ enum class SimStop{ WARP, // stepped onto a door LIMIT, // a held walk ran out of time }; +// Returns the debug string for a SimStop reason. const char* sim_stop_name(SimStop stop); // What one input did. @@ -114,6 +117,7 @@ enum class SimPace{ RUN, // B held: a run once the player has the Running Shoes }; +// Simulates grid-based player movement and collisions in BDSP. class GridSim{ public: GridSim(SimWorld world, const Pokemon::TilePos& start, Pokemon::Direction facing, bool can_run); @@ -180,7 +184,7 @@ struct GridSimFailure{ -} -} -} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation #endif From f453d2aca5c98a7863a27fecbe458463fb1b69e7 Mon Sep 17 00:00:00 2001 From: dayfine Date: Thu, 5 Nov 2026 22:54:39 -0800 Subject: [PATCH 006/166] BDSP AutoStory sim: initialize all designated fields for Windows Clang --- .../AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp index af21d4bf85..0d3d718354 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -473,7 +473,7 @@ SimWorld SimExecutor::setup(const StoryWorld* world) const{ if (sim_world(armed.map) != world){ continue; } - SimTrigger trigger{.name = armed.trigger.name}; + SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; for (const TilePos& pos : armed.trigger.tiles){ trigger.tiles.push_back(story_to_world(*world, armed.map, pos)); } @@ -710,10 +710,10 @@ UnitTestResult run_exit_test(Logger& logger, const std::string& row_id, const St } std::vector runs; for (size_t i = 0; i < clean.misses().fades; i++){ - runs.push_back({.fade = i}); + runs.push_back({.fade = i, .banner = std::nullopt}); } for (size_t i = 0; i < clean.misses().banners; i++){ - runs.push_back({.banner = i}); + runs.push_back({.fade = std::nullopt, .banner = i}); } for (const SimMisses& m : runs){ SimExecutor sim(logger, m); @@ -844,7 +844,7 @@ UnitTestResult test_exit_gate(Logger& logger){ } UnitTestResult test_exit_ravaged_path(Logger& logger){ - return run_exit_test(logger, "01.09", r81_old_cave_exit(), SimMisses{.fade = 0}, r81_below_the_mouth()); + return run_exit_test(logger, "01.09", r81_old_cave_exit(), SimMisses{.fade = 0, .banner = std::nullopt}, r81_below_the_mouth()); } struct AutoStoryStorySimInput{ From 756354d4cbd70a4e68f1d6516520f753c49982fb Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 14:11:50 -0800 Subject: [PATCH 007/166] BDSP AutoStory: move GridSim and simulation tests into Simulation/ subdirectory --- .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 6 +++--- .../PokemonBDSP_AutoStory_GridSim.cpp | 0 .../PokemonBDSP_AutoStory_GridSim.h | 0 .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 2 +- .../PokemonBDSP_AutoStory_GridSim_Tests.h | 2 +- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 2 +- .../PokemonBDSP_AutoStory_StorySim_Tests.h | 0 ...kemonBDSP_AutoStory_StorySimulation_Tests.cpp | 0 ...PokemonBDSP_AutoStory_StorySimulation_Tests.h | 0 SerialPrograms/cmake/SourceFiles.cmake | 16 ++++++++-------- 10 files changed, 14 insertions(+), 14 deletions(-) rename SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/{Utils => Simulation}/PokemonBDSP_AutoStory_GridSim.cpp (100%) rename SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/{Utils => Simulation}/PokemonBDSP_AutoStory_GridSim.h (100%) rename SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/{ => Simulation}/PokemonBDSP_AutoStory_GridSim_Tests.cpp (97%) rename SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/{ => Simulation}/PokemonBDSP_AutoStory_GridSim_Tests.h (86%) rename SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/{ => Simulation}/PokemonBDSP_AutoStory_StorySim_Tests.cpp (99%) rename SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/{ => Simulation}/PokemonBDSP_AutoStory_StorySim_Tests.h (100%) rename SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/{ => Simulation}/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp (100%) rename SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/{ => Simulation}/PokemonBDSP_AutoStory_StorySimulation_Tests.h (100%) diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index d81838554c..73c0d12a29 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -6,15 +6,15 @@ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.h" -#include "Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.h" +#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h" -#include "Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.h" -#include "Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.h" +#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h" +#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h" #include "PokemonBDSP_Tests.h" diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp similarity index 100% rename from SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.cpp rename to SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h similarity index 100% rename from SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.h rename to SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp similarity index 97% rename from SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.cpp rename to SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 785c6a9638..ec8db51b68 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -20,7 +20,7 @@ #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Data/PokemonBDSP_AutoStory_Maps.h" #include "Data/PokemonBDSP_AutoStory_PlanCosts.h" -#include "Utils/PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_GridSim.h" #include "Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "PokemonBDSP_AutoStory_StoryExecutor.h" #include "PokemonBDSP_AutoStory_StoryPlaces.h" diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h similarity index 86% rename from SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.h rename to SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h index d80dd04f8b..dc085dda37 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h @@ -15,7 +15,7 @@ namespace PokemonBDSP{ -// The grid simulation (Utils/PokemonBDSP_AutoStory_GridSim.h): the moves +// The grid simulation (PokemonBDSP_AutoStory_GridSim.h): the moves // measured on the console, the story table's routes walked by the route // walker on it, and walks that missed doors on the console missing them here. void add_tests_AutoStory_GridSim(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp similarity index 99% rename from SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp rename to SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 0d3d718354..4215dd977e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -40,7 +40,7 @@ #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Data/PokemonBDSP_AutoStory_CoordEvents.h" #include "Data/PokemonBDSP_AutoStory_Maps.h" -#include "Utils/PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_GridSim.h" #include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP_AutoStory_Events.h" #include "PokemonBDSP_AutoStory_StoryExecutor.h" diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h similarity index 100% rename from SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.h rename to SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp similarity index 100% rename from SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp rename to SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.h similarity index 100% rename from SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.h rename to SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.h diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 109e75f726..47d09ba3a9 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1567,10 +1567,10 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h - Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp - Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.h - Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.cpp - Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_GridSim.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp @@ -1700,8 +1700,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h - Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.cpp - Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySim_Tests.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.h Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp @@ -1725,8 +1725,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h - Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.cpp - Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_GridSim_Tests.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp From ac1ef0b49d45099c28d73c8ca37cbb8d5608837f Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 14:21:05 -0800 Subject: [PATCH 008/166] BDSP AutoStory: align Oreburgh Mine maps, corridor legs, and Floaroma pathing --- .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 2 + .../Actions/PokemonBDSP_AutoStory_Battle.cpp | 6 +- .../Actions/PokemonBDSP_AutoStory_Talks.cpp | 4 +- .../PokemonBDSP_AutoStory_WildBattle.cpp | 5 +- .../PokemonBDSP_AutoStory_WildBattle.h | 2 +- .../PokemonBDSP_AutoStory_RoutePlanner.cpp | 21 +- .../PokemonBDSP_AutoStory_RouteRecords.cpp | 8 +- .../PokemonBDSP_AutoStory_Segment00Lines.cpp | 2 +- .../Data/PokemonBDSP_AutoStory_StoryMaps.cpp | 17 +- .../Data/PokemonBDSP_AutoStory_StoryWorld.cpp | 24 ++- .../Data/PokemonBDSP_AutoStory_StoryWorld.h | 7 +- .../PokemonBDSP_AutoStory_WallRecovery.cpp | 155 ++++++++++++++ .../Data/PokemonBDSP_AutoStory_WallRecovery.h | 44 ++++ ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 155 ++++++++++++++ ...PokemonBDSP_AutoStory_RecoveryWalk_Tests.h | 15 ++ ...kemonBDSP_AutoStory_RoutePlanner_Tests.cpp | 150 +++++++++++++ .../PokemonBDSP_AutoStory_StoryMaps_Tests.cpp | 32 +++ .../PokemonBDSP_AutoStory_StoryPlaces.cpp | 15 ++ .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 30 ++- .../PokemonBDSP_AutoStory_StoryTable.cpp | 202 ++++++++++-------- ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 2 +- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 106 +++++++-- .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 3 + .../PokemonBDSP_AutoStory_GridSim.cpp | 36 +++- .../PokemonBDSP_AutoStory_GridSim.h | 21 +- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 99 +++++++-- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 90 ++++++-- .../Utils/PokemonBDSP_AutoStory_Walk.cpp | 29 +++ .../Utils/PokemonBDSP_AutoStory_Walk.h | 5 + SerialPrograms/cmake/SourceFiles.cmake | 4 + devtools/maps/bdsp_maps.py | 2 +- ...y-Lesson-Lab-Controller-And-Permissions.md | 100 +++++++++ docs/design/AutoStory-Lessons.md | 7 + 33 files changed, 1224 insertions(+), 176 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h create mode 100644 docs/design/AutoStory-Lesson-Lab-Controller-And-Permissions.md diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index 73c0d12a29..72c29a2fa1 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -7,6 +7,7 @@ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h" @@ -37,6 +38,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_Walk(database); add_tests_AutoStory_PlannedRoute(database); add_tests_AutoStory_GridSim(database); + add_tests_AutoStory_RecoveryWalk(database); add_tests_AutoStory_StorySim(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.cpp index 568247aba4..737834e023 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.cpp @@ -417,12 +417,12 @@ void fight_story_battle(VideoStream& stream, ProControllerContext& context, cons } void fight_trainer(VideoStream& stream, ProControllerContext& context, const std::string& label){ - // The best move on the menu each turn, whatever the starter. - fight_with_best_move(stream, context, {.battle_type = BattleType::TRAINER, .format = BattleFormat::SINGLES, .switch_on_faint = false}, label); + // The best move on the menu each turn, whatever the starter; the next Pokemon after a faint. + fight_with_best_move(stream, context, {.battle_type = BattleType::TRAINER, .format = BattleFormat::SINGLES, .switch_on_faint = true}, label); } void fight_wild_battle(VideoStream& stream, ProControllerContext& context, const std::string& label){ - fight_with_best_move(stream, context, {.battle_type = BattleType::STANDARD, .format = BattleFormat::SINGLES, .switch_on_faint = false}, label); + fight_with_best_move(stream, context, {.battle_type = BattleType::STANDARD, .format = BattleFormat::SINGLES, .switch_on_faint = true}, label); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp index 57a2250edf..ca70e7b09f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp @@ -77,7 +77,7 @@ bool talk_or_fight(VideoStream& stream, ProControllerContext& context, const std finish_dialogue(stream, context, BUTTON_B, label + " after the battle"); } if (!in_pokemon_center(stream)){ - use_potion_first_pokemon(stream, context, 0.5); + use_potion_first_pokemon(stream, context, 0.8); } return true; } @@ -190,7 +190,7 @@ void fight_route_trainer(VideoStream& stream, ProControllerContext& context, con context.wait_for_all_requests(); // The next trainer may be a few tiles on: check HP now. With no // Potion in the Bag this only looks. - use_potion_first_pokemon(stream, context, 0.5); + use_potion_first_pokemon(stream, context, 0.8); } bool sign_text_matches(const std::string& text, const std::string& key){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.cpp index 8be35a67dd..9f8dbf52c2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.cpp @@ -230,8 +230,9 @@ bool run_until_escaped( const int result = run_until(stream, context, [](ProControllerContext& controller){ - pbf_press_button(controller, BUTTON_A, 60ms, 0ms); - pbf_wait(controller, 4s); + pbf_mash_button(controller, BUTTON_ZL, 1000ms); + pbf_mash_button(controller, BUTTON_A, 1000ms); + pbf_mash_button(controller, BUTTON_B, 3000ms); controller.wait_for_all_requests(); }, {battle_end}); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.h index 6ef1b1b8fa..7ca96f2bb7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.h @@ -40,7 +40,7 @@ void escape_wild_battle( VideoStream& stream, ProControllerContext& context, BattleType battle_type = BattleType::STANDARD, - std::chrono::seconds timeout = std::chrono::seconds(30) + std::chrono::seconds timeout = std::chrono::seconds(60) ); // escape_wild_battle() for a standard wild battle, as the walker takes it diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp index f867e407bc..e721e439c3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp @@ -376,6 +376,12 @@ class RobustSearch{ if (expansion.next.size() > m_costs.max_spread || expansion.next == spread){ return; } + if (spread != m_start){ + const TileLeg& prev = m_nodes.at(spread).leg.leg; + if (expansion.leg.direction == prev.direction && !prev.ends_at_wall){ + expansion.cost -= m_costs.per_leg; + } + } const long long total = cost + expansion.cost; auto iter = m_nodes.find(expansion.next); if (iter != m_nodes.end() && iter->second.cost <= total){ @@ -393,7 +399,20 @@ class RobustSearch{ at = step.parent; } std::reverse(legs.begin(), legs.end()); - return legs; + std::vector consolidated; + for (const PlannedLeg& planned : legs){ + if (!consolidated.empty() && + consolidated.back().leg.direction == planned.leg.direction && + !consolidated.back().leg.ends_at_wall + ){ + consolidated.back().leg.tiles += planned.leg.tiles; + consolidated.back().leg.ends_at_wall = planned.leg.ends_at_wall; + consolidated.back().after = planned.after; + }else{ + consolidated.push_back(planned); + } + } + return consolidated; } const StoryWorld& m_world; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp index c30f1528d1..00c53d3832 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp @@ -32,11 +32,9 @@ std::vector checkpoint_0001_records(){ }, "Segment00Lines line 2, not walked by the program yet"}, {"00.01", "Route 201: Barry's tall-grass warning, then west to the Lakefront", "Route 201", "Route201", true, map_point("Route201", "route_201_arrival"), { {Direction::NORTH, 6, LegEnd::COUNT, "up the exit path to (15, 18): Barry's warning fires on that row"}, - {Direction::WEST, 1, LegEnd::COUNT, "after the scene, to (14, 18); west of it is the 201 sign and trees (r16)"}, - {Direction::NORTH, 1, LegEnd::COUNT, "onto row 17, the top of the exit path's T"}, - {Direction::WEST, 2, LegEnd::COUNT, "along row 17 to column 12"}, - {Direction::NORTH, 1, LegEnd::COUNT, "to row 16, the lower level's row to the Lakefront"}, - {Direction::WEST, 12, LegEnd::COUNT, "to (0, 16), the route's last tile"}, + {Direction::WEST, 1, LegEnd::COUNT, "after the scene, to (14, 18); west of it is trees (r16)"}, + {Direction::NORTH, 2, LegEnd::COUNT, "past the 201 sign at (13, 17) onto row 16, the lower level's row to the Lakefront (probe-r201-sign)"}, + {Direction::WEST, 14, LegEnd::COUNT, "to (0, 16), the route's last tile"}, {Direction::WEST, 0, LegEnd::BANNER, "on west onto the Verity Lakefront"}, }, "Segment00Lines lines 2 and 3, not walked by the program yet; traced on the Route201 map, the decomp's since #111"}, {"00.01", "Verity Lakefront: to below the lake's entrance", "Verity Lakefront", "VerityLakefront", true, map_point("VerityLakefront", "lakefront_arrival"), { diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp index f0e86e14c4..c247bc3a35 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp @@ -125,7 +125,7 @@ const std::vector& lines(){ twinleaf_point("barry_doorstep"), twinleaf({15, 12}), twinleaf_point("twinleaf_north_exit"), route201_point("barry_warning"), }, "Barry's tall-grass warning", {"Barry's tall-grass warning"}), walked("00.01", "Route 201's west half to the lake's entrance", { - route201_point("barry_warning"), route201({14, 18}), route201({14, 17}), route201({12, 17}), route201({12, 16}), route201({0, 16}), + route201_point("barry_warning"), route201({14, 18}), route201({14, 16}), route201({0, 16}), lakefront({20, 23}), lakefront({20, 21}), lakefront({17, 21}), lakefront_point("lake_entrance"), }, "Barry at the lake's entrance", {"Barry at the lake's entrance", "Route 201's row 19 after the warning"}), walked("00.03", "the lake's entrance back to Rowan", { diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp index 4e21902d76..c600154fc6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp @@ -54,10 +54,25 @@ MapData crop(const MapData& map, const TilePos& corner, int width, int height){ for (Pokemon::MapObject object : map.objects){ object.x -= corner.x; object.y -= corner.y; - if (cropped.tiles.contains({object.x, object.y})){ + if (object.wander){ + object.wander->x0 -= corner.x; + object.wander->x1 -= corner.x; + object.wander->y0 -= corner.y; + object.wander->y1 -= corner.y; + } + if (cropped.tiles.contains({object.x, object.y}) || (object.wander + && object.wander->x1 >= 0 && object.wander->y1 >= 0 + && object.wander->x0 < width && object.wander->y0 < height)){ cropped.objects.push_back(std::move(object)); } } + for (auto warp : map.warps){ + warp.x -= corner.x; + warp.y -= corner.y; + if (cropped.tiles.contains({warp.x, warp.y})){ + cropped.warps.push_back(std::move(warp)); + } + } return cropped; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp index c245bf283e..bf3fe46218 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp @@ -56,12 +56,17 @@ void StoryWorld::add(std::string name, const Pokemon::MapData& map, const TilePo throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Map placed twice: " + name); } } - Placed placed{std::move(name), map.tiles, {}, offset}; + Placed placed{.name = std::move(name), .tiles = map.tiles, .occupied = {}, .wander = {}, .warps = {}, .offset = offset}; for (const Pokemon::MapObject& object : map.objects){ if (!object.wander){ placed.occupied.push_back({object.x, object.y}); + }else{ + placed.wander.push_back(*object.wander); } } + for (const auto& warp : map.warps){ + placed.warps.push_back({warp.x, warp.y}); + } check_overlap(placed); m_maps.push_back(std::move(placed)); rebuild(); @@ -138,6 +143,18 @@ void StoryWorld::paint(const Placed& placed, const TilePos& corner){ for (const TilePos& pos : placed.occupied){ Pokemon::cell_at(m_cells, {corner.x + pos.x, corner.y + pos.y}).occupant = PERSON; } + for (const auto& box : placed.wander){ + for (int y = std::max(0, box.y0); y <= std::min(placed.tiles.height - 1, box.y1); y++){ + for (int x = std::max(0, box.x0); x <= std::min(placed.tiles.width - 1, box.x1); x++){ + Pokemon::cell_at(m_cells, {corner.x + x, corner.y + y}).recovery_hazard = true; + } + } + } + for (const auto& warp : placed.warps){ + if (placed.tiles.contains(warp)){ + Pokemon::cell_at(m_cells, {corner.x + warp.x, corner.y + warp.y}).recovery_hazard = true; + } + } } const StoryWorld::Cell* StoryWorld::cell(const TilePos& pos) const{ @@ -162,8 +179,11 @@ std::optional StoryWorld::tile(const TilePos& pos) const{ return found->tile; } -StoryWorld::Occupant StoryWorld::occupied(const TilePos& pos) const{ +StoryWorld::Occupant StoryWorld::occupied(const TilePos& pos, OccupancyUse use) const{ const Cell* found = cell(pos); + if (found && use == OccupancyUse::WALL_RECOVERY && found->recovery_hazard){ + return PERSON; + } return found == nullptr ? NOBODY : found->occupant; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h index dc5b76e3c5..751d9cd7bb 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h @@ -55,7 +55,9 @@ class StoryWorld{ PERSON, BLOCKED, }; - Occupant occupied(const Pokemon::TilePos& pos) const; + // Recovery also excludes wandering areas and declared warps. + enum class OccupancyUse{ MOVEMENT, WALL_RECOVERY }; + Occupant occupied(const Pokemon::TilePos& pos, OccupancyUse use = OccupancyUse::MOVEMENT) const; // Blocks a tile found in the way on the console. Tiles off the maps // are left alone. @@ -74,12 +76,15 @@ class StoryWorld{ std::string name; Pokemon::Grid tiles; std::vector occupied; // local tiles + std::vector wander; // recovery hazards, not terrain + std::vector warps; Pokemon::TilePos offset; }; struct Cell{ bool covered = false; Pokemon::TileKind tile = Pokemon::TileKind::WALL; Occupant occupant = NOBODY; + bool recovery_hazard = false; }; void check_overlap(const Placed& map) const; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp new file mode 100644 index 0000000000..7ccc8549c5 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp @@ -0,0 +1,155 @@ +/* BDSP Wall Recovery + * + * From: https://github.com/PokemonAutomation/ + */ +#include +#include "PokemonBDSP_AutoStory_WallRecovery.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace{ + +using Pokemon::Direction; +using Pokemon::TilePos; + +// A wall ray must stay on the same map and walk one tile per step. A +// ledge may be legal travel but must not become a localization anchor. +std::optional safe_wall(const StoryWorld& world, TilePos from, Direction direction){ + const auto map = world.to_local(from); + if (!map || !standable(world, from) + || world.occupied(from, StoryWorld::OccupancyUse::WALL_RECOVERY) == StoryWorld::PERSON){ + return std::nullopt; + } + const WallHit wall = slide_to_wall(world, from, direction); + if (!wall.anchored + || world.occupied(wall.wall, StoryWorld::OccupancyUse::WALL_RECOVERY) == StoryWorld::PERSON){ + return std::nullopt; + } + while (from != wall.stop){ + const auto next = step(world, from, direction); + const auto local = next ? world.to_local(*next) : std::nullopt; + if (!next || *next != from.next(direction) || !local || local->map != map->map + || world.occupied(*next, StoryWorld::OccupancyUse::WALL_RECOVERY) == StoryWorld::PERSON){ + return std::nullopt; + } + from = *next; + } + return wall; +} + +class WallPolicy{ +public: + using Hypothesis = TilePos; + using Position = TilePos; + using Hold = TileLeg; + + static Position position(const Hypothesis& at){ return at; } + static int tiles(const Hold& hold){ return (int)hold.tiles; } + static std::optional> hold( + const StoryWorld& world, const std::vector& from, Direction direction + ){ + std::vector ends; + size_t longest = 0; + for (const auto& start : from){ + const auto wall = safe_wall(world, start, direction); + if (!wall){ + return std::nullopt; + } + longest = std::max(longest, wall->tiles); + if (std::find(ends.begin(), ends.end(), wall->stop) == ends.end()){ + ends.push_back(wall->stop); + } + } + return Pokemon::WallRecoveryStep{ + .positions = std::move(ends), + .hold = {.direction = direction, .tiles = longest, .ends_at_wall = true}, + }; + } + +}; + +} // namespace + +std::vector> wall_recovery_candidates( + const StoryWorld& world, const std::vector& from, + const Pokemon::WallRecoveryLimits& limits +){ + for (const auto& tile : from){ + if (!standable(world, tile)){ + return {}; + } + } + return Pokemon::find_wall_anchors(from, world, limits); +} + +std::vector interrupted_leg_positions( + const StoryWorld& world, const std::vector& from, Direction direction, size_t tiles +){ + std::vector positions; + for (TilePos at : from){ + for (size_t count = 0; count <= tiles; count++){ + if (std::find(positions.begin(), positions.end(), at) == positions.end()){ + positions.push_back(at); + } + const auto next = step(world, at, direction); + if (count == tiles || !next){ + break; + } + at = *next; + } + } + return positions; +} + +namespace{ +std::vector recovery_legs( + const StoryWorld& world, std::vector from, const std::vector& holds +){ + std::vector legs; + for (const auto& hold : holds){ + std::vector after; + for (const auto& at : from){ + const TilePos end = slide_to_wall(world, at, hold.direction).stop; + if (std::find(after.begin(), after.end(), end) == after.end()){ + after.push_back(end); + } + } + legs.push_back({.leg = hold, .after = after}); + from = std::move(after); + } + return legs; +} +} // namespace + +std::optional> plan_recovered_route( + const StoryWorld& world, const std::vector& from, + const std::function& goal, const RobustPlanCosts& costs +){ + if (from.empty()){ + return std::nullopt; + } + if (std::all_of(from.begin(), from.end(), goal)){ + return std::vector(); + } + if (from.size() == 1){ + return plan_robust_route(world, from, goal, costs); + } + auto anchors = wall_recovery_candidates(world, from); + std::stable_sort(anchors.begin(), anchors.end(), [&](const auto& a, const auto& b){ + return goal(a.at) && !goal(b.at); + }); + for (const auto& anchor : anchors){ + const auto back = plan_robust_route(world, std::vector{anchor.at}, goal, costs); + if (back){ + auto route = recovery_legs(world, from, anchor.holds); + route.insert(route.end(), back->begin(), back->end()); + return route; + } + } + return std::nullopt; +} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h new file mode 100644 index 0000000000..862e2a2f14 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h @@ -0,0 +1,44 @@ +/* BDSP Wall Recovery + * + * From: https://github.com/PokemonAutomation/ + * + * BDSP's movement adapter for shared native wall convergence. Predictions + * do not confirm controller execution; the walker must establish arrival. + */ +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_WallRecovery_H +#define PokemonAutomation_PokemonBDSP_AutoStory_WallRecovery_H + +#include "Pokemon/Navigation/Pokemon_WallRecovery.h" +#include "PokemonBDSP_AutoStory_RoutePlanner.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +// Safe holds for every possible position, within one explicitly placed map. +// Never anchors against a person, crosses a door/map edge or hops a ledge. +// Caller must uncover trainer sight/scene hazards absent from StoryWorld. +std::vector> wall_recovery_candidates( + const StoryWorld& world, const std::vector& from, + const Pokemon::WallRecoveryLimits& limits = Pokemon::WallRecoveryLimits() +); + +// Every legal prefix, including zero movement, of an interrupted counted leg. +std::vector interrupted_leg_positions( + const StoryWorld& world, const std::vector& from, + Pokemon::Direction direction, size_t tiles +); + +// Establish a common wall anchor before continuing from an uncertain pose. +// Single positions retain the existing planner. Ambiguous positions without +// a safe anchor fail instead of choosing one. Goals already held need no walk. +std::optional> plan_recovered_route( + const StoryWorld& world, const std::vector& from, + const std::function& goal, + const RobustPlanCosts& costs +); + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp new file mode 100644 index 0000000000..8b9c5dd4c8 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -0,0 +1,155 @@ +/* BDSP Recovery Walk Tests + * + * From: https://github.com/PokemonAutomation/ + * + * November 5 mine report: EAST 14 moved 4 beside Machop on row 15. + * The exact deployed revision/run ID is unavailable. BEFORE/AFTER events + * and two interrupted advances are explicit diagnostics, not an inferred + * physical cause. Run the real story step and route walker on GridSim. + */ +#include +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Utils/PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_RecoveryWalk_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace{ +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::TilePos; + +class InterruptingRouteIO : public GridSimRouteIO{ +public: + InterruptingRouteIO(GridSim& sim, std::vector& notes, + std::vector taps, size_t interrupted_holds) + : GridSimRouteIO(sim, notes, std::move(taps)), m_left(interrupted_holds) + {} + virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override{ + if (m_left > 0){ + m_left--; + return {.stop = WalkStop::LIMIT, .walked = 400ms, .wild_battles = 1}; + } + return GridSimRouteIO::walk_to_wall(walk); + } +private: + size_t m_left; +}; + +// Only walking is needed for this real LEGS step. Unexpected story actions +// fail the test. The actual RouteWalker executes through the GridSim RouteIO. +class RecoveryStepIO : public StoryStepIO{ +public: + explicit RecoveryStepIO(RouteIO& route) : m_route(route){} + virtual RouteIO& route() override{ return m_route; } + virtual void fight(const std::string&) override{ throw GridSimFailure{"unexpected trainer"}; } + virtual void walk_until_stopped(Direction, size_t, const std::string&) override{ throw GridSimFailure{"unexpected blind hold"}; } + virtual bool run_until_map(Direction, Milliseconds, const std::string&, const std::string&) override{ throw GridSimFailure{"unexpected banner walk"}; } + virtual bool run_into_door(Direction, bool) override{ throw GridSimFailure{"unexpected door"}; } + virtual std::optional tap_to_banner(Direction, const std::string&, size_t) override{ throw GridSimFailure{"unexpected banner"}; } + virtual void settle(Button, const std::string&, bool) override{ throw GridSimFailure{"unexpected scene"}; } +private: + RouteIO& m_route; +}; + +const Pokemon::StoryStep& mine_step(){ + for (const auto& row : story_checkpoints()){ + for (const auto& step : row.steps){ + if (row.id == "01.03" && step.name == "below_roark"){ + return step; + } + } + } + throw GridSimFailure{"missing native mine step"}; +} + +struct RecoveryInput{ + std::string name; + std::vector taps; + Direction direction = Direction::SOUTH; + size_t tiles = 5; + SimEncounterPhase phase = SimEncounterPhase::BEFORE_MOVEMENT; + WalkOrigin origin = WalkOrigin::CURRENT_LEG; + size_t interrupted_holds = 0; +}; +struct RecoveryExpectation{ + std::string failure = {}; + TilePos end = {.x = 18, .y = 29}; + Direction facing = Direction::WEST; +}; +struct RecoveryCase{ + RecoveryInput input; + RecoveryExpectation expectation; +}; + +class Test_RecoveryWalk : public UnitTest{ +public: + explicit Test_RecoveryWalk(RecoveryCase data) + : UnitTest("PokemonBDSP::AutoStory - Recovery walk: " + data.input.name), m_case(std::move(data)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const StoryWorld* world = story_plan_world("OreburghMine", "OreburghMine"); + if (world == nullptr){ + return "Missing native mine world."; + } + GridSim sim({.world = world}, world->to_world("OreburghMine", {15, 10}), Direction::SOUTH, true); + std::vector taps; + for (size_t tap : m_case.input.taps){ + taps.push_back({.label = "below_roark", .direction = m_case.input.direction, + .requested_tiles = m_case.input.tiles, .tap = tap, .phase = m_case.input.phase, .origin = m_case.input.origin}); + } + std::vector notes; + InterruptingRouteIO route(sim, notes, std::move(taps), m_case.input.interrupted_holds); + RecoveryStepIO io(route); + StoryWalkSteps walks(io); + walks.begin_attempt("01.03"); + Pokemon::RunState state{.pose = Pokemon::tile_pose("OreburghMine", {{15, 10}}, Direction::SOUTH), .flags = {}}; + std::string failure; + std::optional declared; + try{ + const auto outcome = walks.legs(state, mine_step()); + failure = outcome.failure; + declared = outcome.pose; + }catch (const GridSimFailure& error){ + failure = error.message; + } + if (!m_case.expectation.failure.empty()){ + return failure.find(m_case.expectation.failure) != std::string::npos ? UnitTestResult(true) + : UnitTestResult("Expected " + m_case.expectation.failure + ", got " + failure); + } + const auto end = story_to_local(*world, "OreburghMine", nearest_tile(sim.player().pos)); + if (!failure.empty() || !end || *end != m_case.expectation.end || !declared + || Pokemon::facing_of(*declared) != sim.player().facing || sim.player().facing != m_case.expectation.facing){ + return "Expected below Roark (18,29), got " + to_string(sim.player().pos) + ": " + failure; + } + return true; + } +private: + RecoveryCase m_case; +}; +} // namespace + +void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ + const RecoveryCase CASES[] = { + {.input = {.name = "uninterrupted native mine step", .taps = {}}, .expectation = {.failure = ""}}, + {.input = {.name = "last tap interrupted before movement", .taps = {5}}, .expectation = {.failure = ""}}, + {.input = {.name = "last tap completed before battle", .taps = {5}, .phase = SimEncounterPhase::AFTER_MOVEMENT}, .expectation = {.failure = ""}}, + {.input = {.name = "two interrupted advances, row 15", .taps = {4, 5}}, .expectation = {.failure = ""}}, + {.input = {.name = "last west leg recovers position and facing", .taps = {9}, .direction = Direction::WEST, .tiles = 9}, .expectation = {.failure = ""}}, + {.input = {.name = "repeat the interrupted recovery hold", .taps = {5}, .interrupted_holds = 1}, .expectation = {.failure = ""}}, + {.input = {.name = "recovery hold budget exhausted", .taps = {5}, .interrupted_holds = 10}, .expectation = {.failure = "recovery budget"}}, + {.input = {.name = "first input may belong to previous leg", .taps = {1}}, .expectation = {.failure = "encounter_origin_unknown"}}, + {.input = {.name = "late encounter origin unknown", .taps = {5}, .origin = WalkOrigin::MAY_PRECEDE_LEG}, .expectation = {.failure = "encounter_origin_unknown"}}, + }; + for (const RecoveryCase& scenario : CASES){ + database.add(scenario); + } +} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h new file mode 100644 index 0000000000..9ee770013b --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h @@ -0,0 +1,15 @@ +/* BDSP Recovery Walk Tests + * From: https://github.com/PokemonAutomation/ + */ +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RecoveryWalk_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RecoveryWalk_Tests_H +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +// Register mine interruption, localization and bounded recovery scenarios. +void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database); +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp index 11f82e3cbd..4d95398bd8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp @@ -15,6 +15,9 @@ #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "Data/PokemonBDSP_AutoStory_WallRecovery.h" +#include "Data/PokemonBDSP_AutoStory_Maps.h" +#include "Utils/PokemonBDSP_AutoStory_GridSim.h" #include "PokemonBDSP_AutoStory_RoutePlanner_Tests.h" namespace PokemonAutomation{ @@ -135,6 +138,126 @@ UnitTestResult test_plan_robust_route(Logger&){ } +// November 5 mine report: credited taps need not establish physical pose. +// The two phases are explicit diagnostics, not inferred console timing. +struct EncounterInput{ + std::string name; + SimEncounterPhase phase; +}; +struct EncounterExpectation{ + TilePos end; + size_t battles = 1; + size_t credited = 5; +}; +struct EncounterCase{ + EncounterInput input; + EncounterExpectation expectation; +}; +class Test_InterruptedMineTaps : public UnitTest{ +public: + explicit Test_InterruptedMineTaps(EncounterCase scenario) + : UnitTest("PokemonBDSP::AutoStory - Encounter credits: " + scenario.input.name), m_case(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + StoryWorld mine; + mine.add("OreburghMine", story_map("OreburghMine"), {0, 0}); + GridSim sim({.world = &mine}, {15, 12}, Direction::SOUTH, /*can_run=*/false); + std::vector notes; + GridSimRouteIO io(sim, notes, {{.label = "south", .direction = Direction::SOUTH, + .requested_tiles = 5, .tap = 5, .phase = m_case.input.phase}}); + const auto result = io.walk_taps(Direction::SOUTH, 5, "south"); + const auto& expected = m_case.expectation; + const TilePos actual = nearest_tile(sim.player().pos); + if (result.wild_battles != expected.battles || result.moved_chunks != expected.credited || actual != expected.end){ + return std::format("Expected {} battles, {} credits, tile {}; got {}, {}, {}.", + expected.battles, expected.credited, Pokemon::to_string(expected.end), + result.wild_battles, result.moved_chunks, Pokemon::to_string(actual)); + } + return true; + } +private: + EncounterCase m_case; +}; + +// Empty map name selects a synthetic corridor: ####### / #.....# / #######. +// Both possible starts (1,1)/(5,1) must share a safe wall ray. NPCs and +// warps on that ray or its wall invalidate it; ordinary terrain is unchanged. +struct RecoveryGeometryInput{ + std::string name; + std::string map = {}; + std::vector from; + std::optional wander = {}; + std::vector warps = {}; +}; +struct RecoveryGeometryExpectation{ + std::optional anchor; + Direction direction = Direction::SOUTH; + size_t holds = 1; + std::optional free_tile = {}; +}; +struct RecoveryGeometryCase{ + RecoveryGeometryInput input; + RecoveryGeometryExpectation expectation; +}; + +Pokemon::MapData recovery_map(const RecoveryGeometryInput& input){ + Pokemon::MapData map; + if (!input.map.empty()){ + return story_map(input.map); + } + map.name = "RecoveryDiagnostic"; + map.tiles = Pokemon::Grid{7, 3, {}}; + for (const char* row : {"#######", "#.....#", "#######"}){ + for (char glyph : std::string(row)){ + map.tiles.cells.push_back(*Pokemon::tile_from_glyph(glyph)); + } + } + if (input.wander){ + map.objects.push_back({.name = "wanderer", .x = 3, .y = 1, .facing = std::nullopt, + .wander = input.wander, .trainer = std::nullopt, .hide_flag = std::nullopt}); + } + for (const auto& warp : input.warps){ + map.warps.push_back({.x = warp.x, .y = warp.y, .to = std::nullopt}); + } + return map; +} + +class Test_RecoveryGeometry : public UnitTest{ +public: + explicit Test_RecoveryGeometry(RecoveryGeometryCase scenario) + : UnitTest("PokemonBDSP::AutoStory - Recovery geometry: " + scenario.input.name), m_case(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const auto& expected = m_case.expectation; + const auto map = recovery_map(m_case.input); + StoryWorld world; + world.add(map.name, map, {0, 0}); + if (expected.free_tile && (!standable(world, *expected.free_tile) + || world.occupied(*expected.free_tile) != StoryWorld::NOBODY)){ + return "Expected ordinary movement to remain free at " + Pokemon::to_string(*expected.free_tile); + } + const auto anchors = wall_recovery_candidates(world, m_case.input.from); + const auto actual = anchors.empty() ? std::optional() : std::optional(anchors.front().at); + if (actual != expected.anchor){ + return std::format("Expected anchor {}, got {}.", + expected.anchor ? Pokemon::to_string(*expected.anchor) : "none", + actual ? Pokemon::to_string(*actual) : "none"); + } + if (anchors.empty()){ + return true; + } + const auto& holds = anchors.front().holds; + if (holds.size() != expected.holds || holds.empty() || holds.front().direction != expected.direction){ + return std::format("Expected {} holds beginning {}, got {} beginning {}.", + expected.holds, Pokemon::direction_name(expected.direction), holds.size(), + holds.empty() ? "none" : Pokemon::direction_name(holds.front().direction)); + } + return true; + } +private: + RecoveryGeometryCase m_case; +}; + // A trainer's sight stops at the first tile the player cannot stand on, // and a leg through it is reported; a leg that is stopped throws. UnitTestResult test_trainer_sight(Logger&){ @@ -187,6 +310,27 @@ class Test_RoutePlanner : public UnitTest{ RoutePlannerCase m_case; }; +const EncounterCase ENCOUNTER_CASES[] = { + {.input = {.name = "before movement", .phase = SimEncounterPhase::BEFORE_MOVEMENT}, + .expectation = {.end = {.x = 15, .y = 16}}}, + {.input = {.name = "after movement", .phase = SimEncounterPhase::AFTER_MOVEMENT}, + .expectation = {.end = {.x = 15, .y = 17}}}, +}; + +const RecoveryGeometryCase GEOMETRY_CASES[] = { + {.input = {.name = "mine rows converge south", .map = "OreburghMine", .from = {{15, 15}, {15, 16}, {15, 17}}}, + .expectation = {.anchor = TilePos{.x = 15, .y = 17}}}, + {.input = {.name = "r55 tiles converge east", .map = "Route202", .from = {{27, 5}, {26, 5}}}, + .expectation = {.anchor = TilePos{.x = 30, .y = 5}, .direction = Direction::EAST}}, + {.input = {.name = "wandering area is unsafe", .from = {{1, 1}, {5, 1}}, + .wander = Pokemon::TileBox{.x0 = 2, .y0 = 1, .x1 = 4, .y1 = 1}}, + .expectation = {.anchor = std::nullopt, .free_tile = TilePos{.x = 3, .y = 1}}}, + {.input = {.name = "warp crossings are unsafe", .from = {{1, 1}, {5, 1}}, .warps = {{3, 1}}}, + .expectation = {.anchor = std::nullopt}}, + {.input = {.name = "warps on blocked glyphs are unsafe", .from = {{1, 1}, {5, 1}}, .warps = {{0, 1}, {6, 1}}}, + .expectation = {.anchor = std::nullopt}}, +}; + } // namespace @@ -213,6 +357,12 @@ void add_tests_AutoStory_RoutePlanner(UnitTestDatabase& database){ for (const auto& item : ROUTE_PLANNER_CASES){ database.add(item); } + for (const auto& scenario : ENCOUNTER_CASES){ + database.add(scenario); + } + for (const auto& scenario : GEOMETRY_CASES){ + database.add(scenario); + } } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp index 62dec89465..141fedf46f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp @@ -174,6 +174,34 @@ UnitTestResult test_oreburgh_gym_column(Logger& logger){ return true; } +// Oreburgh Mine B1F (the entrance hall): +// The hallway connects Oreburgh City above with the Coal Room below. +// Row 1 contains warp doors (11..13, 1) leading to the city. +// Row 21 contains warp doors (11..13, 21) leading to the coal room. +// Column 12 is unobstructed south from landing (12, 1) to warp door (12, 21). +// Column 11 is unobstructed north from landing (11, 21) to warp door (11, 1). +UnitTestResult test_oreburgh_mine_hall(Logger& logger){ + const StoryWorld hall = alone("OreburghMineB1F"); + for (int x = 11; x <= 13; x++){ + if (hall.tile({x, 1}) != TileKind::DOOR){ + return std::format("OreburghMineB1F ({}, 1) is not a DOOR tile (exit to city).", x); + } + if (hall.tile({x, 21}) != TileKind::DOOR){ + return std::format("OreburghMineB1F ({}, 21) is not a DOOR tile (entrance to coal room).", x); + } + } + for (int y = 2; y <= 20; y++){ + if (!standable(hall, {12, y})){ + return std::format("OreburghMineB1F column 12 row {} is blocked; expected clear path to coal room.", y); + } + if (!standable(hall, {11, y})){ + return std::format("OreburghMineB1F column 11 row {} is blocked; expected clear path to city exit.", y); + } + } + logger.log("OreburghMineB1F: columns 11 and 12 are clear between row 1 and row 21 warp doors."); + return true; +} + // Each traceable record with a start tile starts on ground, and its legs // counted in whole tiles trace on its map up to the first leg that ends // some other way. @@ -256,6 +284,10 @@ const StoryMapsCase STORY_MAPS_CASES[] = { .input = {"Oreburgh Gym: the column up to Roark", test_oreburgh_gym_column}, .expectation = {}, }, + { + .input = {"Oreburgh Mine B1F: the entrance hall corridor and warps", test_oreburgh_mine_hall}, + .expectation = {}, + }, { .input = {"Route records: counted legs trace on their maps", test_route_records}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp index c396baea98..72d05f3667 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp @@ -191,6 +191,21 @@ std::vector route_203_trainer_sights(){ }; } +std::vector oreburgh_gate_trainer_sights(){ + const auto at = [](const char* name){ + for (const Pokemon::MapObject& object : story_map("OreburghGate").objects){ + if (object.name == name){ + return TilePos{object.x, object.y}; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::string("Oreburgh Gate has no ") + name + "."); + }; + return { + {.name = "Camper Curtis", .pos = at("camper_1"), .facing = Direction::NORTH, .range = 4}, + {.name = "Picnicker Diana", .pos = at("picnicker_0"), .facing = Direction::SOUTH, .range = 2}, + }; +} + // The trainers of the JSON map `map`, in its own tiles. std::vector map_trainers(const std::string& map){ if (map == "Route202"){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index 275717d800..e2a6b89fcf 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -13,6 +13,7 @@ #include "CommonTools/VisualDetectors/BlackScreenDetector.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" #include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" #include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" @@ -46,33 +47,35 @@ namespace{ // and only the quiet after the fade counts: r30's scene went quiet for 5 s // before the fade home, and r28 "went out" a tile beside the door and // walked a whole route in the house. No fade is a map mismatch. -constexpr double FADE_DARKNESS = 40; // brightness 0 to 255; r24's dim fade home goes darker +constexpr double FADE_DARKNESS = 75; // brightness 0 to 255; cave fades reach ~45..64, r24's dim fade goes darker void settle(VideoStream& stream, ProControllerContext& context, Button button, const std::string& label, bool fade){ const WallClock none = WallClock::max(); const WallClock deadline = current_time() + 120s; ShortDialogDetector dialog; OverworldDetector overworld; - WallClock quiet_since = none; - WallClock calm_since = none; // overworld, no text, still or not + BattleMenuDetector battle_menu(BattleType::STANDARD); + WallClock quiet_since = none, calm_since = none; double darkest = 255; VideoSnapshot previous; while (current_time() < deadline){ context.wait_for_all_requests(); const auto frame = stream.video().snapshot(); const WallClock now = current_time(); + if (frame && battle_menu.detect(frame)){ + stream.log("[Story] " + label + ": in wild battle during settle; fleeing."); + run_from_wild_battle(stream, context); + continue; + } if (frame){ darkest = std::min(darkest, image_average(*frame.frame).sum() / 3); } const bool talking = frame && dialog.detect(frame); const bool still = frame && previous && walk_screen_change(*previous.frame, *frame.frame) < WALK_TAP_BLOCKED_CHANGE; previous = frame; - // Cloud shadows drift over Floaroma, so its screen is never still: r83 - // got Mew and then waited out the 120 s on a calm overworld. 15 s of - // overworld with no text is three times r31's silent walk-in. const bool calm = !talking && overworld.detect(frame) && (!fade || darkest < FADE_DARKNESS); calm_since = calm ? (calm_since == none ? now : calm_since) : none; if (calm && now - calm_since >= 15000ms){ - stream.log(std::format("[Story] {}: settled on 15 s of overworld without text (the screen kept moving); darkest frame {:.0f}.", label, darkest)); + stream.log(std::format("[Story] {}: settled on calm overworld; darkest frame {:.0f}.", label, darkest)); return; } if (!talking && still && overworld.detect(frame) && (!fade || darkest < FADE_DARKNESS)){ @@ -95,9 +98,8 @@ void settle(VideoStream& stream, ProControllerContext& context, Button button, c // Holds the D-pad toward a door (with B after the shoes) until the screen goes // dark or a line shows, up to 12 s. Returns whether it went dark. A line -// stops it: holding on under Mom's "Oh, Kosmos!" wasted 12 s (r45). The walker's black-screen watch -// missed the lab's fade into Sandgem (r44, "dialog"), and settle's samples -// 1.3 s apart can fall either side of it, so watch at settle's own darkness. +// stops it: holding on under Mom's "Oh, Kosmos!" wasted 12 s (r45). A wild +// battle in a cave corridor runs away before returning. DpadPosition dpad_toward(Direction direction){ return direction == Direction::NORTH ? DPAD_UP : @@ -109,12 +111,18 @@ bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction const DpadPosition dpad = dpad_toward(direction); BlackScreenWatcher dark(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, 3 * FADE_DARKNESS, 60); ShortDialogWatcher dialog(COLOR_YELLOW); + BattleMenuWatcher battle(BattleType::STANDARD, COLOR_YELLOW); const int ret = run_until(stream, context, [&](ProControllerContext& context){ if (run){ ssf_press_button(context, BUTTON_B, 0ms, 12000ms, 0ms); } pbf_press_dpad(context, dpad, 12000ms, 0ms); - }, {{dark}, {dialog}}); + }, {{dark}, {dialog}, {battle}}); + if (ret == 2){ + stream.log("[Story] run_into_door: wild battle; fleeing."); + run_from_wild_battle(stream, context); + return false; + } return ret == 0; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 187f76fac4..7236bf15d7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -164,6 +164,14 @@ StoryStep tap_into(std::string name, Direction direction, std::string why, Pose step.variant = "to_banner"; return step; } +// Through a door or cave warp by a single D-pad tap onto the warp tile, +// settling on the far map without holding/running (which overshoots if the +// fade is missed or delayed). +StoryStep tap_step(std::string name, Direction direction, std::string why, Pose pose_after){ + StoryStep step = step_into(std::move(name), direction, std::move(why), std::move(pose_after)); + step.variant = "tap"; + return step; +} StoryStep talk(std::string name, std::string why){ return make(StoryStepKind::TALK, std::move(name), std::move(why)); } @@ -224,13 +232,13 @@ std::vector route_201_to_the_lakefront(){ // Barry's warning covers the whole exit path (14..19, 18), so it ends our walk // north: exact legs to the row below it, never a run to a wall through it (r14 // ran north to (15, 13) and back, into it and the row-19 pull-back, in a loop). - legs("below_barrys_warning", {{.direction = EAST, .tiles = 6}, {.direction = NORTH, .tiles = 18}}, - "along row 12, then up Twinleaf's exit to Route 201 (15, 19)"), + anchored(legs("below_barrys_warning", {{.direction = EAST, .tiles = 6}, {.direction = NORTH, .tiles = 18}}, + "along row 12, then up Twinleaf's exit to Route 201 (15, 19)"), at(ROUTE_201, 15, 19, NORTH)), step_into("barrys_warning", NORTH, "the trigger (14..19, 18)"), scene("barry_warns_us", at(ROUTE_201, "barry_warning"), "Barry's tall-grass warning; he then stands north of us at (15, 17)"), // West at once, never back south onto row 19, which pulls us back. - legs("away_from_barry", {{.direction = WEST, .tiles = 1}, {.direction = NORTH, .tiles = 1}, {.direction = WEST, .tiles = 2}}, - "to (12, 17): row 18 west of the path is trees (r16), the dirt goes on along row 17"), + legs("away_from_barry", {{.direction = WEST, .tiles = 1}, {.direction = NORTH, .tiles = 2}}, + "to (14, 16): row 18 west of the path is trees (r16) and (13, 17) is the 201 sign (probe-r201-sign), so clear both onto row 16"), // Route 201's lower level, row 16, clear of the grass, then the Lakefront. route("below_the_lake_entrance", at(LAKEFRONT, "below_lake_entrance", NORTH), "west along Route 201's lower level to the Lakefront"), }; @@ -253,17 +261,19 @@ StoryCheckpoint bedroom_to_lakefront(){ scene("mom_calls", at_or_next_to(HOME, "stairs", SOUTH), "Mom calls the player over as they come down; we stay put"), route("above_the_door", at(HOME, 6, 9, SOUTH), "past Mom at (7, 8) to above the door"), - step_into("mom_warning", SOUTH, "the door's tile (6, 10): Mom's warning (coord event, VAR_PLAYER_HOUSE_STATE 1)"), - scene("mom_warns_us", at(HOME, "door", SOUTH), "\"don't go into the tall grass\""), - step_into("out_of_the_house", SOUTH, "out of the door", at(TWINLEAF, "house_doorstep", SOUTH)), + // In BDSP Mom's downstairs scene already warned us about the tall grass, + // so the door's tile (6, 10) warps right out without Platinum's coord event. + step_into("out_of_the_house", SOUTH, "onto the door's tile (6, 10), and out", at(TWINLEAF, "house_doorstep", SOUTH)), route("short_of_barrys_door", at(TWINLEAF, 10, 12, WEST), "a tile east of Barry's doorstep"), step_into("barrys_door", WEST, "the trigger on his doorstep (9, 12)"), // Barry bumps into us and knocks us back a tile, still facing north (decomp; // r10: the first north tap after the scene gave no warp, the second did). scene("barry_bursts_out", at(TWINLEAF, 9, 13, NORTH), "Barry runs out, bumps into us and runs back in", "a"), scene("barry_goes_home", at(TWINLEAF, 9, 13, NORTH), "his second lines (Butters waited for two)", "a"), - legs("back_onto_barrys_doorstep", {{.direction = NORTH, .tiles = 1}}, "back to (9, 12); its trigger is spent"), - step_into("into_barrys_house", NORTH, "his door", at(BARRYS_HOUSE, "door", NORTH)), + // From (9, 13) straight north through (9, 12) (its trigger is spent) into + // his door: a separate tap to (9, 12) first stepped into the door before + // into_barrys_house watched for the fade. + step_into("into_barrys_house", NORTH, "past (9, 12) into his door", at(BARRYS_HOUSE, "door", NORTH)), legs("off_barrys_mat", {{.direction = NORTH, .tiles = 1}}, "off the door's mat, which no route starts on"), // Like ours: stairs are entered sideways from the top of their mat, the // stairs point (r11: north from (2, 4) only bumps the wall). @@ -339,7 +349,7 @@ std::vector lake_and_pokedex(){ // B answers No too, and closes an item's lines as it did Barry's // parcel (r45). Into the lab is a fade. scene("rowan_gives_pokedex", at(LAB, "rowan_talk", NORTH), - "Dawn walks us to the lab: Rowan, no nickname, the Pokedex"), + "Dawn walks us to the lab: Rowan, no nickname, the Pokedex", "a"), }), }; } @@ -365,46 +375,49 @@ StoryStep out_of_the_lab_into_dawns_tour(){ }, NORTH)); } -// Anywhere in the door's column: the step runs north into the door, so the -// route can end where the south run along x 14 stops (row 26) and go east. -StoryStep home_to_the_doors_column(){ - return route("home", Pokemon::tile_pose(TWINLEAF, { - TilePos{20, 22}, TilePos{20, 23}, TilePos{20, 24}, TilePos{20, 25}, TilePos{20, 26} - }, NORTH), "west along Route 201 to Twinleaf, running from wild battles"); +// West along Route 201 to Mom's doorstep: +// 1. Over the ledge at column 57 down onto Route 201's main road (row 14). +// 2. West along the main road (row 14) to the Twinleaf path at column 15. +// 3. South down column 15 into Twinleaf Town to row 22. +// 4. East to Mom's house doorstep at (20, 22), facing north into the door. +std::vector home_to_the_doors_column(){ + return { + route("to_ledge_column", at(ROUTE_201, 55, 5, WEST), "west to ledge column 55", "line"), + anchored(legs("over_the_ledge", {{.direction = SOUTH, .tiles = 8}}, "south over the ledge to the lower road"), + at(ROUTE_201, 55, 14, SOUTH)), + route("along_route_201_road", at(ROUTE_201, 15, 14, WEST), "west along Route 201's road to the Twinleaf path", "line"), + route("into_twinleaf", at(TWINLEAF, 15, 22, SOUTH), "south down column 15 into Twinleaf Town", "line"), + route("to_moms_doorstep", at(TWINLEAF, 20, 22, NORTH), "east to Mom's house doorstep", "line"), + }; } std::vector to_the_catch(){ + std::vector steps{ + out_of_the_lab_into_dawns_tour(), + // Not west along the doors' row: running it took us into the lab at its + // mat (8, 11) (r41, r42). Row 12 is open into Route 201: run it until + // Route 201's banner shows, a few tiles in. + route("onto_the_path", at(SANDGEM, 29, 12, WEST), "to the east end of the path below the doors' row", "town"), + route_201_by_the_path(), + }; + for (StoryStep& s : home_to_the_doors_column()){ + steps.push_back(std::move(s)); + } + steps.push_back(step_into("into_the_house", NORTH, "the house's door", at(HOME, 6, 9, NORTH))); + steps.push_back(route("beside_mom", at(HOME, 6, 8, EAST), "west of Mom at (7, 8)")); + steps.push_back(talk("mom", "Mom")); + steps.push_back(scene("mom_heals_us", at(HOME, 7, 7, SOUTH), "Mom heals us; Barry's mom gives us his parcel")); + steps.push_back(legs("around_mom", {{.direction = WEST, .tiles = 1}, {.direction = SOUTH, .tiles = 2}}, + "around Mom to (6, 9) above the door")); + steps.push_back(step_into("to_moms_call", SOUTH, "onto the door mat (6, 10), triggering Mom's call")); + steps.push_back(scene("moms_hat", at(TWINLEAF, 19, 22, EAST), "Mom's hat; she walks out with us")); + steps.push_back(route("short_of_the_catch_tutorial", at(ROUTE_202, 22, 27, WEST), "through Sandgem onto Route 202, east of its trigger column")); + steps.push_back(step_into("catch_tutorial_trigger", WEST, "the trigger (21, 25..29), VAR_ROUTE_202_STATE 0")); + steps.push_back(event("catch_tutorial", "Dawn's catching tutorial")); + steps.push_back(event("catch_pokemon", "a Pokemon of our own from the grass", on(ROUTE_202, "catch_save_area"))); + return { - row("00.04", "Home to Mom, then Dawn's catching tutorial on Route 202", at(LAB, "rowan_talk", NORTH), { - out_of_the_lab_into_dawns_tour(), - // Not west along the doors' row: running it took us into the lab at its - // mat (8, 11) (r41, r42). Row 12 is open into Route 201: run it until - // Route 201's banner shows, a few tiles in. - route("onto_the_path", at(SANDGEM, 29, 12, WEST), "to the east end of the path below the doors' row", "town"), - route_201_by_the_path(), - home_to_the_doors_column(), - // The game sets us a tile inside, off the mat: (6, 9) (r40: the old extra - // step north put us beside the TV, above Mom). - step_into("into_the_house", NORTH, "the house's door", at(HOME, 6, 9, NORTH)), - // Mom stands at (7, 7) now, a row above the decomp's (7, 8): from (6, 8) - // she was up and to the right; a tap north, east and A answered (r43). - route("beside_mom", at(HOME, 6, 7, EAST), "west of Mom at (7, 7)"), - talk("mom", "Mom"), - // Mom heals us, then Barry's mom comes in with his parcel; the scene - // leaves Mom at (6, 8), below us (r45). - scene("mom_heals_us", at(HOME, 6, 7, EAST), "Mom heals us; Barry's mom gives us his parcel"), - legs("around_mom", {{.direction = WEST, .tiles = 1}, {.direction = SOUTH, .tiles = 2}}, - "around Mom at (6, 8), to beside the door's column"), - // Stepping onto (6, 9), above the door, Mom calls us back ("Oh, Kosmos!", - // r46), gives us the hat and walks out with us; we end a tile west of the - // doorstep, beside her (r45). - legs("to_moms_call", {{.direction = EAST, .tiles = 1}}, "east above the door until Mom calls", "to_dialogue"), - scene("moms_hat", at(TWINLEAF, 19, 22, EAST), "Mom's hat; she walks out with us"), - route("short_of_the_catch_tutorial", at(ROUTE_202, 22, 27, WEST), "through Sandgem onto Route 202, east of its trigger column"), - step_into("catch_tutorial_trigger", WEST, "the trigger (21, 25..29), VAR_ROUTE_202_STATE 0"), - event("catch_tutorial", "Dawn's catching tutorial"), - event("catch_pokemon", "a Pokemon of our own from the grass", on(ROUTE_202, "catch_save_area")), - }), + row("00.04", "Home to Mom, then Dawn's catching tutorial on Route 202", at(LAB, "rowan_talk", NORTH), std::move(steps)), // A Lv5 starter fainted to Route 202's trainers (r72): training, a // heal, and Potions first, each row from the save the one before ends on. row("00.04b", "After the catch: train and heal in Sandgem", on(ROUTE_202, "catch_save_area"), { @@ -445,7 +458,7 @@ std::vector to_jubilife(){ "Jubilife's south edge is a wall with stairs in it, west of where the route may leave us (r78)", below_jubilifes_steps()); return { - row("00.04c", "Potions, back to Route 202's save spot", door_front(SANDGEM, "pokemon_center_door"), { + row("00.04c", "Poke Mart lady for Potions, back to Route 202's save spot", door_front(SANDGEM, "pokemon_center_door"), { potions, }), // From the one save spot: from both at once the planner gives up. @@ -531,15 +544,17 @@ StoryCheckpoint the_coupons(){ // and is gone (decomp); then up to the street east to Route 203, where // 01.01 walks east until Barry stops us. StoryCheckpoint the_poketch(){ - const Pose below_the_president = next_to(JUBILIFE, "poketch_president", SOUTH, NORTH); + const Pose beside_the_president = next_to(JUBILIFE, "poketch_president", WEST, EAST); return row("00.05c", "Jubilife: the Poketch, up to the street east to Route 203", next_to(JUBILIFE, "clown_poketch_company", SOUTH, NORTH), { - route("below_the_president", below_the_president, "east along the long road, down the main road", "town"), - talk("president", "the Poketch Company's president at (46, 35)"), + route("to_main_boulevard", at(JUBILIFE, 15, 22, SOUTH), "south to the main boulevard", "line"), + route("along_main_boulevard", at(JUBILIFE, 45, 22, SOUTH), "east along the main boulevard", "line"), + route("beside_the_president", beside_the_president, "south down column 45 to the Poketch president", "line"), + talk("president", "the Poketch Company's president at (46, 36)"), // BDSP adds a help panel on the Poketch; B closes it. - scene("the_poketch", below_the_president, "the coupons for the Poketch; he walks off north"), + scene("the_poketch", beside_the_president, "the coupons for the Poketch; he walks off north"), // The street's rows 21 to 24 lead onto Route 203 at x 63. - route("to_the_route_203_street", at(JUBILIFE, 58, 22, EAST), "up the main road and east along the street", "town"), + route("to_the_route_203_street", at(JUBILIFE, 58, 22, EAST), "up the main road and east along the street", "line"), }); } @@ -573,14 +588,15 @@ Pose into_the_ravaged_path(){ return at(RAVAGED_PATH, "entrance", NORTH); } -// Where Oreburgh's welcome scene leaves us, Barry in the Center's door: "a row -// or two below the Center's front, a little west of its door" (01.03's -// save, 2026-10-29); "two tiles west of the door and a row down" (the old -// event). Not Diamond's: its man walks us to the Gym, (23, 23). +// Where Oreburgh's welcome scene leaves us, Barry in the Gym's door. +// In Diamond/Pearl/BDSP, the guide walks us to the Gym: (23, 23) facing east, +// with the guide himself standing directly east at (24, 23). Pose after_the_welcome(){ - return Pokemon::tile_pose(OREBURGH, { - TilePos{43, 21}, TilePos{44, 21}, TilePos{45, 21}, TilePos{43, 22}, TilePos{44, 22}, TilePos{45, 22} - }); + return at(OREBURGH, 23, 23, EAST); +} +// Below Oreburgh's Gym door (26, 20), facing Barry on the doorstep (26, 21). +Pose below_barry(){ + return at(OREBURGH, 26, 22, NORTH); } // Below Oreburgh's Pokemon Center's door (47, 20), facing it. Pose below_oreburghs_center(){ @@ -657,7 +673,7 @@ StoryCheckpoint route_203_to_oreburgh(){ step_into("welcome_trigger", EAST, "the trigger (10, 12..15): the man walks over"), // He walks us to the Pokemon Center between his lines; Barry joins // there with more lines after each walk. - scene("oreburgh_welcome", after_the_welcome(), "the man's lines, the walk to the Center, and Barry's"), + scene("oreburgh_welcome", after_the_welcome(), "the man's lines, the walk to the Gym, and Barry's"), }); } @@ -681,40 +697,54 @@ StoryCheckpoint route_203_to_oreburgh(){ // from the city's (46, 59) we land on its (12, 1); up, from the coal // room's warp we land on its (11, 21) and come out on the city's (45, 59), // below the mine's sign (the old walk north stopped against it, r103). +std::vector legs_below_roark(){ + return { + {.direction = EAST, .tiles = 1}, + {.direction = SOUTH, .tiles = 2}, + {.direction = WEST, .tiles = 1}, + {.direction = SOUTH, .tiles = 5}, + {.direction = EAST, .tiles = 14}, + {.direction = SOUTH, .tiles = 10}, + {.direction = WEST, .tiles = 2}, + {.direction = SOUTH, .tiles = 2}, + {.direction = WEST, .tiles = 9}, + }; +} + +std::vector legs_out_of_coal_room(){ + return { + {.direction = EAST, .tiles = 9}, + {.direction = NORTH, .tiles = 2}, + {.direction = EAST, .tiles = 2}, + {.direction = NORTH, .tiles = 10}, + {.direction = WEST, .tiles = 14}, + {.direction = NORTH, .tiles = 5}, + {.direction = EAST, .tiles = 1}, + {.direction = NORTH, .tiles = 2}, + {.direction = WEST, .tiles = 1}, + {.direction = NORTH, .tiles = 8}, + }; +} + StoryCheckpoint oreburgh_mine_to_roark(){ const Pose below_roark = next_to(MINE, "roark", SOUTH, NORTH); return row("01.03", "Oreburgh Mine to Roark", after_the_welcome(), { - // The fence south of the Center's east corner (column 49) stops a - // walk east on these rows a tile east of the door, as by hand. - anchored(to_walls("to_the_centers_fence", {{.direction = EAST, .tiles = 6}, {.direction = NORTH, .tiles = 2}}, - "east to the fence below the Center's east corner, north to the Center's front"), at(OREBURGH, 48, 21, NORTH)), - anchored(legs("below_the_centers_door", {{.direction = WEST, .tiles = 1}}, "a tap west below the door"), - below_oreburghs_center()), - // He stands in the door the first time; walking into him reads as a wall. - talk("barry", "Barry in the Center's door"), - scene("barrys_lines", below_oreburghs_center(), "Roark has gone to the mine"), - // The Hiker wanders (46..48, 25..27), in the door's column: the - // route goes round him. + anchored(legs("below_barry", {{.direction = SOUTH, .tiles = 1}, {.direction = EAST, .tiles = 3}, {.direction = NORTH, .tiles = 2}}, + "south 1 around the guide, east 3 to Barry's column, north 2 to below Barry"), below_barry()), + talk("barry", "Barry in the Gym's door"), + scene("barrys_lines", below_barry(), "Roark has gone to the mine"), route("above_the_mine", at(OREBURGH, 46, 58, SOUTH), "down the door's column to above the mine's warp tiles", "town"), step_into("into_the_mine", SOUTH, "the warp tile (46, 59)", at(MINE_HALL, 12, 1, SOUTH)), - // We land on the warp tile we came by, (12, 1): 19 taps end on row - // 20, a step short of the warp row. - legs("down_the_hall", {{.direction = SOUTH, .tiles = 19}}, "down column 12 of the entrance hall"), - step_into("into_the_coal_room", SOUTH, "the hall's warp tiles (11..13, 21)", - Pokemon::tile_pose(MINE, {TilePos{15, 2}, TilePos{15, 1}}, SOUTH)), - // One known tile to plan from: the corridor's column 15 ends at the - // boulder (15, 10), where the old walk south stopped too. - anchored(to_walls("down_to_the_boulder", {{.direction = SOUTH, .tiles = 9}}, "down the corridor to the boulder (15, 10)"), - at(MINE, 15, 9, SOUTH)), - route("below_roark", below_roark, "down the corridor and the room's east side, west along the bottom row"), - // His first line comes after the camera zooms in on us (r98); his - // rocks either side answer A too, but he is the one north of us. + step_into("into_the_coal_room", SOUTH, "down the entrance hall through the cave mouth", at(MINE, 15, 2, SOUTH)), + anchored(to_walls("south_to_the_rock", {{.direction = SOUTH, .tiles = 8}}, "south against the corridor rock (15, 11)"), + at(MINE, 15, 10, SOUTH)), + anchored(legs("below_roark", legs_below_roark(), "east around rock, across room, down column 29, and west to below Roark"), below_roark), talk("roark", "Roark, north of us between his rocks"), scene("roark_smashes_the_rock", below_roark, "his lines, Rock Smash on the rock east of him, and he walks off"), - route("below_the_coal_rooms_warp", at(MINE, 15, 2, NORTH), "back up the corridor"), + anchored(legs("below_the_coal_rooms_warp", legs_out_of_coal_room(), "east around crate, up column 29, west across row 17, and up corridor to warp doorstep"), + at(MINE, 15, 2, NORTH)), step_into("up_to_the_hall", NORTH, "the warp tile (15, 1)", at(MINE_HALL, 11, 21, NORTH)), - legs("up_the_hall", {{.direction = NORTH, .tiles = 19}}, "up column 11 of the entrance hall"), - step_into("out_of_the_mine", NORTH, "the hall's warp tiles (11..13, 1)", + step_into("out_of_the_mine", NORTH, "up the entrance hall and out to the city", Pokemon::tile_pose(OREBURGH, {TilePos{45, 59}, TilePos{45, 58}}, NORTH)), anchored(to_walls("up_to_the_mines_sign", {{.direction = NORTH, .tiles = 3}}, "north against the mine's sign (45, 56)"), at(OREBURGH, 45, 57, NORTH)), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index 832133141f..c914e56cb8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -39,7 +39,7 @@ const std::map>& built_in_variants(){ static const std::map> variants{ {StoryStepKind::ROUTE, {"", "town", "robust", "line"}}, {StoryStepKind::LEGS, {"", "one_short_ok", "to_wall", "to_dialogue", "to_map"}}, - {StoryStepKind::STEP, {"", "to_banner"}}, + {StoryStepKind::STEP, {"", "to_banner", "tap"}}, {StoryStepKind::MASH, {"", "a"}}, {StoryStepKind::BATTLE, {"", "doubles", "starter"}}, }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index 067a6281af..d39b0198cf 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -9,6 +9,7 @@ #include "Common/Cpp/Color.h" #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP_AutoStory_StoryExecutor.h" @@ -117,12 +118,16 @@ Outcome StoryWalkSteps::leg_to_dialogue(const StoryStep& step){ const Pokemon::StoryLeg& leg = step.legs.front(); turn(leg.direction); const WalkResult walk = m_io.route().walk_taps(leg.direction, (size_t)leg.tiles, step.name); + if (walk.wild_battles > 0){ + return Pokemon::outcome_failed("interrupted_dialogue_approach", step.name); + } log(std::format("[{}] {}: taps {} to a dialogue: {} tiles, {}.", m_row, step.name, direction_name(leg.direction), walk.moved_chunks, walk_stop_name(walk.stop))); if (walk.stop == WalkStop::DIALOG){ return Pokemon::outcome_ok(); } - // A scene can lock us before its first line: Dawn walks over first (r37). - if (walk.stop == WalkStop::BLOCKED && m_io.route().dialog_within(10000ms, COLOR_CYAN)){ + // A scene can lock us before its first line: Dawn walks over first (r37), + // or Mom walks over to us on the mat (r7). + if (m_io.route().dialog_within(10000ms, COLOR_CYAN)){ return Pokemon::outcome_ok(); } return Pokemon::outcome_failed("no_dialogue", step.name); @@ -152,33 +157,76 @@ Outcome StoryWalkSteps::tap_to_banner(const StoryStep& step){ return Pokemon::outcome_ok(); } -// Each leg in D-pad taps, turning first; "one_short_ok" lets a leg end a -// tile short. +namespace{ +enum class CountedEndPolicy{ EXACT, ONE_SHORT }; +std::vector counted_ends(const std::vector& starts, const Pokemon::StoryLeg& leg, CountedEndPolicy policy){ + std::vector ends; + for (TilePos at : starts){ + for (int i = 0; i < leg.tiles; i++){ + if (policy == CountedEndPolicy::ONE_SHORT && i + 1 == leg.tiles){ + ends.push_back(at); + } + at = at.next(leg.direction); + } + ends.push_back(at); + } + return ends; +} +} // namespace + +Pose StoryWalkSteps::recover_tapped_leg(const Pose& from, const std::vector& starts, + const std::vector& goals, const Pokemon::StoryLeg& leg, const StoryStep& step){ + const StoryWorld* world = story_plan_world(from.map, from.map); + if (world == nullptr){ + fail(m_io.route(), "interrupted leg has no recovery world: " + from.map); + } + std::vector global; + for (const TilePos& at : starts){ + global.push_back(story_to_world(*world, from.map, at)); + } + std::vector possible; + for (const TilePos& at : interrupted_leg_positions(*world, global, leg.direction, (size_t)leg.tiles)){ + const auto local = story_to_local(*world, from.map, at); + if (!local){ + fail(m_io.route(), "interrupted leg crossed an unconfirmed map transition"); + } + possible.push_back(*local); + } + StoryStep recovery = step; + recovery.name += "_recovery"; + recovery.variant.clear(); + const Pose found = walk_to(Pokemon::tile_pose(from.map, possible), Pokemon::tile_pose(from.map, goals, leg.direction), recovery); + // The route back can approach from another direction. Establish the + // original leg's facing before publishing that pose to the story runner. + turn(leg.direction); + return found; +} + +// Counted legs retain their normal path. An observed encounter invalidates +// the exact pose; localize from every legal prefix before the next leg. Outcome StoryWalkSteps::tap_legs(const Pose& from, const StoryStep& step){ const bool one_short_ok = step.variant == "one_short_ok"; std::vector at = Pokemon::tiles_of(from); for (const Pokemon::StoryLeg& leg : step.legs){ - // Facing another way, a tap only turns (r256): turn first. turn(leg.direction); const size_t tiles = (size_t)leg.tiles; const WalkResult walk = m_io.route().walk_taps(leg.direction, tiles, step.name); log(std::format("[{}] {}: taps {} moved {} of {} tiles.", m_row, step.name, direction_name(leg.direction), walk.moved_chunks, tiles)); + const auto next = counted_ends(at, leg, one_short_ok ? CountedEndPolicy::ONE_SHORT : CountedEndPolicy::EXACT); + if (walk.wild_battles > 0){ + if (walk.origin == WalkOrigin::MAY_PRECEDE_LEG){ + return Pokemon::outcome_failed("encounter_origin_unknown", step.name); + } + if (walk.stop != WalkStop::LIMIT && walk.stop != WalkStop::BLOCKED){ + return Pokemon::outcome_failed("interrupted_leg_unconfirmed", step.name); + } + at = Pokemon::tiles_of(recover_tapped_leg(from, at, next, leg, step)); + continue; + } if (walk.moved_chunks + (one_short_ok ? 1 : 0) < tiles){ return Pokemon::outcome_failed("short_leg", std::format("{} {} moved {}", direction_name(leg.direction), tiles, walk.moved_chunks)); } - // Where we may be: the end, or a tile short of it. - std::vector next; - for (const TilePos& start : at){ - TilePos end = start; - for (size_t i = 0; i < tiles; i++){ - if (one_short_ok && i + 1 == tiles){ - next.push_back(end); - } - end = end.next(leg.direction); - } - next.push_back(end); - } - at = std::move(next); + at = next; } return Pokemon::outcome_ok(Pokemon::tile_pose(from.map, at, step.legs.back().direction)); } @@ -203,22 +251,37 @@ Outcome StoryWalkSteps::legs(RunState& state, const StoryStep& step){ } Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ - turn(step.direction); if (step.variant == "to_banner"){ + turn(step.direction); return tap_to_banner(step); } + if (step.variant == "tap"){ + // No separate turn tap first: at 1 tile from the door, a turn tap + // steps onto the warp, causing walk_taps to take an extra step on the far map. + const WalkResult walk = m_io.route().walk_taps(step.direction, 1, step.name); + if (walk.wild_battles > 0){ + return Pokemon::outcome_failed("interrupted_step", step.name); + } + m_io.settle(BUTTON_B, label_of(step), false); + return Pokemon::outcome_ok(); + } // A step through a door: walk (or run) on until the screen goes dark, // from next to the door or from anywhere in its line (r43: tapping 8 tiles // down the lab took 7 s), then settle for any scene on arrival (Mom's, // 00.01; Dawn's tour, 00.04). Without the fade, settle must see it itself - // (r33 was outside, "no fade"). + // (r33 was outside, "no fade"). No separate turn tap first: at 1 tile + // from the door, a 50 ms turn tap can step in before run_into_door() watches. if (step.pose_after && step.pose_after->map != state.pose.map){ const bool faded = m_io.run_into_door(step.direction, m_can_run); log(std::format("[{}] {}: {} through the door: {}.", m_row, step.name, direction_name(step.direction), faded ? "faded" : "no fade yet")); m_io.settle(BUTTON_B, label_of(step), !faded); return Pokemon::outcome_ok(); } + turn(step.direction); const WalkResult walk = m_io.route().walk_taps(step.direction, 1, step.name); + if (walk.wild_battles > 0){ + return Pokemon::outcome_failed("interrupted_step", step.name); + } log(std::format("[{}] {}: a step {}, {}.", m_row, step.name, direction_name(step.direction), walk_stop_name(walk.stop))); std::vector at; for (const TilePos& pos : Pokemon::tiles_of(state.pose)){ @@ -250,7 +313,8 @@ Outcome StoryWalkSteps::mash(RunState& state, const StoryStep& step){ m_io.route().note(label_of(step) + ": no line within 15 s; the step before played it.", RouteNote::WARNING); } m_io.settle(step.variant == "a" ? BUTTON_A : BUTTON_B, label_of(step), - step.pose_after && step.pose_after->map != state.pose.map); + step.pose_after && step.pose_after->map != state.pose.map && + story_plan_world(state.pose.map, step.pose_after->map) == nullptr); if (m_row == RUNNING_SHOES_ROW && step.name == RUNNING_SHOES_STEP){ m_can_run = true; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index fa89abaf14..c5b7493e78 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -51,6 +51,9 @@ class StoryWalkSteps{ private: Pokemon::Pose walk_to(const Pokemon::Pose& from, const Pokemon::Pose& goal, const Pokemon::StoryStep& step); + Pokemon::Pose recover_tapped_leg(const Pokemon::Pose& from, + const std::vector& starts, const std::vector& goals, + const Pokemon::StoryLeg& leg, const Pokemon::StoryStep& step); Pokemon::Outcome tap_legs(const Pokemon::Pose& from, const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_dialogue(const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_map(const Pokemon::StoryStep& step); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp index fd90d56444..5a7be14d15 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -136,8 +136,11 @@ std::optional GridSim::enter_next(Direction direction, int part, int& m part = 2 * SIM_TILE; }else if (!landing && (is_door(world, ahead[0]) || std::find(m_world.doors.begin(), m_world.doors.end(), ahead[0]) != m_world.doors.end())){ m_player.pos = sim_pos(ahead[0]); - m_player.warped = ahead[0]; moved += SIM_TILE; + if (const std::optional stop = arrive()){ + return stop; + } + m_player.warped = ahead[0]; return SimStop::WARP; }else if (!landing){ return SimStop::BLOCKED; @@ -183,6 +186,7 @@ SimMove GridSim::advance(Direction direction, int distance){ if (m_player.dialog){ return {.stop = SimStop::DIALOG}; } + m_player.warped.reset(); int moved = 0; while (moved < distance){ const int offset = along(m_player.pos, direction) % SIM_TILE; @@ -300,14 +304,42 @@ WalkResult GridSimRouteIO::walk_to_wall(const RouteWallWalk& walk){ return {.stop = walk_stop(move.stop), .walked = move.time, .wild_battles = 0, .moved_chunks = (size_t)(move.distance / SIM_TILE)}; } +std::optional GridSimRouteIO::take_encounter(Direction direction, size_t tiles, size_t tap, const std::string& label){ + const auto found = std::find_if(m_encounters.begin(), m_encounters.end(), [&](const SimWildTap& encounter){ + return encounter.direction == direction && encounter.requested_tiles == tiles + && encounter.tap == tap && encounter.label == label; + }); + if (found == m_encounters.end()){ + return std::nullopt; + } + SimWildTap encounter = *found; + m_encounters.erase(found); + return encounter; +} + // A tap a tile, as walk_tiles_dpad() taps: two taps in a row that move // nothing end the walk. WalkResult GridSimRouteIO::walk_taps(Direction direction, size_t tiles, const std::string& label){ WalkResult result{.stop = WalkStop::LIMIT, .walked = 0ms, .wild_battles = 0, .moved_chunks = 0}; size_t still = 0; for (size_t tap = 0; tap < tiles && result.stop == WalkStop::LIMIT; tap++){ - const SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + const auto encounter = take_encounter(direction, tiles, tap + 1, label); + const SimMove move = encounter && encounter->phase == SimEncounterPhase::BEFORE_MOVEMENT + ? SimMove{} : m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); result.walked += 800ms; + if (encounter){ + // Match the production escape_battle() credit, independently + // of actual simulated displacement. Consumers must not infer + // pose solely from this credit after an interrupted input. + result.wild_battles++; + if (tap == 0 || encounter->origin == WalkOrigin::MAY_PRECEDE_LEG){ + result.origin = WalkOrigin::MAY_PRECEDE_LEG; + } + result.moved_chunks++; + still = 0; + m_notes.push_back("[Sim] cleared wild encounter during " + label); + continue; + } still = move.distance > 0 ? 0 : still + 1; result.moved_chunks += move.distance > 0 ? 1 : 0; if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h index 727aac0518..d79ea9e595 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h @@ -26,6 +26,7 @@ #include #include +#include #include #include "Common/Cpp/Time.h" #include "Pokemon/Navigation/Pokemon_Grid.h" @@ -155,13 +156,28 @@ class GridSim{ bool sim_can_step(const GridSim& sim, Pokemon::Direction direction); +// A deterministic, already-cleared encounter at a tap boundary. This is +// normalized movement/escape evidence, not a model of image detectors or +// battle mechanics. BEFORE leaves the tile unchanged; AFTER completes it. +enum class SimEncounterPhase{ BEFORE_MOVEMENT, AFTER_MOVEMENT }; +// Match one tap and supply its cleared encounter phase and origin evidence. +struct SimWildTap{ + std::string label; + Pokemon::Direction direction = Pokemon::Direction::NORTH; + size_t requested_tiles = 0; + size_t tap = 0; // one-based within the matching walk_taps call + SimEncounterPhase phase = SimEncounterPhase::AFTER_MOVEMENT; + WalkOrigin origin = WalkOrigin::CURRENT_LEG; +}; + // The walker's RouteIO on a GridSim. A failure throws GridSimFailure. class GridSimRouteIO : public RouteIO{ public: // Every line noted goes to `notes`, which must outlive this. - GridSimRouteIO(GridSim& sim, std::vector& notes) + GridSimRouteIO(GridSim& sim, std::vector& notes, std::vector encounters = {}) : m_sim(sim) , m_notes(notes) + , m_encounters(std::move(encounters)) {} virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override; @@ -173,8 +189,11 @@ class GridSimRouteIO : public RouteIO{ virtual void note(const std::string& text, RouteNote kind) override; private: + std::optional take_encounter(Pokemon::Direction direction, size_t tiles, size_t tap, const std::string& label); + GridSim& m_sim; std::vector& m_notes; + std::vector m_encounters; }; // What GridSimRouteIO throws for RouteNote::FAILURE. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 4215dd977e..590755af5b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -54,7 +54,6 @@ namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonBDSP{ - namespace{ using namespace std::chrono_literals; @@ -66,7 +65,6 @@ using Pokemon::StoryStep; using Pokemon::StoryStepKind; using Pokemon::TilePos; - // Which detections the simulation misses on purpose (#162): the `fade`th // door fade (run_into_door(), from 0) or the `banner`th map banner // (run_until_map()) of the run goes unseen, though the player did go @@ -146,7 +144,8 @@ class SimStoryStepIO : public StoryStepIO{ // A fade missed on the way in stays missed: it was over before settle() // looked, which then fails as it does on the console after 120 s. virtual void settle(Button, const std::string& label, bool fade) override{ - if (fade && ((!m_sim.player().warped && !m_sim.player().dialog) || m_misses.fade_unseen)){ + const bool scene_fades = m_sim.player().dialog && m_far_side(); + if (fade && ((!m_sim.player().warped && !scene_fades) || m_misses.fade_unseen)){ m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); } m_misses.fade_unseen = false; @@ -238,7 +237,6 @@ std::optional SimStoryStepIO::tap_to_banner(Direction direction, const s return std::nullopt; } - // A scene's trigger the simulation fires from row `row` on, once the step // `after` has run ("" from the row's start), on `map`'s `tiles`. struct RowTrigger{ @@ -273,7 +271,6 @@ struct VarState{ std::vector story_vars(){ return { {.var = "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", .value = 0, .row = "00.01", .after = ""}, - {.var = "VAR_PLAYER_HOUSE_STATE", .value = 1, .row = "00.01", .after = ""}, {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 0, .row = "00.01", .after = ""}, {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 1, .row = "00.01", .after = "barry_warns_us"}, {.var = "VAR_VERITY_LAKEFRONT_STATE", .value = 0, .row = "00.02", .after = ""}, @@ -317,7 +314,6 @@ std::vector story_triggers(){ return triggers; } - // Someone the maps do not have, who stands on `tile` of `map` and is // talked to there or walked round: from row `row` on if `until` is "", // else in `row` until its step `until` has run. @@ -332,9 +328,9 @@ std::vector sim_people(){ return { // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04", .until = ""}, - // Barry stands in the Center's door until his lines (01.03; Roark + // Barry stands in the Gym's door until his lines (01.03; Roark // ignored A until then, r101 and r104). - {.name = "barry", .map = "OreburghCity", .tile = {47, 20}, .row = "01.03", .until = "barrys_lines"}, + {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.03", .until = "barrys_lines"}, }; } @@ -353,7 +349,6 @@ std::vector sim_stairs(){ }; } - // The program's walking steps on the simulation, the rest stubbed. class SimExecutor : public Pokemon::StoryStepExecutor{ public: @@ -639,7 +634,6 @@ Outcome SimExecutor::run(RunState& state, const StoryStep& step){ return outcome; } - // Runs `range` of `rows` (the table unless given) on `executor`, stopping // at the first failure. Pokemon::SegmentReport run_rows_on( @@ -693,7 +687,6 @@ std::string end_of(const SimRun& run){ return run.world ? describe(*run.world, run.end) : "nowhere"; } - UnitTestResult run_exit_test(Logger& logger, const std::string& row_id, const StoryStep& old_step, const SimMisses& misses, const Pose& overshoot){ SimExecutor executor(logger, misses); const std::vector rows = table_with(row_id, old_step); @@ -764,7 +757,6 @@ Pose r81_below_the_mouth(){ return Pokemon::tile_pose("Route204North", {TilePos{20, 27}, TilePos{20, 28}, TilePos{20, 29}, TilePos{20, 30}}); } - UnitTestResult test_coord_events(Logger&){ for (const auto& [map, json] : bdsp_map_json()){ const StoryWorld* world = story_plan_world(map, map); @@ -847,6 +839,63 @@ UnitTestResult test_exit_ravaged_path(Logger& logger){ return run_exit_test(logger, "01.09", r81_old_cave_exit(), SimMisses{.fade = 0, .banner = std::nullopt}, r81_below_the_mouth()); } +// Oreburgh Mine B1F: tapping 20 tiles south steps onto the cave mouth warp +// at (12, 21), cutting the counted leg short at 19 tiles. +StoryStep old_mine_hall_south_20(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "into_the_coal_room"; + step.legs = {{.direction = Direction::SOUTH, .tiles = 20}}; + return step; +} + +// Oreburgh Mine B1F: tapping 19 tiles south leaves the player on row 20 +// without warping; the next step (south_to_the_rock) hits the warp immediately. +StoryStep old_mine_hall_south_19(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "into_the_coal_room"; + step.legs = {{.direction = Direction::SOUTH, .tiles = 19}}; + return step; +} + +// Oreburgh Mine B1F: tapping 20 tiles north steps onto the city exit warp +// at (11, 1), cutting the leg short / warping unexpectedly. +StoryStep old_mine_hall_north_20(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "out_of_the_mine"; + step.legs = {{.direction = Direction::NORTH, .tiles = 20}}; + return step; +} + +// Oreburgh Mine: stepping south at col 29 without bypassing the crate +// hits the wooden crate at (29, 28) on the south leg. +StoryStep old_coal_room_crate_cut(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "below_roark"; + step.legs = { + {.direction = Direction::EAST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 2}, + {.direction = Direction::WEST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 5}, + {.direction = Direction::EAST, .tiles = 14}, {.direction = Direction::SOUTH, .tiles = 10}, + {.direction = Direction::SOUTH, .tiles = 2}, {.direction = Direction::WEST, .tiles = 11}, + }; + return step; +} + +UnitTestResult test_story_sim_step_failure(Logger& logger, const std::string& row, const StoryStep& old_step, const std::string& expected_failed_step, const std::string& expected_error){ + SimExecutor executor(logger); + const std::vector rows = table_with(row, old_step); + run_rows_on(executor, logger, {.from = row, .to = row}, rows); + const SimRun& run = executor.result(); + if (run.failed_step != expected_failed_step || run.error.find(expected_error) == std::string::npos){ + return std::format("expected old {} to fail at '{}' with '{}', but got failed_step='{}', error='{}'.", + old_step.name, expected_failed_step, expected_error, run.failed_step, run.error); + } + return true; +} + struct AutoStoryStorySimInput{ std::string name; std::function body; @@ -880,7 +929,6 @@ class Test_AutoStoryStorySim : public UnitTest{ } // namespace - const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { { .input = {"the maps' coord events are on open ground or doors", test_coord_events}, @@ -906,6 +954,30 @@ const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { .input = {"r81, out of the Ravaged Path", test_exit_ravaged_path}, .expectation = {}, }, + { + .input = {"01.03, counted 20 taps south into cave mouth warp", [](Logger& logger){ + return test_story_sim_step_failure(logger, "01.03", old_mine_hall_south_20(), "01.03 into_the_coal_room", "warped at (12, 21)"); + }}, + .expectation = {}, + }, + { + .input = {"01.03, counted 19 taps south leaves player in hall", [](Logger& logger){ + return test_story_sim_step_failure(logger, "01.03", old_mine_hall_south_19(), "01.03 south_to_the_rock", "warp instead of a stop."); + }}, + .expectation = {}, + }, + { + .input = {"01.03, counted 20 taps north into city exit warp", [](Logger& logger){ + return test_story_sim_step_failure(logger, "01.03", old_mine_hall_north_20(), "01.03 out_of_the_mine", "warped at (11, 1)"); + }}, + .expectation = {}, + }, + { + .input = {"01.03, cut corner through coal room crate at col 29", [](Logger& logger){ + return test_story_sim_step_failure(logger, "01.03", old_coal_room_crate_cut(), "01.03 below_roark", "short_leg: south 2 moved 0"); + }}, + .expectation = {}, + }, }; void add_tests_AutoStory_StorySim(UnitTestDatabase& database){ @@ -914,7 +986,6 @@ void add_tests_AutoStory_StorySim(UnitTestDatabase& database){ } } - } // namespace PokemonBDSP } // namespace NintendoSwitch } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index 3b3bdf4564..0d5f55b236 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -12,6 +12,7 @@ #include "Common/Cpp/Filesystem/Filesystem.h" #include "CommonFramework/GlobalAutoPaths.h" #include "Pokemon/Navigation/Pokemon_RouteLog.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP_AutoStory_RouteIO.h" #include "PokemonBDSP_AutoStory_RouteWalk.h" @@ -222,6 +223,7 @@ class RouteWalker{ // Legs to a wall. LegNext wall_leg(LegWalk& walk); + bool finish_interrupted_wall(LegWalk& walk, Milliseconds limit); size_t unstick_wall_leg(LegWalk& walk, size_t walked_tiles, size_t nearest); LegNext stopped_short_of_wall(LegWalk& walk, size_t walked_tiles); void check_at_wall(LegWalk& walk); @@ -229,6 +231,7 @@ class RouteWalker{ // Open legs, tapped. LegNext open_leg(LegWalk& walk); + LegNext interrupted_open_leg(LegWalk& walk); void turn_tap(LegWalk& walk); LegNext blocked_open_leg(LegWalk& walk, size_t moved); @@ -286,14 +289,14 @@ std::vector RouteWalker::run(std::vector from){ } std::vector RouteWalker::plan_legs() const{ - std::optional> legs = plan_robust_route(m_grid, m_from, m_plan.goal, m_plan.costs); + std::optional> legs = plan_recovered_route(m_grid, m_from, m_plan.goal, m_plan.costs); if (!legs){ // From a few possible tiles the exact-open-leg costs found no // plan where the default ones did (r240a, three tiles on Route // 204's row 27); the default plan is longer but sound. m_io.note("[Route] " + m_plan.label + ": no plan with the route costs from " + describe(m_maps, m_from) + "; trying the default costs.", RouteNote::WARNING); - legs = plan_robust_route(m_grid, m_from, m_plan.goal, RobustPlanCosts()); + legs = plan_recovered_route(m_grid, m_from, m_plan.goal, RobustPlanCosts()); } if (!legs){ fail(m_io, m_plan.label + ": no plan from " + describe(m_maps, m_from) + "."); @@ -360,16 +363,7 @@ LegNext RouteWalker::wall_leg(LegWalk& walk){ const TileLeg& leg = walk.planned.leg; const Milliseconds limit = wall_limit(leg); walk.result = m_io.walk_to_wall({.direction = walk.planned.leg.direction, .limit = limit, .label = walk.label, .options = run_watching(walk)}); - // A wild battle may end the walk early. Walking to a wall again ends in - // the same place, so finish the leg. - const bool interrupted = walk.result.wild_battles > 0; - for (size_t again = 0; again < 3 && walk.result.wild_battles > 0 && - (walk.result.stop == WalkStop::LIMIT || walk.result.stop == WalkStop::BLOCKED); again++ - ){ - m_io.note("[Route] " + walk.label + ": a wild battle on the way; walking to the wall again.", RouteNote::LOG); - walk.result = m_io.walk_to_wall({.direction = walk.planned.leg.direction, .limit = limit, .label = walk.label, .options = run_watching(walk)}); - } - if (interrupted){ + if (finish_interrupted_wall(walk, limit)){ return LegNext::NEXT_LEG; } // A wall well before the nearest one the map has: something the map @@ -406,6 +400,30 @@ LegNext RouteWalker::wall_leg(LegWalk& walk){ return LegNext::NEXT_LEG; } +bool RouteWalker::finish_interrupted_wall(LegWalk& walk, Milliseconds limit){ + if (walk.result.wild_battles == 0){ + return false; + } + for (size_t again = 0; again < 3 && walk.result.wild_battles > 0; again++){ + if (walk.result.origin == WalkOrigin::MAY_PRECEDE_LEG){ + fail(m_io, "encounter_origin_unknown: " + walk.label); + } + if (walk.result.stop != WalkStop::LIMIT && walk.result.stop != WalkStop::BLOCKED){ + fail(m_io, "unconfirmed transition/dialogue during wall recovery: " + walk.label); + } + m_io.note("[Route] " + walk.label + ": a wild battle on the way; walking to the wall again.", RouteNote::LOG); + walk.result = m_io.walk_to_wall({.direction = walk.planned.leg.direction, .limit = limit, + .label = walk.label, .options = run_watching(walk)}); + } + if (walk.result.wild_battles > 0){ + fail(m_io, "recovery budget exhausted: " + walk.label); + } + if (walk.result.stop != WalkStop::BLOCKED){ + check_at_wall(walk); + } + return true; +} + // A walk to the wall that stopped well short of it: tap through a corner, // then wait for someone in the way. Returns the tiles walked by then. size_t RouteWalker::unstick_wall_leg(LegWalk& walk, size_t walked_tiles, size_t nearest){ @@ -486,8 +504,12 @@ void RouteWalker::check_at_wall(LegWalk& walk){ // however far it got, so walk on to it and carry on. void RouteWalker::on_to_wall(LegWalk& walk){ m_io.note("[Route] " + walk.label + ": on to the wall after the battle.", RouteNote::WARNING); - m_io.walk_to_wall({.direction = walk.planned.leg.direction, .limit = wall_limit(walk.planned.leg), + const Milliseconds limit = wall_limit(walk.planned.leg); + walk.result = m_io.walk_to_wall({.direction = walk.planned.leg.direction, .limit = limit, .label = walk.label + ": on to the wall", .options = run_watching(walk)}); + if (!finish_interrupted_wall(walk, limit) && walk.result.stop != WalkStop::BLOCKED){ + check_at_wall(walk); + } m_from = walk.planned.after; log_leg_done(m_io, m_maps, m_plan.label, walk.planned, 0); } @@ -504,11 +526,8 @@ LegNext RouteWalker::open_leg(LegWalk& walk){ if (leg.tiles > walk.turn_moved){ walk.result = m_io.walk_taps(leg.direction, leg.tiles - walk.turn_moved, walk.label); } - // A wild battle starts once the step onto the grass is done, so the - // taps still count; the walk went on after it. if (walk.result.wild_battles > 0){ - m_io.note("[Route] " + walk.label + ": " + std::to_string(walk.result.wild_battles) + - " wild battle(s) on the way; the tap count holds.", RouteNote::WARNING); + return interrupted_open_leg(walk); } // Taps that moved nothing: someone stands in the way (the Youngster // below the Ravaged Path wanders across the row under the cliff, r239a, @@ -527,6 +546,12 @@ LegNext RouteWalker::open_leg(LegWalk& walk){ walk.result.stop = rest.stop; walk.result.walked += rest.walked; walk.result.wild_battles += rest.wild_battles; + if (rest.origin == WalkOrigin::MAY_PRECEDE_LEG){ + walk.result.origin = rest.origin; + } + } + if (walk.result.wild_battles > 0){ + return interrupted_open_leg(walk); } if (walk.result.stop == WalkStop::BLOCKED && moved < leg.tiles){ return blocked_open_leg(walk, moved); @@ -534,6 +559,19 @@ LegNext RouteWalker::open_leg(LegWalk& walk){ return LegNext::NEXT_LEG; } +LegNext RouteWalker::interrupted_open_leg(LegWalk& walk){ + if (walk.result.origin == WalkOrigin::MAY_PRECEDE_LEG){ + fail(m_io, "encounter_origin_unknown: " + walk.label); + } + if (walk.result.stop != WalkStop::LIMIT && walk.result.stop != WalkStop::BLOCKED){ + fail(m_io, "interrupted open leg has an unconfirmed dialogue/transition: " + walk.label); + } + auto possible = interrupted_leg_positions(m_grid, m_from, walk.planned.leg.direction, walk.planned.leg.tiles); + const auto next = replan_from(walk, std::move(possible), "encounter: credited taps do not establish pose"); + m_facing.reset(); + return next; +} + // Turns to the leg's way with a tap too short to step (50 ms: on the // console 40 to 80 ms taps only turned). The leg's taps then each move a // tile. The old 160 ms "turn" tap stepped whichever way we faced, and @@ -636,9 +674,21 @@ std::vector RouteWalker::watching_trainers(const std::vector>& paths){ - std::vector anywhere = m_from; - for (const std::vector& path : paths){ - anywhere.insert(anywhere.end(), path.begin(), path.end()); + std::vector anywhere; + const size_t moved = std::min(walk.planned.leg.tiles, walk.result.moved_chunks + walk.turn_moved); + if (walk.result.stop == WalkStop::DIALOG && moved > 0){ + for (const TilePos& pos : m_from){ + const std::vector path = leg_path(m_grid, pos, walk.planned.leg.direction, moved); + if (!path.empty()){ + anywhere.push_back(path.back()); + } + } + } + if (anywhere.empty()){ + anywhere = m_from; + for (const std::vector& path : paths){ + anywhere.insert(anywhere.end(), path.begin(), path.end()); + } } anywhere = sorted_unique(std::move(anywhere)); // A scene the map lacks (r14: Barry's Route 201 warning, then the row that diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp index a89cc82a6c..5014bb7094 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp @@ -237,6 +237,7 @@ class WalkUntil{ } const Milliseconds chunk = std::min(CHUNK, m_spec.limit - m_result.walked); const int ret = hold(chunk); + m_chunks++; m_result.walked += chunk; ChunkVerdict verdict = after_watchers(ret); if (verdict.next == ChunkNext::LOOK){ @@ -334,6 +335,8 @@ class WalkUntil{ // while the president walked off (r67: "east 2 moved 1", and // the console showed both tiles walked). m_result.moved_chunks += 1 + (m_spec.input == WalkInput::TAPS ? m_unchanged : 0); + }else if (m_unchanged == 0){ + m_before_still = m_before; } m_unchanged = still ? m_unchanged + 1 : 0; if (m_unchanged >= 2){ @@ -357,6 +360,14 @@ class WalkUntil{ void escape_battle(const std::string& what){ m_result.wild_battles++; + if (m_chunks <= 1){ + m_result.origin = WalkOrigin::MAY_PRECEDE_LEG; + } + if (m_spec.input == WalkInput::TAPS){ + // Preserve the reporting credit; callers must carry uncertain + // pose after an encounter rather than infer a completed tile. + m_result.moved_chunks++; + } m_stream.log("[Walk] " + m_spec.label + ": " + what); m_escape(m_stream, m_context); m_context.wait_for_all_requests(); @@ -366,10 +377,26 @@ class WalkUntil{ WalkResult finish(WalkStop stop){ m_result.stop = stop; + bool late_battle = false; if (m_spec.wild == WildPolicy::RUN_FROM && (stop == WalkStop::LIMIT || stop == WalkStop::BLOCKED) && run_from_late_encounter(m_stream, m_context, m_escape, m_spec.label) ){ m_result.wild_battles++; + late_battle = true; + m_result.origin = WalkOrigin::MAY_PRECEDE_LEG; + } + // When the final tap of a TAPS leg lagged during frame drops at its + // 800ms check (m_unchanged == 1 at WalkStop::LIMIT), it finishes + // scrolling during the 1200ms late-encounter wait (r4: away_from_barry + // "north 2 moved 1" while console arrived at (14, 16)). + if (!late_battle && m_spec.input == WalkInput::TAPS && stop == WalkStop::LIMIT && + m_unchanged == 1 && m_before_still + ){ + VideoSnapshot after = snapshot_or_fail(m_stream, m_spec.label); + const double change = walk_screen_change(*m_before_still.frame, *after.frame); + if (!still_chunk(change)){ + m_result.moved_chunks++; + } } m_stream.log("[Walk] " + m_spec.label + ": " + walk_stop_name(stop) + " after " + std::to_string(m_result.walked.count()) + "ms, " + @@ -384,7 +411,9 @@ class WalkUntil{ const DpadPosition m_dpad; WalkResult m_result{WalkStop::LIMIT, 0ms, 0}; VideoSnapshot m_before; + VideoSnapshot m_before_still; size_t m_unchanged = 0; + size_t m_chunks = 0; double m_largest = 0; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h index f46828599d..083a6f7672 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h @@ -43,6 +43,10 @@ const char* walk_stop_name(WalkStop stop); // Whether the walk has arrived, from the screen after each chunk. using WalkArrived = std::function; +// An encounter already active at the first input, or found only after a +// leg, may belong to earlier movement. Never localize from this leg alone. +enum class WalkOrigin{ CURRENT_LEG, MAY_PRECEDE_LEG }; + // Result metrics and terminal state returned by automated walking execution. struct WalkResult{ WalkStop stop; @@ -53,6 +57,7 @@ struct WalkResult{ // not count (r248a: "4 taps before the battle" were 2 steps and 2 // taps into Taylor's freeze). size_t moved_chunks = 0; + WalkOrigin origin = WalkOrigin::CURRENT_LEG; }; // Holds the left stick at `stick` until one of the WalkStop events. Wild battles on diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 47d09ba3a9..facba7bdb6 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1719,6 +1719,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp @@ -1727,6 +1729,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp diff --git a/devtools/maps/bdsp_maps.py b/devtools/maps/bdsp_maps.py index 1d54c8ac99..838c5ea679 100644 --- a/devtools/maps/bdsp_maps.py +++ b/devtools/maps/bdsp_maps.py @@ -419,7 +419,7 @@ def box(x0, y0, x1, y1): 'OreburghCity': [(x, 59) for x in range(44, 49)], # The hall's way up to the city: its other warp row (11..13, 21) has # cave mouths below it, so a step south from row 20 goes through. - 'OreburghMineB1F': [(11, 1), (12, 1), (13, 1)], + 'OreburghMineB1F': [(11, 1), (12, 1), (13, 1), (11, 21), (12, 21), (13, 21)], } diff --git a/docs/design/AutoStory-Lesson-Lab-Controller-And-Permissions.md b/docs/design/AutoStory-Lesson-Lab-Controller-And-Permissions.md new file mode 100644 index 0000000000..8734c20cb2 --- /dev/null +++ b/docs/design/AutoStory-Lesson-Lab-Controller-And-Permissions.md @@ -0,0 +1,100 @@ +# Lesson: Lab App vs. Live App Controller Collisions and macOS Permission Isolation + +**Date**: November 2026 +**Context**: Dual-console automation environment running live production (Console A) alongside continuous experimental story runs (Console B). +**Affected PRs / Worktrees**: BDSP AutoStory (`bdsp/autostory-mine-floaroma-wip`, PR #226). +**Classification**: Operational Safety & Process Lesson. + +--- + +## 1. Summary of What Happened + +During development and testing of BDSP AutoStory checkpoint legs on Console B, multiple collisions occurred where: +1. Console A's live session suddenly halted and dropped its microcontroller connection (`INFO_STREAM_NOT_READY`). +2. macOS System Settings (**Privacy & Security -> Camera**) ended up showing three identical entries all titled `SerialPrograms`. +3. Toggling camera permissions caused macOS to prompt "Quit & Reopen", which upon clicking reopened the app into Console A's profile, immediately knocking Console A offline again. +4. Video frames on Console B dropped to 0.00 FPS due to denied TCC permissions triggered by code-signature and bundle identifier mismatches. + +This document records the exact technical root causes, the cascading failures between process management and macOS security, and the operational rules established to prevent recurrence. + +--- + +## 2. Root Cause Analysis + +### A. The Controller Takeover (Default Profile Fallthrough) + +`SerialPrograms` determines hardware bindings (microcontroller serial port and video capture index) using its profile configuration: +* **Target Profile (`--profile lab-B`)**: Isolated to Console B's configuration directory (`~/Library/Application Support/SerialPrograms/Profiles/lab-B/`) and serial device (`cu.usbmodem...B`). +* **Default Profile (`--profile` omitted)**: Stored in `~/Library/Application Support/SerialPrograms/UserSettings/SerialPrograms-Settings.json`, which was pre-configured with **Console A's live production hardware** (`cu.usbmodem5C630032771`). + +When an agent launched a test command directly: +```bash +./SerialPrograms.app/Contents/MacOS/SerialPrograms --test "bdsp" +``` +or when macOS restarted the app from a system dialog, the executable was invoked **without** `--profile lab-B`. + +Upon startup, `SerialPrograms` initialized its default settings and immediately sent: +```text +PABB2_CONNECTION_OPCODE_ASK_RESET +``` +to Console A's serial port. This reset Console A's PABotBase hardware while Console A was actively playing. Console A's live controller stream immediately severed, aborting the active production run. + +### B. The 3 Identical Permission Entries in System Settings + +macOS TCC (Transparency, Consent, and Control) isolates camera capture permissions based on the application's unique bundle identifier (`CFBundleIdentifier`) and code signature. The lab environment had three bundles: + +| Entry | Bundle Identifier | File System Location | Intended Console | +| :--- | :--- | :--- | :--- | +| **Production** | `PokemonAutomation.SerialPrograms` | `/Applications/SerialPrograms.app` | **Console A (Live)** | +| **Slot A Lab** | `com.dayfine.pokemonautomation.lab` | `~/BDSPLab/builds/slot-A/` | Console A (Test) | +| **Slot B Lab** | `com.dayfine.pokemonautomation.lab2` | `~/BDSPLab/builds/*-B/` | **Console B (Lab)** | + +In [`make_slot_b.sh`](file:///Users/difan/BDSPLab/make_slot_b.sh), the packaging script attempted to set a friendly display name: +```bash +/usr/libexec/PlistBuddy -c 'Set :CFBundleDisplayName PokemonAutomation Lab 2' $A/Contents/Info.plist 2>/dev/null +``` +**The Failure**: In Apple's `PlistBuddy`, the `Set` command fails silently if the specified key does not already exist in the plist. Because `CFBundleDisplayName` was not in the base template, the key was never written. + +**The Result**: Without `CFBundleDisplayName`, macOS Privacy & Security fell back to the raw binary name (`SerialPrograms`) for all three bundles. The user saw **three identical entries named `SerialPrograms`** in System Settings with no indication of which toggle corresponded to Console A vs. Console B. + +### C. The Permission Toggle and "Quit & Reopen" Trap + +1. **Rebuilds and CDHash Changes**: While the code-signing certificate remained constant (`PokemonAutomation Local Development`), every C++ compilation generated a new binary with a new Code Directory Hash (`CDHash`). +2. **Permission Denied**: In attempting to identify the correct entry among the three identical toggles, switches were flipped. Once macOS flags a bundle identifier as Denied, Qt's camera permission handler (`SetupSettings.cpp`) evaluates to: + ```text + Qt::PermissionStatus::Denied -> "No camera permission found" + ``` + Under macOS security policies, once an application is marked Denied, video capture frames are dropped silently (0.00 FPS), and the OS will not present another permission request prompt. +3. **The LaunchServices Trap**: When toggled back to ON in System Settings, macOS displayed a modal: *"Quit & Reopen"*. + Clicking "Reopen" prompted LaunchServices to start the app bundle directly with **zero command-line arguments**. The app launched into the default profile, sending the reset command to Console A's port and hijacking the live controller once again. + +--- + +## 3. The Rules (Lessons for Process & Architecture) + +### Rule 1: Packaging Must Guarantee Unique Display Names +Packaging and deployment scripts (`make_slot_b.sh`, `bdsp_deploy.sh`) must never rely on `PlistBuddy Set` on unverified keys. They must explicitly delete (ignoring error) and `Add`: +```bash +/usr/libexec/PlistBuddy -c 'Delete :CFBundleDisplayName' "$PLIST" 2>/dev/null || true +/usr/libexec/PlistBuddy -c 'Add :CFBundleDisplayName string "PokemonAutomation Lab 2 (Console B)"' "$PLIST" +/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -f "$APP_BUNDLE" +``` +This guarantees distinct names in macOS System Settings: +* Release App: `SerialPrograms` +* Slot A Lab: `PokemonAutomation Lab (Console A)` +* Slot B Lab: `PokemonAutomation Lab 2 (Console B)` + +### Rule 2: Never Run Unwrapped Binaries or Click OS "Reopen" +* Never run `./SerialPrograms` or `./SerialPrograms.app/Contents/MacOS/SerialPrograms` directly without `--profile `. +* If macOS presents a "Quit & Reopen" dialog after a permission toggle, click **Quit Only**. Never allow macOS to reopen the application, as it will launch without CLI flags and collide with Console A. +* Always launch lab instances through designated launch scripts (e.g. `open -n -a "$APP_BUNDLE" --args --profile lab-B`) or explicit test runners. + +### Rule 3: Targeted TCC Reset +If TCC entries become stale or confused, do not guess and toggle entries in System Settings. Clear only the specific lab bundle ID from the terminal: +```bash +tccutil reset Camera com.dayfine.pokemonautomation.lab2 +``` +This leaves Console A's production permissions completely intact while resetting Console B to a clean slate. + +### Rule 4: Default Profile Safety Isolation +The default profile (`UserSettings/SerialPrograms-Settings.json`) should not be treated as a catch-all. Production console controller ports should either require an explicit `--profile live-A` flag, or unparameterized headless/unit-test invocations must default to a dummy/mock controller rather than auto-connecting to the primary serial port. diff --git a/docs/design/AutoStory-Lessons.md b/docs/design/AutoStory-Lessons.md index 8c8f2e982a..381347e59e 100644 --- a/docs/design/AutoStory-Lessons.md +++ b/docs/design/AutoStory-Lessons.md @@ -423,3 +423,10 @@ walk into Floaroma) is the last checkpoint and took eight builds; what they taug Platinum's for Route 204 North, and its coord-event binaries give the story triggers' rectangles and flag values, which Platinum's JSON confirms. Diamond is the primary source now, Platinum the readable cross-check. +- **Isolate lab profiles from live hardware and name macOS bundles explicitly.** + Running raw binaries or reopening from OS permission modals without `--profile lab-B` + defaulted to Console A's serial port and sent reset opcodes, dropping Console A's session. + Missing `CFBundleDisplayName` in lab plist templates made three bundles appear identically as + `SerialPrograms` in macOS Privacy & Security. Full breakdown and operational rules: + [`AutoStory-Lesson-Lab-Controller-And-Permissions.md`](AutoStory-Lesson-Lab-Controller-And-Permissions.md). + From fc56a720b9c0b1f4d945dbef382d61b0a6382b97 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 15:28:09 -0800 Subject: [PATCH 009/166] BDSP AutoStory: test real Oreburgh Mine corridor runs to and back in simulation --- .../PokemonBDSP_AutoStory_Actions_Tests.cpp | 4 +- ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 2 +- ...kemonBDSP_AutoStory_RoutePlanner_Tests.cpp | 2 +- .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 4 +- .../PokemonBDSP_AutoStory_GridSim.cpp | 2 +- .../PokemonBDSP_AutoStory_GridSim.h | 2 +- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 12 +-- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 79 ++++++++++--------- ...onBDSP_AutoStory_StorySimulation_Tests.cpp | 8 +- 9 files changed, 59 insertions(+), 56 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.cpp index bd1476caf1..6b78029754 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.cpp @@ -20,8 +20,8 @@ #include "CommonFramework/GlobalAutoPaths.h" #include "CommonFramework/ImageTypes/ImageRGB32.h" #include "CommonFramework/Logging/Logger.h" -#include "Data/PokemonBDSP_AutoStory_StoryMaps.h" -#include "Utils/PokemonBDSP_AutoStory_Location.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP_AutoStory_Center.h" #include "PokemonBDSP_AutoStory_NewGame.h" #include "PokemonBDSP_AutoStory_Actions_Tests.h" diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index 8b9c5dd4c8..486700ab5f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -9,7 +9,7 @@ */ #include #include "Pokemon/AutoStory/Pokemon_TilePose.h" -#include "Utils/PokemonBDSP_AutoStory_GridSim.h" +#include "Simulation/PokemonBDSP_AutoStory_GridSim.h" #include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP_AutoStory_StoryTable.h" diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp index 4d95398bd8..5696886887 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp @@ -17,7 +17,7 @@ #include "Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "Data/PokemonBDSP_AutoStory_Maps.h" -#include "Utils/PokemonBDSP_AutoStory_GridSim.h" +#include "Simulation/PokemonBDSP_AutoStory_GridSim.h" #include "PokemonBDSP_AutoStory_RoutePlanner_Tests.h" namespace PokemonAutomation{ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index e2a6b89fcf..e8c1c16388 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -18,9 +18,9 @@ #include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" -#include "PokemonBDSP_AutoStory_Talks.h" +#include "Actions/PokemonBDSP_AutoStory_Talks.h" #include "PokemonBDSP_AutoStory_Walks.h" -#include "PokemonBDSP_AutoStory_WildBattle.h" +#include "Actions/PokemonBDSP_AutoStory_WildBattle.h" #include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_StoryStepIO.h" diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp index 5a7be14d15..286872a810 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -6,7 +6,7 @@ #include #include -#include "PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP_AutoStory_GridSim.h" namespace PokemonAutomation{ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h index d79ea9e595..6457abf373 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h @@ -32,7 +32,7 @@ #include "Pokemon/Navigation/Pokemon_Grid.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" -#include "PokemonBDSP_AutoStory_RouteIO.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.h" namespace PokemonAutomation{ namespace NintendoSwitch{ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index ec8db51b68..8030c8d0be 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -18,13 +18,13 @@ #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" -#include "Data/PokemonBDSP_AutoStory_Maps.h" -#include "Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" #include "PokemonBDSP_AutoStory_GridSim.h" -#include "Utils/PokemonBDSP_AutoStory_PlannedRoute.h" -#include "PokemonBDSP_AutoStory_StoryExecutor.h" -#include "PokemonBDSP_AutoStory_StoryPlaces.h" -#include "PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_GridSim_Tests.h" namespace PokemonAutomation{ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 590755af5b..aa14dd0113 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -38,16 +38,16 @@ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Pokemon/AutoStory/Pokemon_StorySegments.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" -#include "Data/PokemonBDSP_AutoStory_CoordEvents.h" -#include "Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP_AutoStory_GridSim.h" -#include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" -#include "PokemonBDSP_AutoStory_Events.h" -#include "PokemonBDSP_AutoStory_StoryExecutor.h" -#include "PokemonBDSP_AutoStory_StoryPlaces.h" -#include "PokemonBDSP_AutoStory_StoryStepIO.h" -#include "PokemonBDSP_AutoStory_StoryTable.h" -#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" #include "PokemonBDSP_AutoStory_StorySim_Tests.h" namespace PokemonAutomation{ @@ -839,33 +839,38 @@ UnitTestResult test_exit_ravaged_path(Logger& logger){ return run_exit_test(logger, "01.09", r81_old_cave_exit(), SimMisses{.fade = 0, .banner = std::nullopt}, r81_below_the_mouth()); } -// Oreburgh Mine B1F: tapping 20 tiles south steps onto the cave mouth warp -// at (12, 21), cutting the counted leg short at 19 tiles. -StoryStep old_mine_hall_south_20(){ - StoryStep step; - step.kind = StoryStepKind::LEGS; - step.name = "into_the_coal_room"; - step.legs = {{.direction = Direction::SOUTH, .tiles = 20}}; - return step; -} - -// Oreburgh Mine B1F: tapping 19 tiles south leaves the player on row 20 -// without warping; the next step (south_to_the_rock) hits the warp immediately. -StoryStep old_mine_hall_south_19(){ - StoryStep step; - step.kind = StoryStepKind::LEGS; - step.name = "into_the_coal_room"; - step.legs = {{.direction = Direction::SOUTH, .tiles = 19}}; - return step; +// Oreburgh Mine B1F: the entrance hall corridor is traversed to and back by +// running south from (12, 1) to (12, 21), and north from (11, 21) to (11, 1). +UnitTestResult test_oreburgh_mine_hall_corridor(Logger& logger){ + const StoryWorld* world = story_plan_world("OreburghMineB1F", "OreburghMineB1F"); + if (world == nullptr){ + return "OreburghMineB1F world not found."; + } + const SimWorld sim_world{.world = world, .can_run = true}; + const auto test_run = [&](TilePos start, Direction dir, TilePos expected, const char* label){ + GridSim sim(sim_world, start, dir, true); + const SimMove move = sim.hold(dir, 5000ms, SimPace::RUN); + if (move.stop != SimStop::WARP || sim.player().pos != sim_pos(expected)){ + return std::format("{}: expected WARP at {}, got {} at {}.", label, + Pokemon::to_string(expected), sim_stop_name(move.stop), Pokemon::to_string(nearest_tile(sim.player().pos))); + } + logger.log(std::format("{} hall run reached {} in {} ms.", label, Pokemon::to_string(expected), move.time.count())); + return std::string{}; + }; + std::string err = test_run({12, 1}, Direction::SOUTH, {12, 21}, "Southbound"); + if (!err.empty()){ + return err; + } + err = test_run({11, 21}, Direction::NORTH, {11, 1}, "Northbound"); + return err.empty() ? UnitTestResult(true) : UnitTestResult(err); } -// Oreburgh Mine B1F: tapping 20 tiles north steps onto the city exit warp -// at (11, 1), cutting the leg short / warping unexpectedly. -StoryStep old_mine_hall_north_20(){ +// Oreburgh Mine B1F: tapping 19 tiles leaves the player 1 tile short of the warp door. +StoryStep old_mine_hall_19(std::string name, Direction direction){ StoryStep step; step.kind = StoryStepKind::LEGS; - step.name = "out_of_the_mine"; - step.legs = {{.direction = Direction::NORTH, .tiles = 20}}; + step.name = std::move(name); + step.legs = {{.direction = direction, .tiles = 19}}; return step; } @@ -955,20 +960,18 @@ const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { .expectation = {}, }, { - .input = {"01.03, counted 20 taps south into cave mouth warp", [](Logger& logger){ - return test_story_sim_step_failure(logger, "01.03", old_mine_hall_south_20(), "01.03 into_the_coal_room", "warped at (12, 21)"); - }}, + .input = {"01.03, Oreburgh Mine B1F entrance hall corridor runs to and back", test_oreburgh_mine_hall_corridor}, .expectation = {}, }, { .input = {"01.03, counted 19 taps south leaves player in hall", [](Logger& logger){ - return test_story_sim_step_failure(logger, "01.03", old_mine_hall_south_19(), "01.03 south_to_the_rock", "warp instead of a stop."); + return test_story_sim_step_failure(logger, "01.03", old_mine_hall_19("into_the_coal_room", Direction::SOUTH), "01.03 south_to_the_rock", "warp instead of a stop."); }}, .expectation = {}, }, { - .input = {"01.03, counted 20 taps north into city exit warp", [](Logger& logger){ - return test_story_sim_step_failure(logger, "01.03", old_mine_hall_north_20(), "01.03 out_of_the_mine", "warped at (11, 1)"); + .input = {"01.03, counted 19 taps north leaves player in hall", [](Logger& logger){ + return test_story_sim_step_failure(logger, "01.03", old_mine_hall_19("out_of_the_mine", Direction::NORTH), "01.03 up_to_the_mines_sign", "warp instead of a stop."); }}, .expectation = {}, }, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index a9918401a3..27c100db13 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -24,10 +24,10 @@ #include "Pokemon/AutoStory/Pokemon_StorySegments.h" #include "Pokemon/AutoStory/Pokemon_StorySteps.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" -#include "Utils/PokemonBDSP_AutoStory_Location.h" -#include "Data/PokemonBDSP_AutoStory_PlanCosts.h" -#include "PokemonBDSP_AutoStory_StoryPlaces.h" -#include "PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_StorySimulation_Tests.h" namespace PokemonAutomation{ From 201bd0e43054c370f5d56929e73a7fe72a6488b1 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 15:40:10 -0800 Subject: [PATCH 010/166] BDSP AutoStory: bound hallway mine exit run and support daylight transition --- ...okemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 2 +- .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 18 ++++++++++-------- .../PokemonBDSP_AutoStory_StoryStepIO.h | 4 ++-- .../PokemonBDSP_AutoStory_StoryTable.cpp | 5 +++-- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 3 ++- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 4 ++-- 6 files changed, 20 insertions(+), 16 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index 486700ab5f..fe28271410 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -50,7 +50,7 @@ class RecoveryStepIO : public StoryStepIO{ virtual void fight(const std::string&) override{ throw GridSimFailure{"unexpected trainer"}; } virtual void walk_until_stopped(Direction, size_t, const std::string&) override{ throw GridSimFailure{"unexpected blind hold"}; } virtual bool run_until_map(Direction, Milliseconds, const std::string&, const std::string&) override{ throw GridSimFailure{"unexpected banner walk"}; } - virtual bool run_into_door(Direction, bool) override{ throw GridSimFailure{"unexpected door"}; } + virtual bool run_into_door(Direction, bool, Milliseconds = Milliseconds(12000)) override{ throw GridSimFailure{"unexpected door"}; } virtual std::optional tap_to_banner(Direction, const std::string&, size_t) override{ throw GridSimFailure{"unexpected banner"}; } virtual void settle(Button, const std::string&, bool) override{ throw GridSimFailure{"unexpected scene"}; } private: diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index e8c1c16388..b3c0f54c72 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -13,6 +13,7 @@ #include "CommonTools/VisualDetectors/BlackScreenDetector.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h" #include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" #include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" #include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h" @@ -107,23 +108,24 @@ DpadPosition dpad_toward(Direction direction){ direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; } -bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction direction, bool run){ +bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction direction, bool run, Milliseconds timeout){ const DpadPosition dpad = dpad_toward(direction); BlackScreenWatcher dark(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, 3 * FADE_DARKNESS, 60); + WhiteScreenWatcher white(COLOR_BLUE, {0.1, 0.1, 0.8, 0.8}, WhiteScreenWatcher::FinderType::PRESENT, 60ms); ShortDialogWatcher dialog(COLOR_YELLOW); BattleMenuWatcher battle(BattleType::STANDARD, COLOR_YELLOW); const int ret = run_until(stream, context, [&](ProControllerContext& context){ if (run){ - ssf_press_button(context, BUTTON_B, 0ms, 12000ms, 0ms); + ssf_press_button(context, BUTTON_B, 0ms, timeout, 0ms); } - pbf_press_dpad(context, dpad, 12000ms, 0ms); - }, {{dark}, {dialog}, {battle}}); - if (ret == 2){ + pbf_press_dpad(context, dpad, timeout, 0ms); + }, {{dark}, {white}, {dialog}, {battle}}); + if (ret == 3){ stream.log("[Story] run_into_door: wild battle; fleeing."); run_from_wild_battle(stream, context); return false; } - return ret == 0; + return ret == 0 || ret == 1; } // What the screen showed after a tap toward a door or a cave mouth. @@ -185,8 +187,8 @@ bool ConsoleStoryStepIO::run_until_map(Direction direction, Milliseconds limit, return walk.stop == WalkStop::ARRIVED; } -bool ConsoleStoryStepIO::run_into_door(Direction direction, bool run){ - return PokemonBDSP::run_into_door(m_stream, m_context, direction, run); +bool ConsoleStoryStepIO::run_into_door(Direction direction, bool run, Milliseconds timeout){ + return PokemonBDSP::run_into_door(m_stream, m_context, direction, run, timeout); } // A held walk can carry on past a fade that goes unseen: out of the Gym it diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h index a6175834ac..da718a6aba 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h @@ -45,7 +45,7 @@ class StoryStepIO{ virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string& label) = 0; // Holds the D-pad toward a door (running with `run`) until the screen // goes dark or a line shows. Returns whether it went dark. - virtual bool run_into_door(Pokemon::Direction direction, bool run) = 0; + virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000)) = 0; // D-pad taps `direction` one at a time, each looked at, toward a door // or cave mouth, until the fade (then no more taps) and the location // banner of `map` (a JSON map's name), for at most `max_taps`. Returns @@ -68,7 +68,7 @@ class ConsoleStoryStepIO : public StoryStepIO{ virtual void fight(const std::string& trainer) override; virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string& label) override; - virtual bool run_into_door(Pokemon::Direction direction, bool run) override; + virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000)) override; virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) override; virtual void settle(Button button, const std::string& label, bool fade) override; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 7236bf15d7..dc00019d3f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -148,10 +148,11 @@ StoryStep anchored(StoryStep step, Pose pose){ } // TODO(#114 coord events): the map schema has no scene triggers yet, so // each row steps onto the decomp's trigger tile, named in its reason. -StoryStep step_into(std::string name, Direction direction, std::string why, std::optional pose_after = std::nullopt){ +StoryStep step_into(std::string name, Direction direction, std::string why, std::optional pose_after = std::nullopt, std::string variant = ""){ StoryStep step = make(StoryStepKind::STEP, std::move(name), std::move(why)); step.direction = direction; step.pose_after = std::move(pose_after); + step.variant = std::move(variant); return step; } // Through a door or a cave mouth `direction` a D-pad tap at a time, each @@ -745,7 +746,7 @@ StoryCheckpoint oreburgh_mine_to_roark(){ at(MINE, 15, 2, NORTH)), step_into("up_to_the_hall", NORTH, "the warp tile (15, 1)", at(MINE_HALL, 11, 21, NORTH)), step_into("out_of_the_mine", NORTH, "up the entrance hall and out to the city", - Pokemon::tile_pose(OREBURGH, {TilePos{45, 59}, TilePos{45, 58}}, NORTH)), + Pokemon::tile_pose(OREBURGH, {TilePos{45, 59}, TilePos{45, 58}}, NORTH), "bounded"), anchored(to_walls("up_to_the_mines_sign", {{.direction = NORTH, .tiles = 3}}, "north against the mine's sign (45, 56)"), at(OREBURGH, 45, 57, NORTH)), route("below_the_centers_door_again", below_oreburghs_center(), "up to below the Center's door", "town"), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index d39b0198cf..afdfa7118b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -272,7 +272,8 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ // (r33 was outside, "no fade"). No separate turn tap first: at 1 tile // from the door, a 50 ms turn tap can step in before run_into_door() watches. if (step.pose_after && step.pose_after->map != state.pose.map){ - const bool faded = m_io.run_into_door(step.direction, m_can_run); + const Milliseconds timeout = (step.variant == "bounded" || (state.pose.map == "OreburghMineB1F" && step.name == "out_of_the_mine")) ? 3800ms : 12000ms; + const bool faded = m_io.run_into_door(step.direction, m_can_run, timeout); log(std::format("[{}] {}: {} through the door: {}.", m_row, step.name, direction_name(step.direction), faded ? "faded" : "no fade yet")); m_io.settle(BUTTON_B, label_of(step), !faded); return Pokemon::outcome_ok(); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index aa14dd0113..ab957ef11f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -131,8 +131,8 @@ class SimStoryStepIO : public StoryStepIO{ } virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string& label) override; virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; - virtual bool run_into_door(Direction direction, bool run) override{ - const bool warped = m_sim.hold(direction, 12000ms, run ? SimPace::RUN : SimPace::WALK).stop == SimStop::WARP; + virtual bool run_into_door(Direction direction, bool run, Milliseconds timeout = Milliseconds(12000)) override{ + const bool warped = m_sim.hold(direction, timeout, run ? SimPace::RUN : SimPace::WALK).stop == SimStop::WARP; if (warped && fade_missed()){ m_misses.fade_unseen = true; return false; From 49437315182e59f42bea13cf64b929354cace6c1 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 16:03:05 -0800 Subject: [PATCH 011/166] BDSP AutoStory: derive door run duration dynamically from map tile distance --- .../PokemonBDSP_AutoStory_StoryTable.cpp | 5 ++- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 34 +++++++++++++++++-- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index dc00019d3f..7236bf15d7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -148,11 +148,10 @@ StoryStep anchored(StoryStep step, Pose pose){ } // TODO(#114 coord events): the map schema has no scene triggers yet, so // each row steps onto the decomp's trigger tile, named in its reason. -StoryStep step_into(std::string name, Direction direction, std::string why, std::optional pose_after = std::nullopt, std::string variant = ""){ +StoryStep step_into(std::string name, Direction direction, std::string why, std::optional pose_after = std::nullopt){ StoryStep step = make(StoryStepKind::STEP, std::move(name), std::move(why)); step.direction = direction; step.pose_after = std::move(pose_after); - step.variant = std::move(variant); return step; } // Through a door or a cave mouth `direction` a D-pad tap at a time, each @@ -746,7 +745,7 @@ StoryCheckpoint oreburgh_mine_to_roark(){ at(MINE, 15, 2, NORTH)), step_into("up_to_the_hall", NORTH, "the warp tile (15, 1)", at(MINE_HALL, 11, 21, NORTH)), step_into("out_of_the_mine", NORTH, "up the entrance hall and out to the city", - Pokemon::tile_pose(OREBURGH, {TilePos{45, 59}, TilePos{45, 58}}, NORTH), "bounded"), + Pokemon::tile_pose(OREBURGH, {TilePos{45, 59}, TilePos{45, 58}}, NORTH)), anchored(to_walls("up_to_the_mines_sign", {{.direction = NORTH, .tiles = 3}}, "north against the mine's sign (45, 56)"), at(OREBURGH, 45, 57, NORTH)), route("below_the_centers_door_again", below_oreburghs_center(), "up to below the Center's door", "town"), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index afdfa7118b..14ff58a386 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -45,6 +45,33 @@ std::string label_of(const StoryStep& step){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "RouteIO::note() returned from a failure: " + message); } +// How many tiles from `pose` along `direction` to the door or map edge. +// When stepping through a door from across the room (or down an entrance hall), +// this bounds the run so missing a fade does not run away across the far map. +size_t tiles_to_door(const Pose& pose, Direction direction){ + const std::vector tiles = Pokemon::tiles_of(pose); + if (tiles.empty()){ + return 1; + } + const StoryWorld* world = story_plan_world(pose.map, pose.map); + if (world == nullptr){ + return 1; + } + const TilePos start = story_to_world(*world, pose.map, tiles.front()); + TilePos at = start; + size_t count = 0; + while (count < 50){ + const TilePos next = at.next(direction); + count++; + const std::optional kind = world->tile(next); + if (!kind || *kind == Pokemon::TileKind::DOOR || *kind == Pokemon::TileKind::WALL || world->occupied(next)){ + break; + } + at = next; + } + return std::max(1, count); +} + } // namespace @@ -272,9 +299,12 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ // (r33 was outside, "no fade"). No separate turn tap first: at 1 tile // from the door, a 50 ms turn tap can step in before run_into_door() watches. if (step.pose_after && step.pose_after->map != state.pose.map){ - const Milliseconds timeout = (step.variant == "bounded" || (state.pose.map == "OreburghMineB1F" && step.name == "out_of_the_mine")) ? 3800ms : 12000ms; + const size_t tiles = tiles_to_door(state.pose, step.direction); + const Milliseconds per_tile = route_ms_per_tile(step.direction, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK); + const Milliseconds timeout = std::max(1500ms, ROUTE_START_DELAY + per_tile * (int64_t)tiles + 800ms); const bool faded = m_io.run_into_door(step.direction, m_can_run, timeout); - log(std::format("[{}] {}: {} through the door: {}.", m_row, step.name, direction_name(step.direction), faded ? "faded" : "no fade yet")); + log(std::format("[{}] {}: {} through the door ({} tiles, {} ms limit): {}.", + m_row, step.name, direction_name(step.direction), tiles, timeout.count(), faded ? "faded" : "no fade yet")); m_io.settle(BUTTON_B, label_of(step), !faded); return Pokemon::outcome_ok(); } From 2e2fcb3ccb07d0ede55cf2a32417f97da1d599c6 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 16:29:07 -0800 Subject: [PATCH 012/166] BDSP AutoStory sim: bound door runs by tile distance and support white fades --- .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 39 ++++++++++++------- .../PokemonBDSP_AutoStory_StoryStepIO.h | 4 +- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 14 ++++++- 3 files changed, 39 insertions(+), 18 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index 275717d800..dd4b1a0637 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -13,6 +13,8 @@ #include "CommonTools/VisualDetectors/BlackScreenDetector.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" #include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" #include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" @@ -46,33 +48,35 @@ namespace{ // and only the quiet after the fade counts: r30's scene went quiet for 5 s // before the fade home, and r28 "went out" a tile beside the door and // walked a whole route in the house. No fade is a map mismatch. -constexpr double FADE_DARKNESS = 40; // brightness 0 to 255; r24's dim fade home goes darker +constexpr double FADE_DARKNESS = 75; // brightness 0 to 255; cave fades reach ~45..64, r24's dim fade goes darker void settle(VideoStream& stream, ProControllerContext& context, Button button, const std::string& label, bool fade){ const WallClock none = WallClock::max(); const WallClock deadline = current_time() + 120s; ShortDialogDetector dialog; OverworldDetector overworld; - WallClock quiet_since = none; - WallClock calm_since = none; // overworld, no text, still or not + BattleMenuDetector battle_menu(BattleType::STANDARD); + WallClock quiet_since = none, calm_since = none; double darkest = 255; VideoSnapshot previous; while (current_time() < deadline){ context.wait_for_all_requests(); const auto frame = stream.video().snapshot(); const WallClock now = current_time(); + if (frame && battle_menu.detect(frame)){ + stream.log("[Story] " + label + ": in wild battle during settle; fleeing."); + run_from_wild_battle(stream, context); + continue; + } if (frame){ darkest = std::min(darkest, image_average(*frame.frame).sum() / 3); } const bool talking = frame && dialog.detect(frame); const bool still = frame && previous && walk_screen_change(*previous.frame, *frame.frame) < WALK_TAP_BLOCKED_CHANGE; previous = frame; - // Cloud shadows drift over Floaroma, so its screen is never still: r83 - // got Mew and then waited out the 120 s on a calm overworld. 15 s of - // overworld with no text is three times r31's silent walk-in. const bool calm = !talking && overworld.detect(frame) && (!fade || darkest < FADE_DARKNESS); calm_since = calm ? (calm_since == none ? now : calm_since) : none; if (calm && now - calm_since >= 15000ms){ - stream.log(std::format("[Story] {}: settled on 15 s of overworld without text (the screen kept moving); darkest frame {:.0f}.", label, darkest)); + stream.log(std::format("[Story] {}: settled on calm overworld; darkest frame {:.0f}.", label, darkest)); return; } if (!talking && still && overworld.detect(frame) && (!fade || darkest < FADE_DARKNESS)){ @@ -105,17 +109,24 @@ DpadPosition dpad_toward(Direction direction){ direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; } -bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction direction, bool run){ +bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction direction, bool run, Milliseconds timeout){ const DpadPosition dpad = dpad_toward(direction); BlackScreenWatcher dark(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, 3 * FADE_DARKNESS, 60); + WhiteScreenWatcher white(COLOR_BLUE, {0.1, 0.1, 0.8, 0.8}, WhiteScreenWatcher::FinderType::PRESENT, 60ms); ShortDialogWatcher dialog(COLOR_YELLOW); + BattleMenuWatcher battle(BattleType::STANDARD, COLOR_YELLOW); const int ret = run_until(stream, context, [&](ProControllerContext& context){ if (run){ - ssf_press_button(context, BUTTON_B, 0ms, 12000ms, 0ms); + ssf_press_button(context, BUTTON_B, 0ms, timeout, 0ms); } - pbf_press_dpad(context, dpad, 12000ms, 0ms); - }, {{dark}, {dialog}}); - return ret == 0; + pbf_press_dpad(context, dpad, timeout, 0ms); + }, {{dark}, {white}, {dialog}, {battle}}); + if (ret == 3){ + stream.log("[Story] run_into_door: wild battle; fleeing."); + run_from_wild_battle(stream, context); + return false; + } + return ret == 0 || ret == 1; } // What the screen showed after a tap toward a door or a cave mouth. @@ -177,8 +188,8 @@ bool ConsoleStoryStepIO::run_until_map(Direction direction, Milliseconds limit, return walk.stop == WalkStop::ARRIVED; } -bool ConsoleStoryStepIO::run_into_door(Direction direction, bool run){ - return PokemonBDSP::run_into_door(m_stream, m_context, direction, run); +bool ConsoleStoryStepIO::run_into_door(Direction direction, bool run, Milliseconds timeout){ + return PokemonBDSP::run_into_door(m_stream, m_context, direction, run, timeout); } // A held walk can carry on past a fade that goes unseen: out of the Gym it diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h index a6175834ac..da718a6aba 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h @@ -45,7 +45,7 @@ class StoryStepIO{ virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string& label) = 0; // Holds the D-pad toward a door (running with `run`) until the screen // goes dark or a line shows. Returns whether it went dark. - virtual bool run_into_door(Pokemon::Direction direction, bool run) = 0; + virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000)) = 0; // D-pad taps `direction` one at a time, each looked at, toward a door // or cave mouth, until the fade (then no more taps) and the location // banner of `map` (a JSON map's name), for at most `max_taps`. Returns @@ -68,7 +68,7 @@ class ConsoleStoryStepIO : public StoryStepIO{ virtual void fight(const std::string& trainer) override; virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string& label) override; - virtual bool run_into_door(Pokemon::Direction direction, bool run) override; + virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000)) override; virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) override; virtual void settle(Button button, const std::string& label, bool fade) override; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index 067a6281af..e7af759fd5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -9,6 +9,7 @@ #include "Common/Cpp/Color.h" #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Pokemon/Navigation/Pokemon_MapData.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP_AutoStory_StoryExecutor.h" @@ -213,8 +214,17 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ // 00.01; Dawn's tour, 00.04). Without the fade, settle must see it itself // (r33 was outside, "no fade"). if (step.pose_after && step.pose_after->map != state.pose.map){ - const bool faded = m_io.run_into_door(step.direction, m_can_run); - log(std::format("[{}] {}: {} through the door: {}.", m_row, step.name, direction_name(step.direction), faded ? "faded" : "no fade yet")); + Milliseconds timeout(12000); + if (m_world.has(state.pose.map)){ + const Pokemon::MapData& map = m_world.map(state.pose.map); + const size_t tiles = Pokemon::tiles_to_door(map, state.pose.pos, step.direction); + if (tiles > 0){ + const Milliseconds per_tile = route_ms_per_tile(step.direction, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK); + timeout = std::max(1500ms, ROUTE_START_DELAY + per_tile * (int64_t)tiles + 800ms); + } + } + const bool faded = m_io.run_into_door(step.direction, m_can_run, timeout); + log(std::format("[{}] {}: {} through the door (timeout {} ms): {}.", m_row, step.name, direction_name(step.direction), timeout.count(), faded ? "faded" : "no fade yet")); m_io.settle(BUTTON_B, label_of(step), !faded); return Pokemon::outcome_ok(); } From 67438e510d1d7c824473424c73766160f558e116 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 16:51:49 -0800 Subject: [PATCH 013/166] BDSP AutoStory sim: add recovery walk and interrupted mine tap tests with wall recovery --- .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 2 + ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 155 ++++++++++++++++++ ...PokemonBDSP_AutoStory_RecoveryWalk_Tests.h | 15 ++ ...kemonBDSP_AutoStory_RoutePlanner_Tests.cpp | 80 +++++++-- .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 9 +- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 106 +++++++++--- SerialPrograms/cmake/SourceFiles.cmake | 2 + 7 files changed, 329 insertions(+), 40 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index 73c0d12a29..72c29a2fa1 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -7,6 +7,7 @@ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h" @@ -37,6 +38,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_Walk(database); add_tests_AutoStory_PlannedRoute(database); add_tests_AutoStory_GridSim(database); + add_tests_AutoStory_RecoveryWalk(database); add_tests_AutoStory_StorySim(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp new file mode 100644 index 0000000000..fe28271410 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -0,0 +1,155 @@ +/* BDSP Recovery Walk Tests + * + * From: https://github.com/PokemonAutomation/ + * + * November 5 mine report: EAST 14 moved 4 beside Machop on row 15. + * The exact deployed revision/run ID is unavailable. BEFORE/AFTER events + * and two interrupted advances are explicit diagnostics, not an inferred + * physical cause. Run the real story step and route walker on GridSim. + */ +#include +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Simulation/PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_RecoveryWalk_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace{ +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::TilePos; + +class InterruptingRouteIO : public GridSimRouteIO{ +public: + InterruptingRouteIO(GridSim& sim, std::vector& notes, + std::vector taps, size_t interrupted_holds) + : GridSimRouteIO(sim, notes, std::move(taps)), m_left(interrupted_holds) + {} + virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override{ + if (m_left > 0){ + m_left--; + return {.stop = WalkStop::LIMIT, .walked = 400ms, .wild_battles = 1}; + } + return GridSimRouteIO::walk_to_wall(walk); + } +private: + size_t m_left; +}; + +// Only walking is needed for this real LEGS step. Unexpected story actions +// fail the test. The actual RouteWalker executes through the GridSim RouteIO. +class RecoveryStepIO : public StoryStepIO{ +public: + explicit RecoveryStepIO(RouteIO& route) : m_route(route){} + virtual RouteIO& route() override{ return m_route; } + virtual void fight(const std::string&) override{ throw GridSimFailure{"unexpected trainer"}; } + virtual void walk_until_stopped(Direction, size_t, const std::string&) override{ throw GridSimFailure{"unexpected blind hold"}; } + virtual bool run_until_map(Direction, Milliseconds, const std::string&, const std::string&) override{ throw GridSimFailure{"unexpected banner walk"}; } + virtual bool run_into_door(Direction, bool, Milliseconds = Milliseconds(12000)) override{ throw GridSimFailure{"unexpected door"}; } + virtual std::optional tap_to_banner(Direction, const std::string&, size_t) override{ throw GridSimFailure{"unexpected banner"}; } + virtual void settle(Button, const std::string&, bool) override{ throw GridSimFailure{"unexpected scene"}; } +private: + RouteIO& m_route; +}; + +const Pokemon::StoryStep& mine_step(){ + for (const auto& row : story_checkpoints()){ + for (const auto& step : row.steps){ + if (row.id == "01.03" && step.name == "below_roark"){ + return step; + } + } + } + throw GridSimFailure{"missing native mine step"}; +} + +struct RecoveryInput{ + std::string name; + std::vector taps; + Direction direction = Direction::SOUTH; + size_t tiles = 5; + SimEncounterPhase phase = SimEncounterPhase::BEFORE_MOVEMENT; + WalkOrigin origin = WalkOrigin::CURRENT_LEG; + size_t interrupted_holds = 0; +}; +struct RecoveryExpectation{ + std::string failure = {}; + TilePos end = {.x = 18, .y = 29}; + Direction facing = Direction::WEST; +}; +struct RecoveryCase{ + RecoveryInput input; + RecoveryExpectation expectation; +}; + +class Test_RecoveryWalk : public UnitTest{ +public: + explicit Test_RecoveryWalk(RecoveryCase data) + : UnitTest("PokemonBDSP::AutoStory - Recovery walk: " + data.input.name), m_case(std::move(data)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const StoryWorld* world = story_plan_world("OreburghMine", "OreburghMine"); + if (world == nullptr){ + return "Missing native mine world."; + } + GridSim sim({.world = world}, world->to_world("OreburghMine", {15, 10}), Direction::SOUTH, true); + std::vector taps; + for (size_t tap : m_case.input.taps){ + taps.push_back({.label = "below_roark", .direction = m_case.input.direction, + .requested_tiles = m_case.input.tiles, .tap = tap, .phase = m_case.input.phase, .origin = m_case.input.origin}); + } + std::vector notes; + InterruptingRouteIO route(sim, notes, std::move(taps), m_case.input.interrupted_holds); + RecoveryStepIO io(route); + StoryWalkSteps walks(io); + walks.begin_attempt("01.03"); + Pokemon::RunState state{.pose = Pokemon::tile_pose("OreburghMine", {{15, 10}}, Direction::SOUTH), .flags = {}}; + std::string failure; + std::optional declared; + try{ + const auto outcome = walks.legs(state, mine_step()); + failure = outcome.failure; + declared = outcome.pose; + }catch (const GridSimFailure& error){ + failure = error.message; + } + if (!m_case.expectation.failure.empty()){ + return failure.find(m_case.expectation.failure) != std::string::npos ? UnitTestResult(true) + : UnitTestResult("Expected " + m_case.expectation.failure + ", got " + failure); + } + const auto end = story_to_local(*world, "OreburghMine", nearest_tile(sim.player().pos)); + if (!failure.empty() || !end || *end != m_case.expectation.end || !declared + || Pokemon::facing_of(*declared) != sim.player().facing || sim.player().facing != m_case.expectation.facing){ + return "Expected below Roark (18,29), got " + to_string(sim.player().pos) + ": " + failure; + } + return true; + } +private: + RecoveryCase m_case; +}; +} // namespace + +void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ + const RecoveryCase CASES[] = { + {.input = {.name = "uninterrupted native mine step", .taps = {}}, .expectation = {.failure = ""}}, + {.input = {.name = "last tap interrupted before movement", .taps = {5}}, .expectation = {.failure = ""}}, + {.input = {.name = "last tap completed before battle", .taps = {5}, .phase = SimEncounterPhase::AFTER_MOVEMENT}, .expectation = {.failure = ""}}, + {.input = {.name = "two interrupted advances, row 15", .taps = {4, 5}}, .expectation = {.failure = ""}}, + {.input = {.name = "last west leg recovers position and facing", .taps = {9}, .direction = Direction::WEST, .tiles = 9}, .expectation = {.failure = ""}}, + {.input = {.name = "repeat the interrupted recovery hold", .taps = {5}, .interrupted_holds = 1}, .expectation = {.failure = ""}}, + {.input = {.name = "recovery hold budget exhausted", .taps = {5}, .interrupted_holds = 10}, .expectation = {.failure = "recovery budget"}}, + {.input = {.name = "first input may belong to previous leg", .taps = {1}}, .expectation = {.failure = "encounter_origin_unknown"}}, + {.input = {.name = "late encounter origin unknown", .taps = {5}, .origin = WalkOrigin::MAY_PRECEDE_LEG}, .expectation = {.failure = "encounter_origin_unknown"}}, + }; + for (const RecoveryCase& scenario : CASES){ + database.add(scenario); + } +} +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h new file mode 100644 index 0000000000..9ee770013b --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h @@ -0,0 +1,15 @@ +/* BDSP Recovery Walk Tests + * From: https://github.com/PokemonAutomation/ + */ +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RecoveryWalk_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RecoveryWalk_Tests_H +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +// Register mine interruption, localization and bounded recovery scenarios. +void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database); +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp index 5e0f972700..5696886887 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp @@ -17,6 +17,7 @@ #include "Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "Data/PokemonBDSP_AutoStory_Maps.h" +#include "Simulation/PokemonBDSP_AutoStory_GridSim.h" #include "PokemonBDSP_AutoStory_RoutePlanner_Tests.h" namespace PokemonAutomation{ @@ -137,6 +138,47 @@ UnitTestResult test_plan_robust_route(Logger&){ } +// November 5 mine report: credited taps need not establish physical pose. +// The two phases are explicit diagnostics, not inferred console timing. +struct EncounterInput{ + std::string name; + SimEncounterPhase phase; +}; +struct EncounterExpectation{ + TilePos end; + size_t battles = 1; + size_t credited = 5; +}; +struct EncounterCase{ + EncounterInput input; + EncounterExpectation expectation; +}; +class Test_InterruptedMineTaps : public UnitTest{ +public: + explicit Test_InterruptedMineTaps(EncounterCase scenario) + : UnitTest("PokemonBDSP::AutoStory - Encounter credits: " + scenario.input.name), m_case(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + StoryWorld mine; + mine.add("OreburghMine", story_map("OreburghMine"), {0, 0}); + GridSim sim({.world = &mine}, {15, 12}, Direction::SOUTH, /*can_run=*/false); + std::vector notes; + GridSimRouteIO io(sim, notes, {{.label = "south", .direction = Direction::SOUTH, + .requested_tiles = 5, .tap = 5, .phase = m_case.input.phase}}); + const auto result = io.walk_taps(Direction::SOUTH, 5, "south"); + const auto& expected = m_case.expectation; + const TilePos actual = nearest_tile(sim.player().pos); + if (result.wild_battles != expected.battles || result.moved_chunks != expected.credited || actual != expected.end){ + return std::format("Expected {} battles, {} credits, tile {}; got {}, {}, {}.", + expected.battles, expected.credited, Pokemon::to_string(expected.end), + result.wild_battles, result.moved_chunks, Pokemon::to_string(actual)); + } + return true; + } +private: + EncounterCase m_case; +}; + // Empty map name selects a synthetic corridor: ####### / #.....# / #######. // Both possible starts (1,1)/(5,1) must share a safe wall ray. NPCs and // warps on that ray or its wall invalidate it; ordinary terrain is unchanged. @@ -268,6 +310,27 @@ class Test_RoutePlanner : public UnitTest{ RoutePlannerCase m_case; }; +const EncounterCase ENCOUNTER_CASES[] = { + {.input = {.name = "before movement", .phase = SimEncounterPhase::BEFORE_MOVEMENT}, + .expectation = {.end = {.x = 15, .y = 16}}}, + {.input = {.name = "after movement", .phase = SimEncounterPhase::AFTER_MOVEMENT}, + .expectation = {.end = {.x = 15, .y = 17}}}, +}; + +const RecoveryGeometryCase GEOMETRY_CASES[] = { + {.input = {.name = "mine rows converge south", .map = "OreburghMine", .from = {{15, 15}, {15, 16}, {15, 17}}}, + .expectation = {.anchor = TilePos{.x = 15, .y = 17}}}, + {.input = {.name = "r55 tiles converge east", .map = "Route202", .from = {{27, 5}, {26, 5}}}, + .expectation = {.anchor = TilePos{.x = 30, .y = 5}, .direction = Direction::EAST}}, + {.input = {.name = "wandering area is unsafe", .from = {{1, 1}, {5, 1}}, + .wander = Pokemon::TileBox{.x0 = 2, .y0 = 1, .x1 = 4, .y1 = 1}}, + .expectation = {.anchor = std::nullopt, .free_tile = TilePos{.x = 3, .y = 1}}}, + {.input = {.name = "warp crossings are unsafe", .from = {{1, 1}, {5, 1}}, .warps = {{3, 1}}}, + .expectation = {.anchor = std::nullopt}}, + {.input = {.name = "warps on blocked glyphs are unsafe", .from = {{1, 1}, {5, 1}}, .warps = {{0, 1}, {6, 1}}}, + .expectation = {.anchor = std::nullopt}}, +}; + } // namespace @@ -290,24 +353,13 @@ const RoutePlannerCase ROUTE_PLANNER_CASES[] = { }, }; -const RecoveryGeometryCase GEOMETRY_CASES[] = { - {.input = {.name = "mine rows converge south", .map = "OreburghMine", .from = {{15, 15}, {15, 16}, {15, 17}}}, - .expectation = {.anchor = TilePos{.x = 15, .y = 17}}}, - {.input = {.name = "r55 tiles converge east", .map = "Route202", .from = {{27, 5}, {26, 5}}}, - .expectation = {.anchor = TilePos{.x = 30, .y = 5}, .direction = Direction::EAST}}, - {.input = {.name = "wandering area is unsafe", .from = {{1, 1}, {5, 1}}, - .wander = Pokemon::TileBox{.x0 = 2, .y0 = 1, .x1 = 4, .y1 = 1}}, - .expectation = {.anchor = std::nullopt, .free_tile = TilePos{.x = 3, .y = 1}}}, - {.input = {.name = "warp crossings are unsafe", .from = {{1, 1}, {5, 1}}, .warps = {{3, 1}}}, - .expectation = {.anchor = std::nullopt}}, - {.input = {.name = "warps on blocked glyphs are unsafe", .from = {{1, 1}, {5, 1}}, .warps = {{0, 1}, {6, 1}}}, - .expectation = {.anchor = std::nullopt}}, -}; - void add_tests_AutoStory_RoutePlanner(UnitTestDatabase& database){ for (const auto& item : ROUTE_PLANNER_CASES){ database.add(item); } + for (const auto& scenario : ENCOUNTER_CASES){ + database.add(scenario); + } for (const auto& scenario : GEOMETRY_CASES){ database.add(scenario); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index dd4b1a0637..b3c0f54c72 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -19,9 +19,9 @@ #include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" -#include "PokemonBDSP_AutoStory_Talks.h" +#include "Actions/PokemonBDSP_AutoStory_Talks.h" #include "PokemonBDSP_AutoStory_Walks.h" -#include "PokemonBDSP_AutoStory_WildBattle.h" +#include "Actions/PokemonBDSP_AutoStory_WildBattle.h" #include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_StoryStepIO.h" @@ -99,9 +99,8 @@ void settle(VideoStream& stream, ProControllerContext& context, Button button, c // Holds the D-pad toward a door (with B after the shoes) until the screen goes // dark or a line shows, up to 12 s. Returns whether it went dark. A line -// stops it: holding on under Mom's "Oh, Kosmos!" wasted 12 s (r45). The walker's black-screen watch -// missed the lab's fade into Sandgem (r44, "dialog"), and settle's samples -// 1.3 s apart can fall either side of it, so watch at settle's own darkness. +// stops it: holding on under Mom's "Oh, Kosmos!" wasted 12 s (r45). A wild +// battle in a cave corridor runs away before returning. DpadPosition dpad_toward(Direction direction){ return direction == Direction::NORTH ? DPAD_UP : diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index e7af759fd5..bc5e52a530 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -10,6 +10,7 @@ #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Pokemon/Navigation/Pokemon_MapData.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP_AutoStory_StoryExecutor.h" @@ -118,12 +119,16 @@ Outcome StoryWalkSteps::leg_to_dialogue(const StoryStep& step){ const Pokemon::StoryLeg& leg = step.legs.front(); turn(leg.direction); const WalkResult walk = m_io.route().walk_taps(leg.direction, (size_t)leg.tiles, step.name); + if (walk.wild_battles > 0){ + return Pokemon::outcome_failed("interrupted_dialogue_approach", step.name); + } log(std::format("[{}] {}: taps {} to a dialogue: {} tiles, {}.", m_row, step.name, direction_name(leg.direction), walk.moved_chunks, walk_stop_name(walk.stop))); if (walk.stop == WalkStop::DIALOG){ return Pokemon::outcome_ok(); } - // A scene can lock us before its first line: Dawn walks over first (r37). - if (walk.stop == WalkStop::BLOCKED && m_io.route().dialog_within(10000ms, COLOR_CYAN)){ + // A scene can lock us before its first line: Dawn walks over first (r37), + // or Mom walks over to us on the mat (r7). + if (m_io.route().dialog_within(10000ms, COLOR_CYAN)){ return Pokemon::outcome_ok(); } return Pokemon::outcome_failed("no_dialogue", step.name); @@ -153,33 +158,76 @@ Outcome StoryWalkSteps::tap_to_banner(const StoryStep& step){ return Pokemon::outcome_ok(); } -// Each leg in D-pad taps, turning first; "one_short_ok" lets a leg end a -// tile short. +namespace{ +enum class CountedEndPolicy{ EXACT, ONE_SHORT }; +std::vector counted_ends(const std::vector& starts, const Pokemon::StoryLeg& leg, CountedEndPolicy policy){ + std::vector ends; + for (TilePos at : starts){ + for (int i = 0; i < leg.tiles; i++){ + if (policy == CountedEndPolicy::ONE_SHORT && i + 1 == leg.tiles){ + ends.push_back(at); + } + at = at.next(leg.direction); + } + ends.push_back(at); + } + return ends; +} +} // namespace + +Pose StoryWalkSteps::recover_tapped_leg(const Pose& from, const std::vector& starts, + const std::vector& goals, const Pokemon::StoryLeg& leg, const StoryStep& step){ + const StoryWorld* world = story_plan_world(from.map, from.map); + if (world == nullptr){ + fail(m_io.route(), "interrupted leg has no recovery world: " + from.map); + } + std::vector global; + for (const TilePos& at : starts){ + global.push_back(story_to_world(*world, from.map, at)); + } + std::vector possible; + for (const TilePos& at : interrupted_leg_positions(*world, global, leg.direction, (size_t)leg.tiles)){ + const auto local = story_to_local(*world, from.map, at); + if (!local){ + fail(m_io.route(), "interrupted leg crossed an unconfirmed map transition"); + } + possible.push_back(*local); + } + StoryStep recovery = step; + recovery.name += "_recovery"; + recovery.variant.clear(); + const Pose found = walk_to(Pokemon::tile_pose(from.map, possible), Pokemon::tile_pose(from.map, goals, leg.direction), recovery); + // The route back can approach from another direction. Establish the + // original leg's facing before publishing that pose to the story runner. + turn(leg.direction); + return found; +} + +// Counted legs retain their normal path. An observed encounter invalidates +// the exact pose; localize from every legal prefix before the next leg. Outcome StoryWalkSteps::tap_legs(const Pose& from, const StoryStep& step){ const bool one_short_ok = step.variant == "one_short_ok"; std::vector at = Pokemon::tiles_of(from); for (const Pokemon::StoryLeg& leg : step.legs){ - // Facing another way, a tap only turns (r256): turn first. turn(leg.direction); const size_t tiles = (size_t)leg.tiles; const WalkResult walk = m_io.route().walk_taps(leg.direction, tiles, step.name); log(std::format("[{}] {}: taps {} moved {} of {} tiles.", m_row, step.name, direction_name(leg.direction), walk.moved_chunks, tiles)); + const auto next = counted_ends(at, leg, one_short_ok ? CountedEndPolicy::ONE_SHORT : CountedEndPolicy::EXACT); + if (walk.wild_battles > 0){ + if (walk.origin == WalkOrigin::MAY_PRECEDE_LEG){ + return Pokemon::outcome_failed("encounter_origin_unknown", step.name); + } + if (walk.stop != WalkStop::LIMIT && walk.stop != WalkStop::BLOCKED){ + return Pokemon::outcome_failed("interrupted_leg_unconfirmed", step.name); + } + at = Pokemon::tiles_of(recover_tapped_leg(from, at, next, leg, step)); + continue; + } if (walk.moved_chunks + (one_short_ok ? 1 : 0) < tiles){ return Pokemon::outcome_failed("short_leg", std::format("{} {} moved {}", direction_name(leg.direction), tiles, walk.moved_chunks)); } - // Where we may be: the end, or a tile short of it. - std::vector next; - for (const TilePos& start : at){ - TilePos end = start; - for (size_t i = 0; i < tiles; i++){ - if (one_short_ok && i + 1 == tiles){ - next.push_back(end); - } - end = end.next(leg.direction); - } - next.push_back(end); - } - at = std::move(next); + at = next; } return Pokemon::outcome_ok(Pokemon::tile_pose(from.map, at, step.legs.back().direction)); } @@ -204,15 +252,26 @@ Outcome StoryWalkSteps::legs(RunState& state, const StoryStep& step){ } Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ - turn(step.direction); if (step.variant == "to_banner"){ + turn(step.direction); return tap_to_banner(step); } + if (step.variant == "tap"){ + // No separate turn tap first: at 1 tile from the door, a turn tap + // steps onto the warp, causing walk_taps to take an extra step on the far map. + const WalkResult walk = m_io.route().walk_taps(step.direction, 1, step.name); + if (walk.wild_battles > 0){ + return Pokemon::outcome_failed("interrupted_step", step.name); + } + m_io.settle(BUTTON_B, label_of(step), false); + return Pokemon::outcome_ok(); + } // A step through a door: walk (or run) on until the screen goes dark, // from next to the door or from anywhere in its line (r43: tapping 8 tiles // down the lab took 7 s), then settle for any scene on arrival (Mom's, // 00.01; Dawn's tour, 00.04). Without the fade, settle must see it itself - // (r33 was outside, "no fade"). + // (r33 was outside, "no fade"). No separate turn tap first: at 1 tile + // from the door, a 50 ms turn tap can step in before run_into_door() watches. if (step.pose_after && step.pose_after->map != state.pose.map){ Milliseconds timeout(12000); if (m_world.has(state.pose.map)){ @@ -228,7 +287,11 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ m_io.settle(BUTTON_B, label_of(step), !faded); return Pokemon::outcome_ok(); } + turn(step.direction); const WalkResult walk = m_io.route().walk_taps(step.direction, 1, step.name); + if (walk.wild_battles > 0){ + return Pokemon::outcome_failed("interrupted_step", step.name); + } log(std::format("[{}] {}: a step {}, {}.", m_row, step.name, direction_name(step.direction), walk_stop_name(walk.stop))); std::vector at; for (const TilePos& pos : Pokemon::tiles_of(state.pose)){ @@ -260,7 +323,8 @@ Outcome StoryWalkSteps::mash(RunState& state, const StoryStep& step){ m_io.route().note(label_of(step) + ": no line within 15 s; the step before played it.", RouteNote::WARNING); } m_io.settle(step.variant == "a" ? BUTTON_A : BUTTON_B, label_of(step), - step.pose_after && step.pose_after->map != state.pose.map); + step.pose_after && step.pose_after->map != state.pose.map && + story_plan_world(state.pose.map, step.pose_after->map) == nullptr); if (m_row == RUNNING_SHOES_ROW && step.name == RUNNING_SHOES_STEP){ m_can_run = true; } diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 2a32594b53..c352a899b2 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1733,6 +1733,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp From 9b1832c9a499638e9c5fafb53f42b66cd6a6d85f Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 16:52:25 -0800 Subject: [PATCH 014/166] Align SourceFiles.cmake with origin/bdsp/sim --- SerialPrograms/cmake/SourceFiles.cmake | 2 -- 1 file changed, 2 deletions(-) diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index d27300cf01..c352a899b2 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1723,8 +1723,6 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp - Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp From 22768f1448c317c8a8204f1b0996bbc53baad75b Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 16:54:01 -0800 Subject: [PATCH 015/166] Fix tiles_to_door map lookup in StoryWalkSteps --- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 25 ++++++++++++------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index bc5e52a530..ceef6d1a8b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -10,6 +10,7 @@ #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Pokemon/Navigation/Pokemon_MapData.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" @@ -159,6 +160,20 @@ Outcome StoryWalkSteps::tap_to_banner(const StoryStep& step){ } namespace{ +Milliseconds door_timeout(const std::string& map_name, const Pose& pose, Direction direction, bool can_run){ + try{ + const Pokemon::MapData& map = story_map(map_name); + const auto tiles_list = Pokemon::tiles_of(pose); + if (!tiles_list.empty()){ + const size_t tiles = Pokemon::tiles_to_door(map, tiles_list.front(), direction); + if (tiles > 0){ + const Milliseconds per_tile = route_ms_per_tile(direction, can_run ? MoveSpeed::RUN : MoveSpeed::WALK); + return std::max(1500ms, ROUTE_START_DELAY + per_tile * (int64_t)tiles + 800ms); + } + } + }catch (...){} + return Milliseconds(12000); +} enum class CountedEndPolicy{ EXACT, ONE_SHORT }; std::vector counted_ends(const std::vector& starts, const Pokemon::StoryLeg& leg, CountedEndPolicy policy){ std::vector ends; @@ -273,15 +288,7 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ // (r33 was outside, "no fade"). No separate turn tap first: at 1 tile // from the door, a 50 ms turn tap can step in before run_into_door() watches. if (step.pose_after && step.pose_after->map != state.pose.map){ - Milliseconds timeout(12000); - if (m_world.has(state.pose.map)){ - const Pokemon::MapData& map = m_world.map(state.pose.map); - const size_t tiles = Pokemon::tiles_to_door(map, state.pose.pos, step.direction); - if (tiles > 0){ - const Milliseconds per_tile = route_ms_per_tile(step.direction, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK); - timeout = std::max(1500ms, ROUTE_START_DELAY + per_tile * (int64_t)tiles + 800ms); - } - } + const Milliseconds timeout = door_timeout(state.pose.map, state.pose, step.direction, m_can_run); const bool faded = m_io.run_into_door(step.direction, m_can_run, timeout); log(std::format("[{}] {}: {} through the door (timeout {} ms): {}.", m_row, step.name, direction_name(step.direction), timeout.count(), faded ? "faded" : "no fade yet")); m_io.settle(BUTTON_B, label_of(step), !faded); From 9cbf90a93698090fb5ffa7f77d0472dd3a2d5009 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 16:54:43 -0800 Subject: [PATCH 016/166] Adopt origin/bdsp/sim StoryWalkSteps --- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 25 ++++++++++++------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index bc5e52a530..ceef6d1a8b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -10,6 +10,7 @@ #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Pokemon/Navigation/Pokemon_MapData.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" @@ -159,6 +160,20 @@ Outcome StoryWalkSteps::tap_to_banner(const StoryStep& step){ } namespace{ +Milliseconds door_timeout(const std::string& map_name, const Pose& pose, Direction direction, bool can_run){ + try{ + const Pokemon::MapData& map = story_map(map_name); + const auto tiles_list = Pokemon::tiles_of(pose); + if (!tiles_list.empty()){ + const size_t tiles = Pokemon::tiles_to_door(map, tiles_list.front(), direction); + if (tiles > 0){ + const Milliseconds per_tile = route_ms_per_tile(direction, can_run ? MoveSpeed::RUN : MoveSpeed::WALK); + return std::max(1500ms, ROUTE_START_DELAY + per_tile * (int64_t)tiles + 800ms); + } + } + }catch (...){} + return Milliseconds(12000); +} enum class CountedEndPolicy{ EXACT, ONE_SHORT }; std::vector counted_ends(const std::vector& starts, const Pokemon::StoryLeg& leg, CountedEndPolicy policy){ std::vector ends; @@ -273,15 +288,7 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ // (r33 was outside, "no fade"). No separate turn tap first: at 1 tile // from the door, a 50 ms turn tap can step in before run_into_door() watches. if (step.pose_after && step.pose_after->map != state.pose.map){ - Milliseconds timeout(12000); - if (m_world.has(state.pose.map)){ - const Pokemon::MapData& map = m_world.map(state.pose.map); - const size_t tiles = Pokemon::tiles_to_door(map, state.pose.pos, step.direction); - if (tiles > 0){ - const Milliseconds per_tile = route_ms_per_tile(step.direction, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK); - timeout = std::max(1500ms, ROUTE_START_DELAY + per_tile * (int64_t)tiles + 800ms); - } - } + const Milliseconds timeout = door_timeout(state.pose.map, state.pose, step.direction, m_can_run); const bool faded = m_io.run_into_door(step.direction, m_can_run, timeout); log(std::format("[{}] {}: {} through the door (timeout {} ms): {}.", m_row, step.name, direction_name(step.direction), timeout.count(), faded ? "faded" : "no fade yet")); m_io.settle(BUTTON_B, label_of(step), !faded); From 9a1bd0c9c6d6dbc9b463e8603062d2dcd83492e7 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 16:59:31 -0800 Subject: [PATCH 017/166] BDSP AutoStory sim: align RecoveryWalk test start position to north of corridor rock --- .../AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index fe28271410..e7436bcfe4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -97,7 +97,7 @@ class Test_RecoveryWalk : public UnitTest{ if (world == nullptr){ return "Missing native mine world."; } - GridSim sim({.world = world}, world->to_world("OreburghMine", {15, 10}), Direction::SOUTH, true); + GridSim sim({.world = world}, world->to_world("OreburghMine", {15, 9}), Direction::SOUTH, true); std::vector taps; for (size_t tap : m_case.input.taps){ taps.push_back({.label = "below_roark", .direction = m_case.input.direction, @@ -108,7 +108,7 @@ class Test_RecoveryWalk : public UnitTest{ RecoveryStepIO io(route); StoryWalkSteps walks(io); walks.begin_attempt("01.03"); - Pokemon::RunState state{.pose = Pokemon::tile_pose("OreburghMine", {{15, 10}}, Direction::SOUTH), .flags = {}}; + Pokemon::RunState state{.pose = Pokemon::tile_pose("OreburghMine", {{15, 9}}, Direction::SOUTH), .flags = {}}; std::string failure; std::optional declared; try{ From e6209f2129d15e29436224bd94a458f14afb816c Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 16:59:38 -0800 Subject: [PATCH 018/166] BDSP AutoStory: update 01.03 coal room leg counts for new map alignment --- .../AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 4 ++-- .../Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index fe28271410..e7436bcfe4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -97,7 +97,7 @@ class Test_RecoveryWalk : public UnitTest{ if (world == nullptr){ return "Missing native mine world."; } - GridSim sim({.world = world}, world->to_world("OreburghMine", {15, 10}), Direction::SOUTH, true); + GridSim sim({.world = world}, world->to_world("OreburghMine", {15, 9}), Direction::SOUTH, true); std::vector taps; for (size_t tap : m_case.input.taps){ taps.push_back({.label = "below_roark", .direction = m_case.input.direction, @@ -108,7 +108,7 @@ class Test_RecoveryWalk : public UnitTest{ RecoveryStepIO io(route); StoryWalkSteps walks(io); walks.begin_attempt("01.03"); - Pokemon::RunState state{.pose = Pokemon::tile_pose("OreburghMine", {{15, 10}}, Direction::SOUTH), .flags = {}}; + Pokemon::RunState state{.pose = Pokemon::tile_pose("OreburghMine", {{15, 9}}, Direction::SOUTH), .flags = {}}; std::string failure; std::optional declared; try{ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 7236bf15d7..53bc27acc3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -706,7 +706,7 @@ std::vector legs_below_roark(){ {.direction = EAST, .tiles = 14}, {.direction = SOUTH, .tiles = 10}, {.direction = WEST, .tiles = 2}, - {.direction = SOUTH, .tiles = 2}, + {.direction = SOUTH, .tiles = 3}, {.direction = WEST, .tiles = 9}, }; } @@ -714,7 +714,7 @@ std::vector legs_below_roark(){ std::vector legs_out_of_coal_room(){ return { {.direction = EAST, .tiles = 9}, - {.direction = NORTH, .tiles = 2}, + {.direction = NORTH, .tiles = 3}, {.direction = EAST, .tiles = 2}, {.direction = NORTH, .tiles = 10}, {.direction = WEST, .tiles = 14}, @@ -737,7 +737,7 @@ StoryCheckpoint oreburgh_mine_to_roark(){ step_into("into_the_mine", SOUTH, "the warp tile (46, 59)", at(MINE_HALL, 12, 1, SOUTH)), step_into("into_the_coal_room", SOUTH, "down the entrance hall through the cave mouth", at(MINE, 15, 2, SOUTH)), anchored(to_walls("south_to_the_rock", {{.direction = SOUTH, .tiles = 8}}, "south against the corridor rock (15, 11)"), - at(MINE, 15, 10, SOUTH)), + at(MINE, 15, 9, SOUTH)), anchored(legs("below_roark", legs_below_roark(), "east around rock, across room, down column 29, and west to below Roark"), below_roark), talk("roark", "Roark, north of us between his rocks"), scene("roark_smashes_the_rock", below_roark, "his lines, Rock Smash on the rock east of him, and he walks off"), From a8924e8000714dbc5fa13276c672eac7caf54581 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 17:01:51 -0800 Subject: [PATCH 019/166] BDSP AutoStory sim: declare recover_tapped_leg in StoryWalkSteps.h --- .../Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index fa89abaf14..c5b7493e78 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -51,6 +51,9 @@ class StoryWalkSteps{ private: Pokemon::Pose walk_to(const Pokemon::Pose& from, const Pokemon::Pose& goal, const Pokemon::StoryStep& step); + Pokemon::Pose recover_tapped_leg(const Pokemon::Pose& from, + const std::vector& starts, const std::vector& goals, + const Pokemon::StoryLeg& leg, const Pokemon::StoryStep& step); Pokemon::Outcome tap_legs(const Pokemon::Pose& from, const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_dialogue(const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_map(const Pokemon::StoryStep& step); From 9a2eb0a1176756d19144beef102a86953912bb39 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 20:02:45 -0800 Subject: [PATCH 020/166] BDSP AutoStory: avoid wandering NPC hazards and simulate wandering NPCs --- .../PokemonBDSP_AutoStory_CoordEvents.cpp | 14 +- .../Data/PokemonBDSP_AutoStory_StoryWorld.cpp | 34 ++++ .../Data/PokemonBDSP_AutoStory_StoryWorld.h | 4 + .../PokemonBDSP_AutoStory_StoryTable.cpp | 2 +- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 7 +- .../PokemonBDSP_AutoStory_GridSim.cpp | 87 +++++++++ .../PokemonBDSP_AutoStory_GridSim.h | 25 +++ .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 173 +++++++++++++++++- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 7 + 9 files changed, 348 insertions(+), 5 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp index c3fe3fea36..446ec4a4fd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp @@ -47,8 +47,18 @@ CoordEvent read_event(const JsonObject& object, const std::string& where){ .value = read_int(object, "value", where), .source = read_string(object, "source", where), }; - const int x = read_int(object, "x", where); - const int y = read_int(object, "y", where); + int x = 0; + int y = 0; + if (const JsonArray* coord = object.get_array("coord")){ + if (coord->size() < 2 || !(*coord)[0].is_integer() || !(*coord)[1].is_integer()){ + throw ParseException(where + "coord must have at least 2 integer elements."); + } + x = (int)(*coord)[0].to_integer_default(); + y = (int)(*coord)[1].to_integer_default(); + }else{ + x = read_int(object, "x", where); + y = read_int(object, "y", where); + } const int width = read_int(object, "width", where); const int length = read_int(object, "length", where); if (width < 1 || length < 1){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp index bf3fe46218..d983f7b7da 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp @@ -187,6 +187,40 @@ StoryWorld::Occupant StoryWorld::occupied(const TilePos& pos, OccupancyUse use) return found == nullptr ? NOBODY : found->occupant; } +namespace{ + +void add_box_tiles(std::vector& out, const TilePos& corner, const Pokemon::TileBox& box, int max_w, int max_h){ + const int y0 = std::max(0, box.y0); + const int y1 = std::min(max_h - 1, box.y1); + const int x0 = std::max(0, box.x0); + const int x1 = std::min(max_w - 1, box.x1); + for (int y = y0; y <= y1; y++){ + for (int x = x0; x <= x1; x++){ + out.push_back({corner.x + x, corner.y + y}); + } + } +} + +} // namespace + +std::vector wandering_hazards(const StoryWorld& world){ + std::vector result; + for (const auto& placed : world.m_maps){ + const TilePos corner{placed.offset.x - world.m_origin.x, placed.offset.y - world.m_origin.y}; + for (const auto& box : placed.wander){ + add_box_tiles(result, corner, box, placed.tiles.width, placed.tiles.height); + } + } + std::sort(result.begin(), result.end(), [](const TilePos& a, const TilePos& b){ + if (a.y != b.y){ + return a.y < b.y; + } + return a.x < b.x; + }); + result.erase(std::unique(result.begin(), result.end()), result.end()); + return result; +} + void StoryWorld::block(const TilePos& pos){ if (Cell* found = cell(pos)){ found->occupant = BLOCKED; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h index 751d9cd7bb..670380ecaa 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h @@ -71,6 +71,8 @@ class StoryWorld{ // The map that holds a world tile, or nothing between maps. std::optional to_local(const Pokemon::TilePos& world) const; + friend std::vector wandering_hazards(const StoryWorld& world); + private: struct Placed{ std::string name; @@ -106,6 +108,8 @@ class StoryWorld{ // The rules of walking on a story world, from its tiles. +// All tiles where someone wanders on the maps, in world coordinates. +std::vector wandering_hazards(const StoryWorld& world); // Whether a map holds this world tile. bool covered(const StoryWorld& world, const Pokemon::TilePos& pos); // Whether the player can stand on this tile. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 53bc27acc3..649caf9622 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -722,7 +722,7 @@ std::vector legs_out_of_coal_room(){ {.direction = EAST, .tiles = 1}, {.direction = NORTH, .tiles = 2}, {.direction = WEST, .tiles = 1}, - {.direction = NORTH, .tiles = 8}, + {.direction = NORTH, .tiles = 7}, }; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index ceef6d1a8b..d15c44b17d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -89,9 +89,14 @@ Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep sights, [this](const std::string& trainer){ m_io.fight(trainer); } }; + std::vector avoid = wandering_hazards(*maps); + std::erase_if(avoid, [&](const TilePos& pos){ + return std::find(start.begin(), start.end(), pos) != start.end() + || std::find(targets.begin(), targets.end(), pos) != targets.end(); + }); const RouteWalkPlan plan{ [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }, - label_of(step), {}, *costs, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK + label_of(step), std::move(avoid), *costs, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK }; const std::vector at = walk_route(m_io.route(), *maps, start, trainers, plan); sights = std::move(trainers.sights); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp index 286872a810..909766eb48 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -67,6 +67,11 @@ Milliseconds per_tile(Direction direction, SimPace pace, bool can_run){ return route_ms_per_tile(direction, pace == SimPace::RUN && can_run ? MoveSpeed::RUN : MoveSpeed::WALK); } +uint32_t step_rng(uint64_t& state){ + state = state * 6364136223846793005ULL + 1442695040888963407ULL; + return static_cast(state >> 32); +} + } // namespace @@ -102,14 +107,21 @@ const char* sim_stop_name(SimStop stop){ GridSim::GridSim(SimWorld world, const TilePos& start, Direction facing, bool can_run) : m_world(std::move(world)) + , m_wanderers(m_world.wanderers) { m_player.pos = sim_pos(start); m_player.facing = facing; m_player.can_run = can_run; + for (SimWanderer& wanderer : m_wanderers){ + if (wanderer.time_offset > 0ms){ + advance_wanderer(wanderer, wanderer.time_offset); + } + } } void GridSim::place(SimWorld world, const TilePos& start, std::optional facing){ m_world = std::move(world); + m_wanderers = m_world.wanderers; m_player.pos = sim_pos(start); if (facing){ m_player.facing = *facing; @@ -120,6 +132,68 @@ void GridSim::place(SimWorld world, const TilePos& start, std::optional 0ms){ + advance_wanderer(wanderer, wanderer.time_offset); + } + } +} + +bool GridSim::can_wander_to(const SimWanderer& wanderer, const TilePos& next) const{ + if (next.x < wanderer.box.x0 || next.x > wanderer.box.x1 || next.y < wanderer.box.y0 || next.y > wanderer.box.y1){ + return false; + } + if (!standable(*m_world.world, next) || m_world.world->occupied(next) != StoryWorld::NOBODY){ + return false; + } + if (nearest_tile(m_player.pos) == next){ + return false; + } + for (const SimWanderer& other : m_wanderers){ + if (&other != &wanderer && other.pos == next){ + return false; + } + } + return true; +} + +void GridSim::step_wanderer(SimWanderer& wanderer){ + const uint32_t choice = step_rng(wanderer.seed) % 5; + if (choice >= 4){ + return; + } + const Direction dir = static_cast(choice); + const TilePos next = wanderer.pos.next(dir); + if (can_wander_to(wanderer, next)){ + wanderer.pos = next; + } +} + +void GridSim::advance_wanderer(SimWanderer& wanderer, Milliseconds time){ + wanderer.elapsed += time; + while (wanderer.step_interval > 0ms && wanderer.elapsed >= wanderer.step_interval){ + wanderer.elapsed -= wanderer.step_interval; + step_wanderer(wanderer); + } +} + +void sim_advance_time(GridSim& sim, Milliseconds time){ + for (SimWanderer& wanderer : sim.m_wanderers){ + sim.advance_wanderer(wanderer, time); + } +} + +const std::vector& sim_wanderers(const GridSim& sim){ + return sim.m_wanderers; +} + +bool GridSim::wanderer_at(const TilePos& pos) const{ + for (const SimWanderer& wanderer : m_wanderers){ + if (wanderer.pos == pos){ + return true; + } + } + return false; } // Moves into the next tile toward `direction`, `part` of the way (a whole @@ -146,6 +220,11 @@ std::optional GridSim::enter_next(Direction direction, int part, int& m return SimStop::BLOCKED; } } + for (const TilePos& pos : ahead){ + if (wanderer_at(pos)){ + return SimStop::BLOCKED; + } + } // Off the grid, both tiles must be open: a door frame or a corner stops us. for (const TilePos& pos : ahead){ if (ahead.size() > 1 && !standable(world, pos)){ @@ -219,6 +298,7 @@ SimMove GridSim::tap(Direction direction, Milliseconds hold, bool stick){ if (!stick){ distance = std::max(1, (int)((hold + tile_time / 2) / tile_time)) * SIM_TILE; } + sim_advance_time(*this, hold); SimMove move = advance(direction, distance); move.time = hold; return move; @@ -230,6 +310,7 @@ SimMove GridSim::hold(Direction direction, Milliseconds limit, SimPace pace){ int moved = 0; SimStop stop = SimStop::LIMIT; while (moved < tiles * SIM_TILE){ + sim_advance_time(*this, tile_time); const SimMove step = advance(direction, SIM_TILE); moved += step.distance; if (step.stop != SimStop::DONE){ @@ -258,6 +339,11 @@ bool GridSim::press_a(){ m_player.trainer = trainer.name; } } + for (const SimWanderer& wanderer : m_wanderers){ + if (wanderer.pos == faced){ + m_player.dialog = true; + } + } return m_player.dialog; } @@ -367,6 +453,7 @@ void GridSimRouteIO::press(const RouteInput& input){ break; case RouteInputKind::WAIT: case RouteInputKind::PAUSE: + sim_advance_time(m_sim, input.hold * input.count); break; } } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h index 6457abf373..0535e3f043 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h @@ -70,12 +70,24 @@ struct SimTrigger{ // the tiles that warp like doors though the maps draw them as walls (a // house's stairs, entered from beside them); and, if the caller knows, // whether B runs from here on (the Running Shoes, 00.03). +// A person who wanders pseudo-randomly within their wander box. +struct SimWanderer{ + std::string name; + Pokemon::TileBox box; // wander boundary in world tiles + Pokemon::TilePos pos; // current position + uint64_t seed = 0; // PRNG seed for deterministic walk + Milliseconds step_interval = Milliseconds(2000); // how often the NPC attempts a move + Milliseconds elapsed = Milliseconds(0); // time accumulated towards next step + Milliseconds time_offset = Milliseconds(0); // initial start time offset +}; + struct SimWorld{ const StoryWorld* world = nullptr; std::vector trainers = {}; std::vector triggers = {}; std::vector doors = {}; std::optional can_run = std::nullopt; + std::vector wanderers = {}; }; // Reason why simulated player movement stopped. @@ -144,14 +156,27 @@ class GridSim{ } private: + friend void sim_advance_time(GridSim& sim, Milliseconds time); + friend const std::vector& sim_wanderers(const GridSim& sim); + SimMove advance(Pokemon::Direction direction, int distance); std::optional enter_next(Pokemon::Direction direction, int part, int& moved); std::optional arrive(); + void advance_wanderer(SimWanderer& wanderer, Milliseconds time); + void step_wanderer(SimWanderer& wanderer); + bool can_wander_to(const SimWanderer& wanderer, const Pokemon::TilePos& next) const; + bool wanderer_at(const Pokemon::TilePos& pos) const; SimWorld m_world; SimPlayer m_player; + std::vector m_wanderers; }; +// Advances simulated time for world events and wandering NPCs. +void sim_advance_time(GridSim& sim, Milliseconds time); +// The wandering NPCs on the simulation's world. +const std::vector& sim_wanderers(const GridSim& sim); + // Whether the player could take a step toward `direction` from where they stand. bool sim_can_step(const GridSim& sim, Pokemon::Direction direction); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 8030c8d0be..5762abc21a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -39,6 +39,7 @@ using Pokemon::Direction; using Pokemon::Pose; using Pokemon::StoryStep; using Pokemon::StoryStepKind; +using Pokemon::TileBox; using Pokemon::TilePos; @@ -210,11 +211,16 @@ SimWalk walk_on_sim(const SimRoute& route, bool stick_turns){ RouteIO& io = stick_turns ? static_cast(stick_io) : sim_io; RouteTrainers trainers{story_trainers(*route.world), [&sim](const std::string&){ sim.end_dialogue(); }}; const std::vector& targets = route.targets; + std::vector avoid = wandering_hazards(*route.world); + std::erase_if(avoid, [&](const TilePos& pos){ + return std::find(route.from.begin(), route.from.end(), pos) != route.from.end() + || std::find(targets.begin(), targets.end(), pos) != targets.end(); + }); try{ out.believed = walk_route(io, *route.world, route.from, trainers, { .goal = [&targets](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }, .label = route.label, - .avoid = {}, + .avoid = std::move(avoid), .costs = route.costs, .speed = route.can_run ? MoveSpeed::RUN : MoveSpeed::WALK, }); @@ -384,6 +390,155 @@ UnitTestResult test_door_routes(Logger& logger){ } + +UnitTestResult test_wandering_npc_mechanics(Logger& logger){ + StoryWorld world = make_world({ + "#######", + "#.....#", + "#.....#", + "#.....#", + "#######", + }); + SimWanderer wanderer{ + .name = "wanderer", + .box = {1, 1, 3, 3}, + .pos = {2, 2}, + .seed = 42, + .step_interval = 2000ms, + }; + GridSim sim({.world = &world, .wanderers = {wanderer}}, {1, 2}, Direction::EAST, false); + sim_advance_time(sim, 100000ms); + const SimWanderer& after = sim_wanderers(sim).front(); + if (after.pos.x < 1 || after.pos.x > 3 || after.pos.y < 1 || after.pos.y > 3){ + return "wanderer stepped outside its bounding box"; + } + GridSim sim2({.world = &world, .wanderers = {wanderer}}, {1, 2}, Direction::EAST, false); + sim_advance_time(sim2, 100000ms); + if (sim_wanderers(sim2).front().pos != after.pos){ + return "wanderer simulation is not deterministic across identical seeds"; + } + return true; +} + +UnitTestResult test_wandering_npc_collision_and_dialog(Logger& logger){ + StoryWorld world = make_world({ + "#####", + "#...#", + "#####", + }); + SimWanderer wanderer{ + .name = "blocker", + .box = {2, 1, 2, 1}, + .pos = {2, 1}, + .seed = 0, + .step_interval = 10000ms, + }; + GridSim sim({.world = &world, .wanderers = {wanderer}}, {1, 1}, Direction::EAST, false); + const SimMove move = sim.tap(Direction::EAST, 160ms, false); + if (move.stop != SimStop::BLOCKED || sim.player().pos != sim_pos({1, 1})){ + return "player was not blocked by wandering NPC"; + } + if (!sim.press_a()){ + return "pressing A facing wandering NPC failed to open dialogue"; + } + return true; +} + +UnitTestResult test_wandering_npc_routes_multi_seed(Logger& logger){ + const StoryWorld* world = story_plan_world("OreburghCity", "OreburghCity"); + if (world == nullptr){ + return "OreburghCity world not found"; + } + const TilePos start = story_to_world(*world, "OreburghCity", {26, 22}); + const TilePos target = story_to_world(*world, "OreburghCity", {46, 58}); + const TileBox hiker_box{ + story_to_world(*world, "OreburghCity", {46, 25}).x, + story_to_world(*world, "OreburghCity", {46, 25}).y, + story_to_world(*world, "OreburghCity", {48, 27}).x, + story_to_world(*world, "OreburghCity", {48, 27}).y + }; + const TilePos hiker_home = story_to_world(*world, "OreburghCity", {47, 26}); + const std::vector seeds = {0, 1, 2, 7, 42, 100, 999, 1337}; + const std::vector start_times = {0ms, 500ms, 1200ms, 2000ms, 3500ms, 5000ms}; + std::vector avoid = wandering_hazards(*world); + std::erase_if(avoid, [&](const TilePos& pos){ + return pos == start || pos == target; + }); + for (uint64_t seed : seeds){ + for (Milliseconds start_time : start_times){ + SimWanderer hiker{ + .name = "hiker_0", + .box = hiker_box, + .pos = hiker_home, + .seed = seed, + .step_interval = 2000ms, + .time_offset = start_time, + }; + GridSim sim({.world = world, .trainers = story_trainers(*world), .wanderers = {hiker}}, start, Direction::NORTH, true); + std::vector notes; + GridSimRouteIO sim_io(sim, notes); + RouteTrainers trainers{story_trainers(*world), [&sim](const std::string&){ sim.end_dialogue(); }}; + const auto result = walk_route(sim_io, *world, {start}, trainers, { + .goal = [&](const TilePos& pos){ return pos == target; }, + .label = "01.03 above_the_mine", + .avoid = avoid, + .costs = *story_route_costs("town"), + .speed = MoveSpeed::RUN, + }); + if (result.empty() || result.front() != target || nearest_tile(sim.player().pos) != target){ + return std::format("route failed for seed {} and start_time {} ms", seed, start_time.count()); + } + } + } + return true; +} + +UnitTestResult test_wandering_npc_wait_clearance(Logger& logger){ + const StoryWorld* world = story_plan_world("OreburghCity", "OreburghCity"); + if (world == nullptr){ + return "OreburghCity world not found"; + } + const TilePos start = story_to_world(*world, "OreburghCity", {48, 22}); + const TilePos target = story_to_world(*world, "OreburghCity", {48, 30}); + const TileBox hiker_box{ + story_to_world(*world, "OreburghCity", {46, 25}).x, + story_to_world(*world, "OreburghCity", {46, 25}).y, + story_to_world(*world, "OreburghCity", {48, 27}).x, + story_to_world(*world, "OreburghCity", {48, 27}).y + }; + SimWanderer hiker{ + .name = "hiker_0", + .box = hiker_box, + .pos = story_to_world(*world, "OreburghCity", {48, 26}), + .seed = 2, + .step_interval = 2000ms, + }; + GridSim sim({.world = world, .trainers = story_trainers(*world), .wanderers = {hiker}}, start, Direction::NORTH, true); + std::vector notes; + GridSimRouteIO sim_io(sim, notes); + RouteTrainers trainers{story_trainers(*world), [&sim](const std::string&){ sim.end_dialogue(); }}; + const auto result = walk_route(sim_io, *world, {start}, trainers, { + .goal = [&](const TilePos& pos){ return pos == target; }, + .label = "walk_through_hiker", + .avoid = {}, + .costs = *story_route_costs("town"), + .speed = MoveSpeed::RUN, + }); + if (result.empty() || result.front() != target){ + return "wait clearance route did not reach target"; + } + bool saw_blocked_note = false; + for (const std::string& n : notes){ + if (n.find("waiting for the way to clear") != std::string::npos){ + saw_blocked_note = true; + break; + } + } + if (!saw_blocked_note){ + return "expected route to encounter blocked wanderer and wait for clearance"; + } + return true; +} struct AutoStoryGridSimInput{ std::string name; std::function body; @@ -431,6 +586,22 @@ const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { .input = {"a stick-tap turn misses the Sandgem Center and Jubilife School doors", test_door_routes}, .expectation = {}, }, + { + .input = {"wandering NPC movement and deterministic seed behavior", test_wandering_npc_mechanics}, + .expectation = {}, + }, + { + .input = {"wandering NPC collision stops player and opens dialogue", test_wandering_npc_collision_and_dialog}, + .expectation = {}, + }, + { + .input = {"01.03 above_the_mine detours around wanderer across seeds and start times", test_wandering_npc_routes_multi_seed}, + .expectation = {}, + }, + { + .input = {"wandering NPC collision without avoid waits for clearance and resumes", test_wandering_npc_wait_clearance}, + .expectation = {}, + }, }; void add_tests_AutoStory_GridSim(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index 0d5f55b236..d3f3ff875b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -298,6 +298,13 @@ std::vector RouteWalker::plan_legs() const{ "; trying the default costs.", RouteNote::WARNING); legs = plan_recovered_route(m_grid, m_from, m_plan.goal, RobustPlanCosts()); } + if (!legs && !m_plan.avoid.empty()){ + m_io.note("[Route] " + m_plan.label + ": no plan avoiding hazard tiles; trying without hazard avoidance.", RouteNote::WARNING); + legs = plan_recovered_route(m_maps, m_from, m_plan.goal, m_plan.costs); + if (!legs){ + legs = plan_recovered_route(m_maps, m_from, m_plan.goal, RobustPlanCosts()); + } + } if (!legs){ fail(m_io, m_plan.label + ": no plan from " + describe(m_maps, m_from) + "."); } From 5a1626885c2752be78974bacf98e27aecb88c129 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 21:49:31 -0800 Subject: [PATCH 021/166] BDSP AutoStory: soft cost penalty for wandering hazards and wall check safeguard - StoryWorld: add wander_hazard tracking and wandering_hazard(world, pos) helper to distinguish wandering areas from impassable walls. - RoutePlanner: add per_wander_tile = 3 penalty to TilePlanCosts so paths through wander boxes are preferred over long detours while still favoring open streets when distances are equal. - StoryWalkSteps: do not pass wandering hazard boxes into plan.avoid, preventing RouteWalker from uncovering and severing main thoroughfares such as Oreburgh City column 46. - Walk: raise WALK_BLOCKED_CHANGE to 16.0 to detect running in place against obstacles and wandering NPCs rather than running to timeout. - PlannedRoute: bound tiles_moved when stop == WalkStop::LIMIT by moved_chunks, and add distance safeguard in check_at_wall requiring at least 70% of expected distance traversed before verifying arrival. - GridSim_Tests: add multi-seed test for Oreburgh City north route, test custom map check_at_wall safeguard against stalled legs, and update above_the_mine test to path through wander zones. --- .../PokemonBDSP_AutoStory_RoutePlanner.cpp | 17 ++- .../Data/PokemonBDSP_AutoStory_RoutePlanner.h | 1 + .../Data/PokemonBDSP_AutoStory_StoryWorld.cpp | 14 ++- .../Data/PokemonBDSP_AutoStory_StoryWorld.h | 7 ++ .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 7 +- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 113 +++++++++++++++++- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 19 ++- .../Utils/PokemonBDSP_AutoStory_Walk.h | 2 +- 8 files changed, 161 insertions(+), 19 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp index e721e439c3..184549ce82 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp @@ -83,6 +83,9 @@ class StoryWorldModel{ if (tall_grass(m_world, *next)){ step.extra_cost += m_costs.per_grass_tile; } + if (wandering_hazard(m_world, *next)){ + step.extra_cost += m_costs.per_wander_tile; + } return step; } bool held_at(const State& pos, Direction direction) const{ @@ -218,6 +221,7 @@ namespace{ struct Stepped{ TilePos end; int grass = 0; + int wander = 0; }; std::optional step_tiles(const StoryWorld& world, TilePos from, Direction direction, int tiles){ Stepped stepped; @@ -234,6 +238,9 @@ std::optional step_tiles(const StoryWorld& world, TilePos from, Directi if (tall_grass(world, *next)){ stepped.grass++; } + if (wandering_hazard(world, *next)){ + stepped.wander++; + } from = *next; } stepped.end = from; @@ -268,6 +275,7 @@ std::optional to_wall_leg(const StoryWorld& world, const Spread& spre Expansion expansion; size_t longest = 0; int grass = 0; + int wander = 0; for (const TilePos& pos : spread){ const WallHit hit = slide_to_wall(world, pos, direction); if (!hit.anchored){ @@ -275,6 +283,7 @@ std::optional to_wall_leg(const StoryWorld& world, const Spread& spre } if (const std::optional stepped = step_tiles(world, pos, direction, (int)hit.tiles)){ grass = std::max(grass, stepped->grass); + wander = std::max(wander, stepped->wander); } longest = std::max(longest, hit.tiles); expansion.next.push_back(hit.stop); @@ -282,7 +291,8 @@ std::optional to_wall_leg(const StoryWorld& world, const Spread& spre if (longest == 0){ return std::nullopt; } - expansion.cost = (long long)costs.per_leg + (long long)costs.per_tile * longest + (long long)costs.per_grass_tile * grass; + expansion.cost = (long long)costs.per_leg + (long long)costs.per_tile * longest + + (long long)costs.per_grass_tile * grass + (long long)costs.per_wander_tile * wander; expansion.leg = TileLeg{direction, longest, true}; return expansion; } @@ -292,6 +302,7 @@ std::optional to_wall_leg(const StoryWorld& world, const Spread& spre std::optional open_leg(const StoryWorld& world, const Spread& spread, Direction direction, int tiles, const RobustPlanCosts& costs){ Expansion expansion; int grass = 0; + int wander = 0; const int error = tiles <= costs.exact_open_tiles ? 0 : costs.open_error + tiles / costs.open_error_per; for (const TilePos& pos : spread){ for (int n = std::max(1, tiles - error); n <= tiles + error; n++){ @@ -300,11 +311,13 @@ std::optional open_leg(const StoryWorld& world, const Spread& spread, return std::nullopt; } grass = std::max(grass, stepped->grass); + wander = std::max(wander, stepped->wander); expansion.next.push_back(stepped->end); } } expansion.cost = (long long)costs.per_leg + costs.leg_not_at_wall + - (long long)(costs.per_tile + costs.per_open_tile) * tiles + (long long)costs.per_grass_tile * grass; + (long long)(costs.per_tile + costs.per_open_tile) * tiles + + (long long)costs.per_grass_tile * grass + (long long)costs.per_wander_tile * wander; expansion.leg = TileLeg{direction, (size_t)tiles, false}; return expansion; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h index a8660a078f..2376e8e59b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h @@ -49,6 +49,7 @@ std::string to_string(const TileLeg& leg); struct TilePlanCosts{ int per_tile = 1; int per_grass_tile = 4; // extra for each tall-grass tile entered + int per_wander_tile = 3; // extra for each wander hazard tile entered int per_leg = 8; int leg_not_at_wall = 50; // extra for a leg that stops in the open }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp index d983f7b7da..fb9e7a89f5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp @@ -146,7 +146,9 @@ void StoryWorld::paint(const Placed& placed, const TilePos& corner){ for (const auto& box : placed.wander){ for (int y = std::max(0, box.y0); y <= std::min(placed.tiles.height - 1, box.y1); y++){ for (int x = std::max(0, box.x0); x <= std::min(placed.tiles.width - 1, box.x1); x++){ - Pokemon::cell_at(m_cells, {corner.x + x, corner.y + y}).recovery_hazard = true; + Cell& c = Pokemon::cell_at(m_cells, {corner.x + x, corner.y + y}); + c.recovery_hazard = true; + c.wander_hazard = true; } } } @@ -221,6 +223,16 @@ std::vector wandering_hazards(const StoryWorld& world){ return result; } +bool wandering_hazard(const StoryWorld& world, const TilePos& pos){ + const StoryWorld::Cell* found = world.cell(pos); + return found != nullptr && found->wander_hazard; +} + +bool recovery_hazard(const StoryWorld& world, const TilePos& pos){ + const StoryWorld::Cell* found = world.cell(pos); + return found != nullptr && found->recovery_hazard; +} + void StoryWorld::block(const TilePos& pos){ if (Cell* found = cell(pos)){ found->occupant = BLOCKED; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h index 670380ecaa..9cf790e24f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h @@ -72,6 +72,8 @@ class StoryWorld{ std::optional to_local(const Pokemon::TilePos& world) const; friend std::vector wandering_hazards(const StoryWorld& world); + friend bool wandering_hazard(const StoryWorld& world, const Pokemon::TilePos& pos); + friend bool recovery_hazard(const StoryWorld& world, const Pokemon::TilePos& pos); private: struct Placed{ @@ -87,6 +89,7 @@ class StoryWorld{ Pokemon::TileKind tile = Pokemon::TileKind::WALL; Occupant occupant = NOBODY; bool recovery_hazard = false; + bool wander_hazard = false; }; void check_overlap(const Placed& map) const; @@ -110,6 +113,10 @@ class StoryWorld{ // All tiles where someone wanders on the maps, in world coordinates. std::vector wandering_hazards(const StoryWorld& world); +// Whether a world tile is within a wandering hazard box. +bool wandering_hazard(const StoryWorld& world, const Pokemon::TilePos& pos); +// Whether a world tile is a recovery hazard (wander box or warp). +bool recovery_hazard(const StoryWorld& world, const Pokemon::TilePos& pos); // Whether a map holds this world tile. bool covered(const StoryWorld& world, const Pokemon::TilePos& pos); // Whether the player can stand on this tile. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index d15c44b17d..ceef6d1a8b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -89,14 +89,9 @@ Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep sights, [this](const std::string& trainer){ m_io.fight(trainer); } }; - std::vector avoid = wandering_hazards(*maps); - std::erase_if(avoid, [&](const TilePos& pos){ - return std::find(start.begin(), start.end(), pos) != start.end() - || std::find(targets.begin(), targets.end(), pos) != targets.end(); - }); const RouteWalkPlan plan{ [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }, - label_of(step), std::move(avoid), *costs, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK + label_of(step), {}, *costs, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK }; const std::vector at = walk_route(m_io.route(), *maps, start, trainers, plan); sights = std::move(trainers.sights); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 5762abc21a..3fa4af63fe 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -460,10 +460,6 @@ UnitTestResult test_wandering_npc_routes_multi_seed(Logger& logger){ const TilePos hiker_home = story_to_world(*world, "OreburghCity", {47, 26}); const std::vector seeds = {0, 1, 2, 7, 42, 100, 999, 1337}; const std::vector start_times = {0ms, 500ms, 1200ms, 2000ms, 3500ms, 5000ms}; - std::vector avoid = wandering_hazards(*world); - std::erase_if(avoid, [&](const TilePos& pos){ - return pos == start || pos == target; - }); for (uint64_t seed : seeds){ for (Milliseconds start_time : start_times){ SimWanderer hiker{ @@ -481,7 +477,7 @@ UnitTestResult test_wandering_npc_routes_multi_seed(Logger& logger){ const auto result = walk_route(sim_io, *world, {start}, trainers, { .goal = [&](const TilePos& pos){ return pos == target; }, .label = "01.03 above_the_mine", - .avoid = avoid, + .avoid = {}, .costs = *story_route_costs("town"), .speed = MoveSpeed::RUN, }); @@ -539,6 +535,103 @@ UnitTestResult test_wandering_npc_wait_clearance(Logger& logger){ } return true; } + +UnitTestResult test_wandering_npc_oreburgh_north_multi_seed(Logger& logger){ + const StoryWorld* world = story_plan_world("OreburghCity", "OreburghCity"); + if (world == nullptr){ + return "OreburghCity world not found"; + } + const TilePos start = story_to_world(*world, "OreburghCity", {46, 52}); + const TilePos target = story_to_world(*world, "OreburghCity", {46, 21}); + const TileBox hiker_box{ + story_to_world(*world, "OreburghCity", {46, 25}).x, + story_to_world(*world, "OreburghCity", {46, 25}).y, + story_to_world(*world, "OreburghCity", {48, 27}).x, + story_to_world(*world, "OreburghCity", {48, 27}).y + }; + const TilePos hiker_home = story_to_world(*world, "OreburghCity", {47, 26}); + const std::vector seeds = {0, 1, 2, 7, 42, 100, 999, 1337}; + const std::vector start_times = {0ms, 500ms, 1200ms, 2000ms, 3500ms, 5000ms}; + for (uint64_t seed : seeds){ + for (Milliseconds start_time : start_times){ + SimWanderer hiker{ + .name = "hiker_0", + .box = hiker_box, + .pos = hiker_home, + .seed = seed, + .step_interval = 2000ms, + .time_offset = start_time, + }; + GridSim sim({.world = world, .trainers = story_trainers(*world), .wanderers = {hiker}}, start, Direction::NORTH, true); + std::vector notes; + GridSimRouteIO sim_io(sim, notes); + RouteTrainers trainers{story_trainers(*world), [&sim](const std::string&){ sim.end_dialogue(); }}; + const auto result = walk_route(sim_io, *world, {start}, trainers, { + .goal = [&](const TilePos& pos){ return pos == target; }, + .label = "01.03 oreburgh_north", + .avoid = {}, + .costs = *story_route_costs("town"), + .speed = MoveSpeed::RUN, + }); + if (result.empty() || result.front() != target || nearest_tile(sim.player().pos) != target){ + return std::format("oreburgh north route failed for seed {} and start_time {} ms", seed, start_time.count()); + } + } + } + return true; +} + +class StalledWallLegRouteIO : public GridSimRouteIO{ +public: + StalledWallLegRouteIO(GridSim& sim, std::vector& notes) + : GridSimRouteIO(sim, notes) + {} + + virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override{ + if (m_first_wall_call){ + m_first_wall_call = false; + return WalkResult{ + .stop = WalkStop::LIMIT, + .walked = 5000ms, + .wild_battles = 0, + .moved_chunks = 2, + }; + } + return GridSimRouteIO::walk_to_wall(walk); + } + +private: + bool m_first_wall_call = true; +}; + +UnitTestResult test_wall_leg_check_at_wall_short_distance_safeguard(Logger& logger){ + StoryWorld world = make_world({ + "########################", + "#......................#", + "########################", + }); + const TilePos start{1, 1}; + const TilePos target{22, 1}; + GridSim sim({.world = &world}, start, Direction::EAST, true); + std::vector notes; + StalledWallLegRouteIO sim_io(sim, notes); + RouteTrainers trainers{{}, [](const std::string&){}}; + try{ + walk_route(sim_io, world, {start}, trainers, { + .goal = [&](const TilePos& pos){ return pos == target; }, + .label = "test_check_at_wall_safeguard", + .avoid = {}, + .costs = *story_route_costs("town"), + .speed = MoveSpeed::RUN, + }); + return "check_at_wall falsely accepted leg stalled well short of expected distance"; + }catch (const GridSimFailure& f){ + if (f.message.find("short of the wall") != std::string::npos){ + return true; + } + return "caught unexpected failure: " + f.message; + } +} struct AutoStoryGridSimInput{ std::string name; std::function body; @@ -595,13 +688,21 @@ const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { .expectation = {}, }, { - .input = {"01.03 above_the_mine detours around wanderer across seeds and start times", test_wandering_npc_routes_multi_seed}, + .input = {"01.03 above_the_mine paths through wanderer zone across seeds and start times", test_wandering_npc_routes_multi_seed}, .expectation = {}, }, { .input = {"wandering NPC collision without avoid waits for clearance and resumes", test_wandering_npc_wait_clearance}, .expectation = {}, }, + { + .input = {"01.03 oreburgh_north paths straight up column 46 across seeds and start times", test_wandering_npc_oreburgh_north_multi_seed}, + .expectation = {}, + }, + { + .input = {"check_at_wall safeguard rejects legs stalled well short of expected distance", test_wall_leg_check_at_wall_short_distance_safeguard}, + .expectation = {}, + }, }; void add_tests_AutoStory_GridSim(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index d3f3ff875b..cf02a9920e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -154,6 +154,12 @@ constexpr RouteInput WAIT_FOR_THE_WAY{.kind = RouteInputKind::WAIT, .direction = // Tiles a walk to the wall moved, from the time it walked. size_t tiles_moved(const WalkResult& walk, Milliseconds per_tile){ + if (walk.stop == WalkStop::LIMIT && walk.moved_chunks > 0){ + const Milliseconds moving = walk.walked - ROUTE_START_DELAY; + const size_t tiles_from_time = moving.count() <= 0 ? (size_t)0 : (size_t)(moving / per_tile); + const size_t tiles_from_chunks = (walk.moved_chunks * 400ms) / per_tile; + return std::min(tiles_from_time, std::max(walk.moved_chunks, tiles_from_chunks)); + } const Milliseconds moving = walk.walked - ROUTE_START_DELAY - (walk.stop == WalkStop::BLOCKED ? 800ms : 0ms); return moving.count() <= 0 ? (size_t)0 : (size_t)(moving / per_tile); @@ -226,7 +232,7 @@ class RouteWalker{ bool finish_interrupted_wall(LegWalk& walk, Milliseconds limit); size_t unstick_wall_leg(LegWalk& walk, size_t walked_tiles, size_t nearest); LegNext stopped_short_of_wall(LegWalk& walk, size_t walked_tiles); - void check_at_wall(LegWalk& walk); + void check_at_wall(LegWalk& walk, size_t walked_tiles = SIZE_MAX, size_t expected_tiles = SIZE_MAX); void on_to_wall(LegWalk& walk); // Open legs, tapped. @@ -402,7 +408,7 @@ LegNext RouteWalker::wall_leg(LegWalk& walk){ // into the lab). Out of tall grass a stop reads, so walk on: a player // still moving is not where the plan has him. if (walk.result.stop == WalkStop::LIMIT && route_wall_readable(m_grid, walk.planned.after)){ - check_at_wall(walk); + check_at_wall(walk, walked_tiles, nearest); } return LegNext::NEXT_LEG; } @@ -479,7 +485,14 @@ LegNext RouteWalker::stopped_short_of_wall(LegWalk& walk, size_t walked_tiles){ return replan_from(walk, std::move(stopped), "stopped early after about " + std::to_string(walked_tiles) + " tiles"); } -void RouteWalker::check_at_wall(LegWalk& walk){ +void RouteWalker::check_at_wall(LegWalk& walk, size_t walked_tiles, size_t expected_tiles){ + if (expected_tiles != SIZE_MAX && expected_tiles > 0 && walked_tiles != SIZE_MAX){ + const size_t min_tiles = expected_tiles > 3 ? (expected_tiles * 7 / 10) : (expected_tiles > 1 ? expected_tiles - 1 : 1); + if (walked_tiles < min_tiles){ + fail(m_io, walk.label + ": ran out of time well short of the wall (" + + std::to_string(walked_tiles) + " of " + std::to_string(expected_tiles) + " tiles): not where the plan has us."); + } + } WalkResult check = m_io.walk_to_wall({.direction = walk.planned.leg.direction, .limit = 2000ms, .label = walk.label + ": at the wall?", .options = {.arrived = nullptr, .pace = DpadPace::RUN}}); if (check.stop == WalkStop::DIALOG){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h index ae33d766d7..0d3d5f6b7a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h @@ -160,7 +160,7 @@ WalkResult walk_to_talk( // place against trees. double walk_screen_change(const ImageViewRGB32& before, const ImageViewRGB32& after); // Screen change metric threshold indicative of blocked movement against an obstacle. -constexpr double WALK_BLOCKED_CHANGE = 10.0; +constexpr double WALK_BLOCKED_CHANGE = 16.0; // For whole-tile D-pad taps: a tap that moves changes the screen by 21 to 50 // (r244a: 40 per tap along Route 204's row 27); a tap into a wall or an NPC // bumps for 10 to 13.4, and an NPC walking past does the same, so 10 counted From f9d253be4ef51cb795f01029489f96c4f1dafb68 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 22:13:13 -0800 Subject: [PATCH 022/166] BDSP AutoStory: tag late encounter origin unknown only when chunks moved <= 1 --- .../Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp index 9050540834..a7e896f3cd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp @@ -383,7 +383,9 @@ class WalkUntil{ ){ m_result.wild_battles++; late_battle = true; - m_result.origin = WalkOrigin::MAY_PRECEDE_LEG; + if (m_chunks <= 1 && m_result.moved_chunks <= 1){ + m_result.origin = WalkOrigin::MAY_PRECEDE_LEG; + } } // When the final tap of a TAPS leg lagged during frame drops at its // 800ms check (m_unchanged == 1 at WalkStop::LIMIT), it finishes From a0d22048d4738b8248a709288ed2cbf572821874 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sat, 7 Nov 2026 22:23:02 -0800 Subject: [PATCH 023/166] BDSP walk: do not mark origin as preceding leg when movement moved chunks --- .../AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp index a7e896f3cd..fdc6357556 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp @@ -298,7 +298,7 @@ class WalkUntil{ return {ChunkNext::STOP, WalkStop::DIALOG}; } if (battle){ - escape_battle("wild battle; running."); + escape_battle("wild battle; running.", BattleMovement::NONE); return {ChunkNext::NEXT_CHUNK, WalkStop::LIMIT}; } if (ret == 3){ @@ -318,7 +318,7 @@ class WalkUntil{ return {ChunkNext::STOP, WalkStop::DIALOG}; } if (change > WALK_SCENE_CHANGE && battle_follows(m_stream, m_context)){ - escape_battle("wild battle (leaf opening); running."); + escape_battle("wild battle (leaf opening); running.", BattleMovement::STEP_MOVED); return {ChunkNext::NEXT_CHUNK, WalkStop::LIMIT}; } // Two still chunks in a row, so one dropped frame does not stop us. A @@ -358,9 +358,10 @@ class WalkUntil{ return change < line; } - void escape_battle(const std::string& what){ + enum class BattleMovement{ NONE, STEP_MOVED }; + void escape_battle(const std::string& what, BattleMovement movement){ m_result.wild_battles++; - if (m_chunks <= 1){ + if (m_chunks <= 1 && movement == BattleMovement::NONE){ m_result.origin = WalkOrigin::MAY_PRECEDE_LEG; } if (m_spec.input == WalkInput::TAPS){ @@ -400,6 +401,9 @@ class WalkUntil{ m_result.moved_chunks++; } } + if (m_result.moved_chunks > 1){ + m_result.origin = WalkOrigin::CURRENT_LEG; + } m_stream.log("[Walk] " + m_spec.label + ": " + walk_stop_name(stop) + " after " + std::to_string(m_result.walked.count()) + "ms, " + std::to_string(m_result.moved_chunks) + " moved chunks, " + From e50873ff23079938d1b243cc0016525600f9d0fb Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 01:10:58 -0800 Subject: [PATCH 024/166] BDSP AutoStory: enter Oreburgh's Pokemon Center reliably Check for the Center's inside before lining up on a lit door, give run_into_door's black-screen watcher a 50 ms hold and log which watcher fired, and target the map's pokemon_center_doorstep point below the Center's door. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryExecutor.cpp | 10 ++++++++-- .../AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp | 12 ++++++++++-- .../AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp | 4 ++-- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp index e6da4c63f7..e16a01e186 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp @@ -95,7 +95,7 @@ void save_failure_screenshot(VideoStream& stream, size_t attempt){ stream.log("Failure screenshot: " + path); } -} +} // namespace StoryExecutor::StoryExecutor(StoryEnv& env) @@ -217,7 +217,13 @@ Outcome StoryExecutor::heal(RunState&, const StoryStep& step){ if (in){ pbf_wait(context(), 1500ms); }else{ - enter_lit_door(stream(), context(), label_of(step)); + context().wait_for_all_requests(); + const VideoSnapshot screen = stream().video().snapshot(); + if (screen && pokemon_center_inside(*screen.frame)){ + stream().log(std::format("[{}] {}: already inside Pokemon Center despite no fade detected.", m_checkpoint, step.name)); + }else{ + enter_lit_door(stream(), context(), label_of(step)); + } } talk_to_nurse(stream(), context(), label_of(step)); // Her last line ("We hope to see you again!") can still be up, and a diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index b3c0f54c72..c90c91d17b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -110,7 +110,7 @@ DpadPosition dpad_toward(Direction direction){ bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction direction, bool run, Milliseconds timeout){ const DpadPosition dpad = dpad_toward(direction); - BlackScreenWatcher dark(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, 3 * FADE_DARKNESS, 60); + BlackScreenWatcher dark(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, 3 * FADE_DARKNESS, 60, BlackScreenWatcher::FinderType::PRESENT, 50ms); WhiteScreenWatcher white(COLOR_BLUE, {0.1, 0.1, 0.8, 0.8}, WhiteScreenWatcher::FinderType::PRESENT, 60ms); ShortDialogWatcher dialog(COLOR_YELLOW); BattleMenuWatcher battle(BattleType::STANDARD, COLOR_YELLOW); @@ -120,10 +120,18 @@ bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction } pbf_press_dpad(context, dpad, timeout, 0ms); }, {{dark}, {white}, {dialog}, {battle}}); - if (ret == 3){ + if (ret == 0){ + stream.log("[Story] run_into_door: black screen fade detected."); + }else if (ret == 1){ + stream.log("[Story] run_into_door: white screen fade detected."); + }else if (ret == 2){ + stream.log("[Story] run_into_door: dialog detected."); + }else if (ret == 3){ stream.log("[Story] run_into_door: wild battle; fleeing."); run_from_wild_battle(stream, context); return false; + }else{ + stream.log("[Story] run_into_door: timed out without detecting fade."); } return ret == 0 || ret == 1; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 649caf9622..1b95557bc7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -598,9 +598,9 @@ Pose after_the_welcome(){ Pose below_barry(){ return at(OREBURGH, 26, 22, NORTH); } -// Below Oreburgh's Pokemon Center's door (47, 20), facing it. +// Below Oreburgh's Pokemon Center's door, facing it. Pose below_oreburghs_center(){ - return at(OREBURGH, 47, 21, NORTH); + return at(OREBURGH, "pokemon_center_doorstep", NORTH); } // Out of Oreburgh's Pokemon Center, facing south: below its door, or on // the map's doorstep (46, 21), from which 01.04's 20 taps west reach the From 051d6c34323d20630a6aa404479e5dea3180039c Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 01:11:58 -0800 Subject: [PATCH 025/166] BDSP AutoStory: heal at Oreburgh's Center before the mine (01.02b) The welcome leaves the party as Route 203 left it, and every reload of 01.03 replayed a paralysed lead with no PP on its water move. New row 01.02b walks from the welcome to the Center and heals; 01.03 now starts on the Center's doorstep and routes west to Barry. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryTable.cpp | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 1b95557bc7..e73cf7b22c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -726,11 +726,21 @@ std::vector legs_out_of_coal_room(){ }; } +// 01.02b: the welcome leaves the party as Route 203 left it (2026-11-07 runs: +// the lead paralysed, its water move out of PP, and every reload of 01.03 +// replayed that). The Center first, so 01.03's save is a healed party on +// the doorstep. +StoryCheckpoint oreburgh_center_heal(){ + return row("01.02b", "Oreburgh Center heal", after_the_welcome(), { + route("below_the_centers_door", below_oreburghs_center(), "east along the street to below the Center's door", "town"), + heal("heal_oreburgh_first", "the nurse; out onto the doorstep, where 01.03 starts", out_of_oreburgh_center()), + }); +} + StoryCheckpoint oreburgh_mine_to_roark(){ const Pose below_roark = next_to(MINE, "roark", SOUTH, NORTH); - return row("01.03", "Oreburgh Mine to Roark", after_the_welcome(), { - anchored(legs("below_barry", {{.direction = SOUTH, .tiles = 1}, {.direction = EAST, .tiles = 3}, {.direction = NORTH, .tiles = 2}}, - "south 1 around the guide, east 3 to Barry's column, north 2 to below Barry"), below_barry()), + return row("01.03", "Oreburgh Mine to Roark", out_of_oreburgh_center(), { + route("below_barry", below_barry(), "west from the Center to below Barry in the Gym's door", "town"), talk("barry", "Barry in the Gym's door"), scene("barrys_lines", below_barry(), "Roark has gone to the mine"), route("above_the_mine", at(OREBURGH, 46, 58, SOUTH), "down the door's column to above the mine's warp tiles", "town"), @@ -820,6 +830,7 @@ std::vector to_oreburgh(){ anchored(battle("barry", true, "Barry's battle; a loss goes on, as it did on the console"), on_barrys_trigger()), }), route_203_to_oreburgh(), + oreburgh_center_heal(), oreburgh_mine_to_roark(), // Stays an event: after a loss it walks back from the Center with // the experience the battles gave, which a reload of this row's @@ -899,6 +910,7 @@ const std::map& start_save_cards(){ {"00.05c", "Jubilife City"}, {"01.01", "Jubilife City"}, {"01.02", "Route 203"}, + {"01.02b", "Oreburgh City"}, {"01.03", "Oreburgh City"}, {"01.04", "Oreburgh City"}, {"01.05", "Oreburgh City"}, From f30a03b2c030db44fd453a76c7c6f2631eeefd34 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 01:32:34 -0800 Subject: [PATCH 026/166] BDSP AutoStory: route to below the Center's door, not the doorstep The doorstep point (46, 21) is west of the door: on lab-B the route there ended against the wall and the heal found no door (2026-11-07 20:18), and the grid sim finds no door north of it. Keep the tile below the door. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index e73cf7b22c..ea70df6671 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -598,9 +598,11 @@ Pose after_the_welcome(){ Pose below_barry(){ return at(OREBURGH, 26, 22, NORTH); } -// Below Oreburgh's Pokemon Center's door, facing it. +// Below Oreburgh's Pokemon Center's door (47, 20), facing it. Not the +// map's doorstep (46, 21): a route there ended against the wall west of +// the door and the heal found no door (lab-B, 2026-11-07 20:18). Pose below_oreburghs_center(){ - return at(OREBURGH, "pokemon_center_doorstep", NORTH); + return at(OREBURGH, 47, 21, NORTH); } // Out of Oreburgh's Pokemon Center, facing south: below its door, or on // the map's doorstep (46, 21), from which 01.04's 20 taps west reach the From 0062d0b56879447d810f622e26d3ad13008a7b79 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 01:36:26 -0800 Subject: [PATCH 027/166] BDSP AutoStory: clip the walk to Roark against his rock and the wall Counted taps along the coal room's open row 29 drifted on lab-B (2026-11-07: south 3 moved 2). The walk now leaves the counted legs on Roark's row (27, 28), walks west against the rock east of him and south against the room's wall, and taps the last two tiles west. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp | 12 +++++++++--- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 6 +++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index ea70df6671..304382303a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -708,8 +708,7 @@ std::vector legs_below_roark(){ {.direction = EAST, .tiles = 14}, {.direction = SOUTH, .tiles = 10}, {.direction = WEST, .tiles = 2}, - {.direction = SOUTH, .tiles = 3}, - {.direction = WEST, .tiles = 9}, + {.direction = SOUTH, .tiles = 2}, }; } @@ -750,7 +749,14 @@ StoryCheckpoint oreburgh_mine_to_roark(){ step_into("into_the_coal_room", SOUTH, "down the entrance hall through the cave mouth", at(MINE, 15, 2, SOUTH)), anchored(to_walls("south_to_the_rock", {{.direction = SOUTH, .tiles = 8}}, "south against the corridor rock (15, 11)"), at(MINE, 15, 9, SOUTH)), - anchored(legs("below_roark", legs_below_roark(), "east around rock, across room, down column 29, and west to below Roark"), below_roark), + anchored(legs("above_roarks_row", legs_below_roark(), "east around rock, across room, down column 29, and onto Roark's row (27, 28)"), + at(MINE, 27, 28, SOUTH)), + // Counted taps along the open row 29 drifted (lab-B 2026-11-07: south 3 + // moved 2): west on row 28 stops at the rock (19, 28) east of Roark, + // south stops at the wall under row 29, two tiles from below him. + anchored(to_walls("beside_roarks_rock", {{.direction = WEST, .tiles = 7}, {.direction = SOUTH, .tiles = 1}}, + "west against the rock east of Roark, south against the room's wall"), at(MINE, 20, 29, SOUTH)), + anchored(legs("below_roark", {{.direction = WEST, .tiles = 2}}, "west 2 to below Roark"), below_roark), talk("roark", "Roark, north of us between his rocks"), scene("roark_smashes_the_rock", below_roark, "his lines, Rock Smash on the rock east of him, and he walks off"), anchored(legs("below_the_coal_rooms_warp", legs_out_of_coal_room(), "east around crate, up column 29, west across row 17, and up corridor to warp doorstep"), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index ab957ef11f..cc9d8ec37d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -875,11 +875,11 @@ StoryStep old_mine_hall_19(std::string name, Direction direction){ } // Oreburgh Mine: stepping south at col 29 without bypassing the crate -// hits the wooden crate at (29, 28) on the south leg. +// hits the wooden crate at (29, 28) on the south leg, a tile down. StoryStep old_coal_room_crate_cut(){ StoryStep step; step.kind = StoryStepKind::LEGS; - step.name = "below_roark"; + step.name = "above_roarks_row"; step.legs = { {.direction = Direction::EAST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 2}, {.direction = Direction::WEST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 5}, @@ -977,7 +977,7 @@ const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { }, { .input = {"01.03, cut corner through coal room crate at col 29", [](Logger& logger){ - return test_story_sim_step_failure(logger, "01.03", old_coal_room_crate_cut(), "01.03 below_roark", "short_leg: south 2 moved 0"); + return test_story_sim_step_failure(logger, "01.03", old_coal_room_crate_cut(), "01.03 above_roarks_row", "short_leg: south 2 moved 1"); }}, .expectation = {}, }, From 27b12d908a2eec932e25f06cbe0e8838271d2dc5 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 01:38:31 -0800 Subject: [PATCH 028/166] BDSP AutoStory: keep the recovery-walk tests on their own mine walk They exercise tap recovery on the coal room's nine counted legs, which 01.03 no longer walks as one step. Give them a fixed copy of that walk instead of looking up the table's step by name. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index e7436bcfe4..a957ac55e4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -57,15 +57,29 @@ class RecoveryStepIO : public StoryStepIO{ RouteIO& m_route; }; +// The coal room's counted walk from the corridor rock (15, 9) to below +// Roark (18, 29), as 01.03 walked it before its end was clipped to his +// rock and the wall: nine counted legs, the last one 9 tiles west along +// an open row, which is what these recovery cases need. const Pokemon::StoryStep& mine_step(){ - for (const auto& row : story_checkpoints()){ - for (const auto& step : row.steps){ - if (row.id == "01.03" && step.name == "below_roark"){ - return step; - } - } - } - throw GridSimFailure{"missing native mine step"}; + static const Pokemon::StoryStep step = []{ + Pokemon::StoryStep step; + step.kind = Pokemon::StoryStepKind::LEGS; + step.name = "below_roark"; + step.legs = { + {.direction = Direction::EAST, .tiles = 1}, + {.direction = Direction::SOUTH, .tiles = 2}, + {.direction = Direction::WEST, .tiles = 1}, + {.direction = Direction::SOUTH, .tiles = 5}, + {.direction = Direction::EAST, .tiles = 14}, + {.direction = Direction::SOUTH, .tiles = 10}, + {.direction = Direction::WEST, .tiles = 2}, + {.direction = Direction::SOUTH, .tiles = 3}, + {.direction = Direction::WEST, .tiles = 9}, + }; + return step; + }(); + return step; } struct RecoveryInput{ From 540642f1a6fad34873a07bf1d8a5a797cfc23437 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 09:08:50 -0800 Subject: [PATCH 029/166] BDSP AutoStory: Barry stands on Oreburgh's Gym doorstep from the welcome in the story sim lab-B 2026-11-08: 01.02b's walk to the Center stopped west of Barry on (26, 21). The sim now has him there from 01.02b to his lines in 01.03, and a test runs 01.02b alone (red on the current table). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 28 ++++++++++++++----- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index cc9d8ec37d..a95c7a1b9e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -316,21 +316,23 @@ std::vector story_triggers(){ // Someone the maps do not have, who stands on `tile` of `map` and is // talked to there or walked round: from row `row` on if `until` is "", -// else in `row` until its step `until` has run. +// else until the step `until` of row `until_row` has run. struct SimPerson{ std::string name; std::string map; TilePos tile; std::string row; - std::string until; + std::string until_row = {}; + std::string until = {}; }; std::vector sim_people(){ return { // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). - {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04", .until = ""}, - // Barry stands in the Gym's door until his lines (01.03; Roark - // ignored A until then, r101 and r104). - {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.03", .until = "barrys_lines"}, + {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04"}, + // Barry stands in the Gym's door from the welcome scene (lab-B, + // 2026-11-08: 01.02b's walk to the Center stopped west of him) + // until his lines in 01.03 (Roark ignored A until then, r101 and r104). + {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.02b", .until_row = "01.03", .until = "barrys_lines"}, }; } @@ -437,7 +439,9 @@ const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ std::vector here; std::string who; for (const SimPerson& person : sim_people()){ - const bool now = person.until.empty() ? m_row >= person.row : m_row == person.row && !m_ran.contains(person.until); + const bool gone = !person.until.empty() && + (m_row > person.until_row || (m_row == person.until_row && m_ran.contains(person.until))); + const bool now = m_row >= person.row && !gone; if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ here.push_back(person); who += person.name + ";"; @@ -831,6 +835,12 @@ UnitTestResult test_story_sim_each_row(Logger& logger){ return true; } +// lab-B, 2026-11-08: 01.02b from the welcome's end, Barry on the Gym's +// doorstep (26, 21), walked east to the Center and stopped west of him. +UnitTestResult test_oreburgh_heal_round_barry(Logger& logger){ + return run_rows(logger, {.from = "01.02b", .to = "01.02b"}); +} + UnitTestResult test_exit_gate(Logger& logger){ return run_exit_test(logger, "01.05", r75_old_gate_exit(), SimMisses{}, r75_pond_pocket()); } @@ -951,6 +961,10 @@ const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { .input = {"each row from 00.00 to 01.11 in isolation", test_story_sim_each_row}, .expectation = {}, }, + { + .input = {"01.02b, to the Center round Barry on the Gym's doorstep", test_oreburgh_heal_round_barry}, + .expectation = {}, + }, { .input = {"r75, out of the Oreburgh Gate", test_exit_gate}, .expectation = {}, From 4abd21d4fdafce867ab05a1860458a6b7f815dc8 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 09:11:10 -0800 Subject: [PATCH 030/166] BDSP AutoStory: plan Oreburgh's routes round Barry on the Gym's doorstep A route step can now name people standing in the way whom the maps do not have (StoryStep::standing, name to pose); the BDSP walker plans on a copy of its world with their tiles blocked. 01.02b's walk to the Center and 01.03's walk to below Barry declare him on (26, 21), so later rows still cross the doorstep once he has gone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/AutoStory/Pokemon_StorySteps.h | 5 +++++ .../PokemonBDSP_AutoStory_StoryTable.cpp | 18 ++++++++++++++++-- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 19 ++++++++++++++++++- 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h index 27aaabad8a..73bea6700e 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h @@ -32,6 +32,7 @@ #define PokemonAutomation_Pokemon_StorySteps_H #include +#include #include #include #include @@ -100,6 +101,10 @@ struct StoryStep{ // ROUTE: where to go; with several tiles, any of them. READY: the nurse. std::optional target; + // ROUTE: people standing in the way for now whom the maps do not have, + // by name: the plan goes round their tiles (Barry on a doorstep until + // he talks). + std::map standing = {}; // STEP Direction direction = Direction::NORTH; // LEGS diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 304382303a..d1164873b4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -146,6 +146,12 @@ StoryStep anchored(StoryStep step, Pose pose){ step.pose_after = std::move(pose); return step; } +// The route `step`, planned round `people`, who stand in the way for now +// though the maps do not have them. +StoryStep going_round(StoryStep step, std::map people){ + step.standing = std::move(people); + return step; +} // TODO(#114 coord events): the map schema has no scene triggers yet, so // each row steps onto the decomp's trigger tile, named in its reason. StoryStep step_into(std::string name, Direction direction, std::string why, std::optional pose_after = std::nullopt){ @@ -598,6 +604,12 @@ Pose after_the_welcome(){ Pose below_barry(){ return at(OREBURGH, 26, 22, NORTH); } +// Barry on the Gym's doorstep (26, 21), from the welcome until his lines in +// 01.03; the map has no Barry there. lab-B, 2026-11-08: 01.02b's walk east +// along row 21 to the Center stopped west of him. +std::map barry_in_the_gyms_door(){ + return {{"barry", at(OREBURGH, 26, 21)}}; +} // Below Oreburgh's Pokemon Center's door (47, 20), facing it. Not the // map's doorstep (46, 21): a route there ended against the wall west of // the door and the heal found no door (lab-B, 2026-11-07 20:18). @@ -733,7 +745,8 @@ std::vector legs_out_of_coal_room(){ // the doorstep. StoryCheckpoint oreburgh_center_heal(){ return row("01.02b", "Oreburgh Center heal", after_the_welcome(), { - route("below_the_centers_door", below_oreburghs_center(), "east along the street to below the Center's door", "town"), + going_round(route("below_the_centers_door", below_oreburghs_center(), "east along the street to below the Center's door", "town"), + barry_in_the_gyms_door()), heal("heal_oreburgh_first", "the nurse; out onto the doorstep, where 01.03 starts", out_of_oreburgh_center()), }); } @@ -741,7 +754,8 @@ StoryCheckpoint oreburgh_center_heal(){ StoryCheckpoint oreburgh_mine_to_roark(){ const Pose below_roark = next_to(MINE, "roark", SOUTH, NORTH); return row("01.03", "Oreburgh Mine to Roark", out_of_oreburgh_center(), { - route("below_barry", below_barry(), "west from the Center to below Barry in the Gym's door", "town"), + going_round(route("below_barry", below_barry(), "west from the Center to below Barry in the Gym's door", "town"), + barry_in_the_gyms_door()), talk("barry", "Barry in the Gym's door"), scene("barrys_lines", below_barry(), "Roark has gone to the mine"), route("above_the_mine", at(OREBURGH, 46, 58, SOUTH), "down the door's column to above the mine's warp tiles", "town"), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index ceef6d1a8b..03add5ae1e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -6,6 +6,7 @@ #include #include +#include #include "Common/Cpp/Color.h" #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" @@ -47,6 +48,21 @@ std::string label_of(const StoryStep& step){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "RouteIO::note() returned from a failure: " + message); } +// `world` with the people `step` says stand in the way on their tiles, or +// nothing if it names none. +std::optional with_standing(const StoryWorld& world, const StoryStep& step){ + if (step.standing.empty()){ + return std::nullopt; + } + StoryWorld peopled = world; + for (const auto& person : step.standing){ + for (const TilePos& pos : Pokemon::tiles_of(person.second)){ + peopled.block(story_to_world(world, person.second.map, pos)); + } + } + return peopled; +} + } // namespace @@ -89,11 +105,12 @@ Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep sights, [this](const std::string& trainer){ m_io.fight(trainer); } }; + const std::optional peopled = with_standing(*maps, step); const RouteWalkPlan plan{ [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }, label_of(step), {}, *costs, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK }; - const std::vector at = walk_route(m_io.route(), *maps, start, trainers, plan); + const std::vector at = walk_route(m_io.route(), peopled ? *peopled : *maps, start, trainers, plan); sights = std::move(trainers.sights); std::vector local; for (const TilePos& pos : at){ From be3ea5ab95db300f57043d23c17dfa74f5b9dac0 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 09:14:00 -0800 Subject: [PATCH 031/166] BDSP AutoStory: keep the story sim tests under the file-length limit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 24 +++++++------------ 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index a95c7a1b9e..ac86abdd94 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -314,9 +314,8 @@ std::vector story_triggers(){ return triggers; } -// Someone the maps do not have, who stands on `tile` of `map` and is -// talked to there or walked round: from row `row` on if `until` is "", -// else until the step `until` of row `until_row` has run. +// Someone the maps do not have, on `tile` of `map`, talked to or walked round: +// from row `row` on, until row `until_row`'s step `until` has run if it is set. struct SimPerson{ std::string name; std::string map; @@ -329,9 +328,7 @@ std::vector sim_people(){ return { // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04"}, - // Barry stands in the Gym's door from the welcome scene (lab-B, - // 2026-11-08: 01.02b's walk to the Center stopped west of him) - // until his lines in 01.03 (Roark ignored A until then, r101 and r104). + // Barry in the Gym's door, from the welcome (lab-B 2026-11-08) to his lines (r101, r104). {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.02b", .until_row = "01.03", .until = "barrys_lines"}, }; } @@ -439,9 +436,8 @@ const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ std::vector here; std::string who; for (const SimPerson& person : sim_people()){ - const bool gone = !person.until.empty() && - (m_row > person.until_row || (m_row == person.until_row && m_ran.contains(person.until))); - const bool now = m_row >= person.row && !gone; + const bool now = m_row >= person.row && (person.until.empty() || m_row < person.until_row || + (m_row == person.until_row && !m_ran.contains(person.until))); if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ here.push_back(person); who += person.name + ";"; @@ -835,12 +831,6 @@ UnitTestResult test_story_sim_each_row(Logger& logger){ return true; } -// lab-B, 2026-11-08: 01.02b from the welcome's end, Barry on the Gym's -// doorstep (26, 21), walked east to the Center and stopped west of him. -UnitTestResult test_oreburgh_heal_round_barry(Logger& logger){ - return run_rows(logger, {.from = "01.02b", .to = "01.02b"}); -} - UnitTestResult test_exit_gate(Logger& logger){ return run_exit_test(logger, "01.05", r75_old_gate_exit(), SimMisses{}, r75_pond_pocket()); } @@ -962,7 +952,9 @@ const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { .expectation = {}, }, { - .input = {"01.02b, to the Center round Barry on the Gym's doorstep", test_oreburgh_heal_round_barry}, + .input = {"01.02b, to the Center round Barry on the Gym's doorstep (lab-B, 2026-11-08)", [](Logger& logger){ + return run_rows(logger, {.from = "01.02b", .to = "01.02b"}); + }}, .expectation = {}, }, { From d3dc2f9a0254d13f83492bc73c81d9a8b5d6ea4e Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 09:20:19 -0800 Subject: [PATCH 032/166] Revert "BDSP AutoStory: plan Oreburgh's routes round Barry on the Gym's doorstep" This reverts commit 4abd21d4fdafce867ab05a1860458a6b7f815dc8. --- .../Pokemon/AutoStory/Pokemon_StorySteps.h | 5 ----- .../PokemonBDSP_AutoStory_StoryTable.cpp | 18 ++---------------- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 19 +------------------ 3 files changed, 3 insertions(+), 39 deletions(-) diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h index 73bea6700e..27aaabad8a 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySteps.h @@ -32,7 +32,6 @@ #define PokemonAutomation_Pokemon_StorySteps_H #include -#include #include #include #include @@ -101,10 +100,6 @@ struct StoryStep{ // ROUTE: where to go; with several tiles, any of them. READY: the nurse. std::optional target; - // ROUTE: people standing in the way for now whom the maps do not have, - // by name: the plan goes round their tiles (Barry on a doorstep until - // he talks). - std::map standing = {}; // STEP Direction direction = Direction::NORTH; // LEGS diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index d1164873b4..304382303a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -146,12 +146,6 @@ StoryStep anchored(StoryStep step, Pose pose){ step.pose_after = std::move(pose); return step; } -// The route `step`, planned round `people`, who stand in the way for now -// though the maps do not have them. -StoryStep going_round(StoryStep step, std::map people){ - step.standing = std::move(people); - return step; -} // TODO(#114 coord events): the map schema has no scene triggers yet, so // each row steps onto the decomp's trigger tile, named in its reason. StoryStep step_into(std::string name, Direction direction, std::string why, std::optional pose_after = std::nullopt){ @@ -604,12 +598,6 @@ Pose after_the_welcome(){ Pose below_barry(){ return at(OREBURGH, 26, 22, NORTH); } -// Barry on the Gym's doorstep (26, 21), from the welcome until his lines in -// 01.03; the map has no Barry there. lab-B, 2026-11-08: 01.02b's walk east -// along row 21 to the Center stopped west of him. -std::map barry_in_the_gyms_door(){ - return {{"barry", at(OREBURGH, 26, 21)}}; -} // Below Oreburgh's Pokemon Center's door (47, 20), facing it. Not the // map's doorstep (46, 21): a route there ended against the wall west of // the door and the heal found no door (lab-B, 2026-11-07 20:18). @@ -745,8 +733,7 @@ std::vector legs_out_of_coal_room(){ // the doorstep. StoryCheckpoint oreburgh_center_heal(){ return row("01.02b", "Oreburgh Center heal", after_the_welcome(), { - going_round(route("below_the_centers_door", below_oreburghs_center(), "east along the street to below the Center's door", "town"), - barry_in_the_gyms_door()), + route("below_the_centers_door", below_oreburghs_center(), "east along the street to below the Center's door", "town"), heal("heal_oreburgh_first", "the nurse; out onto the doorstep, where 01.03 starts", out_of_oreburgh_center()), }); } @@ -754,8 +741,7 @@ StoryCheckpoint oreburgh_center_heal(){ StoryCheckpoint oreburgh_mine_to_roark(){ const Pose below_roark = next_to(MINE, "roark", SOUTH, NORTH); return row("01.03", "Oreburgh Mine to Roark", out_of_oreburgh_center(), { - going_round(route("below_barry", below_barry(), "west from the Center to below Barry in the Gym's door", "town"), - barry_in_the_gyms_door()), + route("below_barry", below_barry(), "west from the Center to below Barry in the Gym's door", "town"), talk("barry", "Barry in the Gym's door"), scene("barrys_lines", below_barry(), "Roark has gone to the mine"), route("above_the_mine", at(OREBURGH, 46, 58, SOUTH), "down the door's column to above the mine's warp tiles", "town"), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index 03add5ae1e..ceef6d1a8b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -6,7 +6,6 @@ #include #include -#include #include "Common/Cpp/Color.h" #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" @@ -48,21 +47,6 @@ std::string label_of(const StoryStep& step){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "RouteIO::note() returned from a failure: " + message); } -// `world` with the people `step` says stand in the way on their tiles, or -// nothing if it names none. -std::optional with_standing(const StoryWorld& world, const StoryStep& step){ - if (step.standing.empty()){ - return std::nullopt; - } - StoryWorld peopled = world; - for (const auto& person : step.standing){ - for (const TilePos& pos : Pokemon::tiles_of(person.second)){ - peopled.block(story_to_world(world, person.second.map, pos)); - } - } - return peopled; -} - } // namespace @@ -105,12 +89,11 @@ Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep sights, [this](const std::string& trainer){ m_io.fight(trainer); } }; - const std::optional peopled = with_standing(*maps, step); const RouteWalkPlan plan{ [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }, label_of(step), {}, *costs, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK }; - const std::vector at = walk_route(m_io.route(), peopled ? *peopled : *maps, start, trainers, plan); + const std::vector at = walk_route(m_io.route(), *maps, start, trainers, plan); sights = std::move(trainers.sights); std::vector local; for (const TilePos& pos : at){ From b8f7b1e39e450e44b2f07505ef2076f39bb3df2e Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 09:20:50 -0800 Subject: [PATCH 033/166] BDSP AutoStory: 01.02b talks to Barry before the Center, as 01.03 did before the split Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp | 12 +++++++----- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 4 ++-- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 304382303a..8bee279c95 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -729,10 +729,15 @@ std::vector legs_out_of_coal_room(){ // 01.02b: the welcome leaves the party as Route 203 left it (2026-11-07 runs: // the lead paralysed, its water move out of PP, and every reload of 01.03 -// replayed that). The Center first, so 01.03's save is a healed party on -// the doorstep. +// replayed that). Barry's lines first, as before the split (he blocks the +// street east from his doorstep until then: lab-B 2026-11-08), then the +// Center, so 01.03's save is a healed party on the doorstep. StoryCheckpoint oreburgh_center_heal(){ return row("01.02b", "Oreburgh Center heal", after_the_welcome(), { + anchored(legs("below_barry", {{.direction = SOUTH, .tiles = 1}, {.direction = EAST, .tiles = 3}, {.direction = NORTH, .tiles = 2}}, + "south 1 around the guide, east 3 to Barry's column, north 2 to below Barry"), below_barry()), + talk("barry", "Barry in the Gym's door"), + scene("barrys_lines", below_barry(), "Roark has gone to the mine"), route("below_the_centers_door", below_oreburghs_center(), "east along the street to below the Center's door", "town"), heal("heal_oreburgh_first", "the nurse; out onto the doorstep, where 01.03 starts", out_of_oreburgh_center()), }); @@ -741,9 +746,6 @@ StoryCheckpoint oreburgh_center_heal(){ StoryCheckpoint oreburgh_mine_to_roark(){ const Pose below_roark = next_to(MINE, "roark", SOUTH, NORTH); return row("01.03", "Oreburgh Mine to Roark", out_of_oreburgh_center(), { - route("below_barry", below_barry(), "west from the Center to below Barry in the Gym's door", "town"), - talk("barry", "Barry in the Gym's door"), - scene("barrys_lines", below_barry(), "Roark has gone to the mine"), route("above_the_mine", at(OREBURGH, 46, 58, SOUTH), "down the door's column to above the mine's warp tiles", "town"), step_into("into_the_mine", SOUTH, "the warp tile (46, 59)", at(MINE_HALL, 12, 1, SOUTH)), step_into("into_the_coal_room", SOUTH, "down the entrance hall through the cave mouth", at(MINE, 15, 2, SOUTH)), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index ac86abdd94..98d8b4c9b5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -329,7 +329,7 @@ std::vector sim_people(){ // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04"}, // Barry in the Gym's door, from the welcome (lab-B 2026-11-08) to his lines (r101, r104). - {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.02b", .until_row = "01.03", .until = "barrys_lines"}, + {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.02b", .until_row = "01.02b", .until = "barrys_lines"}, }; } @@ -952,7 +952,7 @@ const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { .expectation = {}, }, { - .input = {"01.02b, to the Center round Barry on the Gym's doorstep (lab-B, 2026-11-08)", [](Logger& logger){ + .input = {"01.02b, Barry's lines, then the Center past his doorstep (lab-B, 2026-11-08)", [](Logger& logger){ return run_rows(logger, {.from = "01.02b", .to = "01.02b"}); }}, .expectation = {}, From c66cb559f2986c605447a22c4dcbcac7ecabe842 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 09:35:33 -0800 Subject: [PATCH 034/166] BDSP AutoStory: story sim test for a dark frame early in the mine's entrance hall lab-B 2026-11-08 09:27: 01.03's run into the coal room read dark 1.8 s into a 4050 ms run, stopped mid-hall, and south_to_the_rock walked on through the mouth. The story sim models that frame. run_into_door() takes dark_from (dark before then is not the door) and runs on after a fled wild battle for the running time it had left; no caller passes it yet. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 2 +- .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 111 ++++++++++++++---- .../PokemonBDSP_AutoStory_StoryStepIO.h | 10 +- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 66 +++++------ 4 files changed, 127 insertions(+), 62 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index a957ac55e4..f2fb322c31 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -50,7 +50,7 @@ class RecoveryStepIO : public StoryStepIO{ virtual void fight(const std::string&) override{ throw GridSimFailure{"unexpected trainer"}; } virtual void walk_until_stopped(Direction, size_t, const std::string&) override{ throw GridSimFailure{"unexpected blind hold"}; } virtual bool run_until_map(Direction, Milliseconds, const std::string&, const std::string&) override{ throw GridSimFailure{"unexpected banner walk"}; } - virtual bool run_into_door(Direction, bool, Milliseconds = Milliseconds(12000)) override{ throw GridSimFailure{"unexpected door"}; } + virtual bool run_into_door(Direction, bool, Milliseconds = Milliseconds(12000), Milliseconds = Milliseconds(0)) override{ throw GridSimFailure{"unexpected door"}; } virtual std::optional tap_to_banner(Direction, const std::string&, size_t) override{ throw GridSimFailure{"unexpected banner"}; } virtual void settle(Button, const std::string&, bool) override{ throw GridSimFailure{"unexpected scene"}; } private: diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index c90c91d17b..ad3d5f66cd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -97,10 +97,6 @@ void settle(VideoStream& stream, ProControllerContext& context, Button button, c stream); } -// Holds the D-pad toward a door (with B after the shoes) until the screen goes -// dark or a line shows, up to 12 s. Returns whether it went dark. A line -// stops it: holding on under Mom's "Oh, Kosmos!" wasted 12 s (r45). A wild -// battle in a cave corridor runs away before returning. DpadPosition dpad_toward(Direction direction){ return direction == Direction::NORTH ? DPAD_UP : @@ -108,32 +104,99 @@ DpadPosition dpad_toward(Direction direction){ direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; } -bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction direction, bool run, Milliseconds timeout){ - const DpadPosition dpad = dpad_toward(direction); +// A dark-screen watcher that fires only from `from` on, and keeps when the +// screen last went dark: where a wild battle's fade began. +class DarkFrom : public VisualInferenceCallback{ +public: + DarkFrom(BlackScreenWatcher& dark, WallClock from) + : VisualInferenceCallback("DarkFrom") + , m_dark(dark) + , m_from(from) + {} + virtual void make_overlays(VideoOverlaySet& items) const override{ + m_dark.make_overlays(items); + } + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ + const bool dark = m_dark.process_frame(frame, timestamp); + if (dark && !m_was_dark){ + m_went_dark = timestamp; + } + m_was_dark = dark; + return dark && timestamp >= m_from; + } + // When the screen last went dark; WallClock::max() if it has not. + WallClock went_dark() const{ + return m_went_dark; + } + +private: + BlackScreenWatcher& m_dark; + WallClock m_from; + bool m_was_dark = false; + WallClock m_went_dark = WallClock::max(); +}; + +// How one hold toward a door ended: run_until()'s index (0 dark, 1 white, +// 2 a line, 3 a wild battle; -1 time up), and when the screen last went dark. +struct DoorHoldEnd{ + int ret; + WallClock went_dark; +}; + +DoorHoldEnd hold_into_door(VideoStream& stream, ProControllerContext& context, DpadPosition dpad, bool run, Milliseconds hold, Milliseconds dark_from){ BlackScreenWatcher dark(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, 3 * FADE_DARKNESS, 60, BlackScreenWatcher::FinderType::PRESENT, 50ms); + DarkFrom late_dark(dark, current_time() + dark_from); WhiteScreenWatcher white(COLOR_BLUE, {0.1, 0.1, 0.8, 0.8}, WhiteScreenWatcher::FinderType::PRESENT, 60ms); ShortDialogWatcher dialog(COLOR_YELLOW); BattleMenuWatcher battle(BattleType::STANDARD, COLOR_YELLOW); const int ret = run_until(stream, context, [&](ProControllerContext& context){ if (run){ - ssf_press_button(context, BUTTON_B, 0ms, timeout, 0ms); + ssf_press_button(context, BUTTON_B, 0ms, hold, 0ms); + } + pbf_press_dpad(context, dpad, hold, 0ms); + }, {{late_dark}, {white}, {dialog}, {battle}}); + return {.ret = ret, .went_dark = late_dark.went_dark()}; +} + +// Wild battles a run into a door flees and runs on after. +constexpr size_t DOOR_RUN_BATTLES = 3; + +// Holds the D-pad toward a door (with B after the shoes) for `timeout` +// until the screen goes dark or a line shows. Returns whether it went dark. +// A line stops it: holding on under Mom's "Oh, Kosmos!" wasted 12 s (r45). +// Dark in the first `dark_from` of running is not the door (lab-B +// 2026-11-08: dark at 1.8 s, halfway down the mine's entrance hall). A wild +// battle on the way is fled, and the run goes on for the time it had left: +// only the running counts, up to the battle's fade. +bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction direction, bool run, Milliseconds timeout, Milliseconds dark_from){ + Milliseconds left = timeout; + for (size_t battles = 0;; battles++){ + const WallClock start = current_time(); + const DoorHoldEnd end = hold_into_door(stream, context, dpad_toward(direction), run, left, dark_from); + if (end.ret == 3){ + const WallClock stopped = std::min(end.went_dark, current_time()); + const Milliseconds ran = std::chrono::duration_cast(stopped - start) - ROUTE_START_DELAY; + const Milliseconds counted = std::clamp(ran, 0ms, left); + left -= counted; + dark_from -= std::min(dark_from, counted); + stream.log(std::format("[Story] run_into_door: wild battle after {} ms of running; fleeing.", counted.count())); + run_from_wild_battle(stream, context); + if (battles < DOOR_RUN_BATTLES && left > 0ms){ + continue; + } + return false; + } + if (end.ret == 0){ + stream.log("[Story] run_into_door: black screen fade detected."); + }else if (end.ret == 1){ + stream.log("[Story] run_into_door: white screen fade detected."); + }else if (end.ret == 2){ + stream.log("[Story] run_into_door: dialog detected."); + }else{ + stream.log("[Story] run_into_door: timed out without detecting fade."); } - pbf_press_dpad(context, dpad, timeout, 0ms); - }, {{dark}, {white}, {dialog}, {battle}}); - if (ret == 0){ - stream.log("[Story] run_into_door: black screen fade detected."); - }else if (ret == 1){ - stream.log("[Story] run_into_door: white screen fade detected."); - }else if (ret == 2){ - stream.log("[Story] run_into_door: dialog detected."); - }else if (ret == 3){ - stream.log("[Story] run_into_door: wild battle; fleeing."); - run_from_wild_battle(stream, context); - return false; - }else{ - stream.log("[Story] run_into_door: timed out without detecting fade."); + return end.ret == 0 || end.ret == 1; } - return ret == 0 || ret == 1; } // What the screen showed after a tap toward a door or a cave mouth. @@ -195,8 +258,8 @@ bool ConsoleStoryStepIO::run_until_map(Direction direction, Milliseconds limit, return walk.stop == WalkStop::ARRIVED; } -bool ConsoleStoryStepIO::run_into_door(Direction direction, bool run, Milliseconds timeout){ - return PokemonBDSP::run_into_door(m_stream, m_context, direction, run, timeout); +bool ConsoleStoryStepIO::run_into_door(Direction direction, bool run, Milliseconds timeout, Milliseconds dark_from){ + return PokemonBDSP::run_into_door(m_stream, m_context, direction, run, timeout, dark_from); } // A held walk can carry on past a fade that goes unseen: out of the Gym it diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h index da718a6aba..52470d8fcd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h @@ -43,9 +43,11 @@ class StoryStepIO{ // Runs `direction` on the D-pad until the location banner of `map` (a // JSON map's name) shows, for at most `limit`. Returns whether it showed. virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string& label) = 0; - // Holds the D-pad toward a door (running with `run`) until the screen - // goes dark or a line shows. Returns whether it went dark. - virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000)) = 0; + // Holds the D-pad toward a door (running with `run`) for `timeout` until + // the screen goes dark or a line shows. A dark screen in the first + // `dark_from` of running is not the door's fade, and a wild battle on the + // way is fled, the run going on for the time left. Returns whether it went dark. + virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) = 0; // D-pad taps `direction` one at a time, each looked at, toward a door // or cave mouth, until the fade (then no more taps) and the location // banner of `map` (a JSON map's name), for at most `max_taps`. Returns @@ -68,7 +70,7 @@ class ConsoleStoryStepIO : public StoryStepIO{ virtual void fight(const std::string& trainer) override; virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string& label) override; - virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000)) override; + virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) override; virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) override; virtual void settle(Button button, const std::string& label, bool fade) override; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 98d8b4c9b5..413cad45cb 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -68,15 +68,18 @@ using Pokemon::TilePos; // Which detections the simulation misses on purpose (#162): the `fade`th // door fade (run_into_door(), from 0) or the `banner`th map banner // (run_until_map()) of the run goes unseen, though the player did go -// through. The console missed both (r75, r81). +// through. The console missed both (r75, r81). The `dark`th door run reads +// dark SIM_FALSE_DARK in, short of the door, as lab-B's did on 2026-11-08. // The counts and flags below are the run's: how many fades and banners it // looked for, whether a miss happened since the executor last looked, and // whether a missed fade is still unseen. struct SimMisses{ std::optional fade; std::optional banner; + std::optional dark = {}; size_t fades = 0; size_t banners = 0; + size_t doors = 0; bool missed = false; bool fade_unseen = false; }; @@ -87,6 +90,7 @@ struct SimMisses{ // reads at once. Through a cave mouth the fade comes first, and a hold // whose fade went unseen goes on the same way (r75, r81). constexpr size_t SIM_BANNER_TILES = 3; +constexpr Milliseconds SIM_FALSE_DARK = 1800ms; // What a run on the simulation did. struct SimRun{ @@ -131,8 +135,13 @@ class SimStoryStepIO : public StoryStepIO{ } virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string& label) override; virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; - virtual bool run_into_door(Direction direction, bool run, Milliseconds timeout = Milliseconds(12000)) override{ - const bool warped = m_sim.hold(direction, timeout, run ? SimPace::RUN : SimPace::WALK).stop == SimStop::WARP; + virtual bool run_into_door(Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) override{ + const SimPace pace = run ? SimPace::RUN : SimPace::WALK; + if (false_dark() && dark_from <= SIM_FALSE_DARK && SIM_FALSE_DARK < timeout){ + m_sim.hold(direction, SIM_FALSE_DARK, pace); + return true; + } + const bool warped = m_sim.hold(direction, timeout, pace).stop == SimStop::WARP; if (warped && fade_missed()){ m_misses.fade_unseen = true; return false; @@ -160,6 +169,11 @@ class SimStoryStepIO : public StoryStepIO{ m_misses.missed |= miss; return miss; } + bool false_dark(){ + const bool dark = m_misses.dark == m_misses.doors++; + m_misses.missed |= dark; + return dark; + } bool banner_missed(){ const bool miss = m_misses.banner == m_misses.banners++; m_misses.missed |= miss; @@ -935,40 +949,26 @@ class Test_AutoStoryStorySim : public UnitTest{ } // namespace const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { + {.input = {"the maps' coord events are on open ground or doors", test_coord_events}, .expectation = {}}, + {.input = {"detector misses from 00.00 to 01.11", test_story_sim_misses}, .expectation = {}}, + {.input = {"00.00 to 01.11: the whole table, from the new game to Floaroma", test_story_sim_whole_table}, .expectation = {}}, + {.input = {"each row from 00.00 to 01.11 in isolation", test_story_sim_each_row}, .expectation = {}}, + {.input = {"01.02b, Barry's lines, then the Center past his doorstep (lab-B, 2026-11-08)", [](Logger& logger){ + return run_rows(logger, {.from = "01.02b", .to = "01.02b"}); + }}, .expectation = {}}, + {.input = {"r75, out of the Oreburgh Gate", test_exit_gate}, .expectation = {}}, + {.input = {"r81, out of the Ravaged Path", test_exit_ravaged_path}, .expectation = {}}, + {.input = {"01.03, Oreburgh Mine B1F entrance hall corridor runs to and back", test_oreburgh_mine_hall_corridor}, .expectation = {}}, { - .input = {"the maps' coord events are on open ground or doors", test_coord_events}, - .expectation = {}, - }, - { - .input = {"detector misses from 00.00 to 01.11", test_story_sim_misses}, - .expectation = {}, - }, - { - .input = {"00.00 to 01.11: the whole table, from the new game to Floaroma", test_story_sim_whole_table}, - .expectation = {}, - }, - { - .input = {"each row from 00.00 to 01.11 in isolation", test_story_sim_each_row}, - .expectation = {}, - }, - { - .input = {"01.02b, Barry's lines, then the Center past his doorstep (lab-B, 2026-11-08)", [](Logger& logger){ - return run_rows(logger, {.from = "01.02b", .to = "01.02b"}); + .input = {"01.03, a dark frame 1.8 s down the mine's entrance hall is not its mouth (lab-B, 2026-11-08)", [](Logger& logger){ + SimExecutor executor(logger, {.fade = {}, .banner = {}, .dark = 1}); + run_rows_on(executor, logger, {.from = "01.03", .to = "01.03"}); + const SimRun& run = executor.result(); + return run.missed_step == "01.03 into_the_coal_room" && run.error.empty() ? UnitTestResult(true) + : UnitTestResult(std::format("dark in '{}', failed in '{}': {}", run.missed_step, run.failed_step, run.error)); }}, .expectation = {}, }, - { - .input = {"r75, out of the Oreburgh Gate", test_exit_gate}, - .expectation = {}, - }, - { - .input = {"r81, out of the Ravaged Path", test_exit_ravaged_path}, - .expectation = {}, - }, - { - .input = {"01.03, Oreburgh Mine B1F entrance hall corridor runs to and back", test_oreburgh_mine_hall_corridor}, - .expectation = {}, - }, { .input = {"01.03, counted 19 taps south leaves player in hall", [](Logger& logger){ return test_story_sim_step_failure(logger, "01.03", old_mine_hall_19("into_the_coal_room", Direction::SOUTH), "01.03 south_to_the_rock", "warp instead of a stop."); From 04f84ec57b0f86bbef3a6bbe8f428bd79d763a11 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 09:37:37 -0800 Subject: [PATCH 035/166] BDSP AutoStory: a door run ignores dark before 85% of its way to the door A door step's run into a door now passes run_into_door() a dark_from of 85% of its time to the door, so a dark frame halfway down the mine's entrance hall (lab-B 2026-11-08, 1.8 s of 4050 ms) no longer stops the run. Door holds last at least 4500 ms: the one-tile step onto the mine's warp faded 3.35 s in, after the old 1500 ms hold had given up. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 33 +++++++++++++++---- 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index ceef6d1a8b..e999b88b76 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -160,7 +160,23 @@ Outcome StoryWalkSteps::tap_to_banner(const StoryStep& step){ } namespace{ -Milliseconds door_timeout(const std::string& map_name, const Pose& pose, Direction direction, bool can_run){ +// A run into a door: how long to hold, and for how long of it a dark screen +// is not yet the door's fade (run_into_door()). +struct DoorRun{ + Milliseconds timeout; + Milliseconds dark_from; +}; +// Dark before this share of the run's time to the door is not the door: +// lab-B 2026-11-08 09:27:33 read dark at 1.8 s of the 4050 ms run down the +// mine's entrance hall (3250 ms to the mouth), stopped there, and the next +// step walked on through the mouth. +constexpr double DOOR_DARK_FROM_SHARE = 0.85; +// The shortest hold: the one-tile step onto the mine's warp faded 3.35 s +// after its hold began (lab-B 2026-11-07 12:19 and 12:27); a 1500 ms hold +// gave up just before the fade (2026-11-08 09:27:16) and settle() pressed B +// 15 s before it called the overworld calm. +constexpr Milliseconds DOOR_MIN_HOLD = 4500ms; +DoorRun door_run(const std::string& map_name, const Pose& pose, Direction direction, bool can_run){ try{ const Pokemon::MapData& map = story_map(map_name); const auto tiles_list = Pokemon::tiles_of(pose); @@ -168,11 +184,15 @@ Milliseconds door_timeout(const std::string& map_name, const Pose& pose, Directi const size_t tiles = Pokemon::tiles_to_door(map, tiles_list.front(), direction); if (tiles > 0){ const Milliseconds per_tile = route_ms_per_tile(direction, can_run ? MoveSpeed::RUN : MoveSpeed::WALK); - return std::max(1500ms, ROUTE_START_DELAY + per_tile * (int64_t)tiles + 800ms); + const Milliseconds to_door = ROUTE_START_DELAY + per_tile * (int64_t)tiles; + return { + .timeout = std::max(DOOR_MIN_HOLD, to_door + 800ms), + .dark_from = std::chrono::duration_cast(to_door * DOOR_DARK_FROM_SHARE), + }; } } }catch (...){} - return Milliseconds(12000); + return {.timeout = 12000ms, .dark_from = 0ms}; } enum class CountedEndPolicy{ EXACT, ONE_SHORT }; std::vector counted_ends(const std::vector& starts, const Pokemon::StoryLeg& leg, CountedEndPolicy policy){ @@ -288,9 +308,10 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ // (r33 was outside, "no fade"). No separate turn tap first: at 1 tile // from the door, a 50 ms turn tap can step in before run_into_door() watches. if (step.pose_after && step.pose_after->map != state.pose.map){ - const Milliseconds timeout = door_timeout(state.pose.map, state.pose, step.direction, m_can_run); - const bool faded = m_io.run_into_door(step.direction, m_can_run, timeout); - log(std::format("[{}] {}: {} through the door (timeout {} ms): {}.", m_row, step.name, direction_name(step.direction), timeout.count(), faded ? "faded" : "no fade yet")); + const DoorRun door = door_run(state.pose.map, state.pose, step.direction, m_can_run); + const bool faded = m_io.run_into_door(step.direction, m_can_run, door.timeout, door.dark_from); + log(std::format("[{}] {}: {} through the door (timeout {} ms, dark from {} ms): {}.", m_row, step.name, + direction_name(step.direction), door.timeout.count(), door.dark_from.count(), faded ? "faded" : "no fade yet")); m_io.settle(BUTTON_B, label_of(step), !faded); return Pokemon::outcome_ok(); } From bca0742eec10474370c299541352194e3cc4da0d Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 10:23:43 -0800 Subject: [PATCH 036/166] BDSP AutoStory: the mine hall corridor test runs on the grid sim; move it there test_oreburgh_mine_hall_corridor() holds on a GridSim alone, with no story row, so it belongs with the grid sim tests; the story sim tests need its lines for the heal test that follows. Moved unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 30 +++++++++++++++++++ .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 27 ----------------- 2 files changed, 30 insertions(+), 27 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 3fa4af63fe..242d6c59b3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -632,6 +632,32 @@ UnitTestResult test_wall_leg_check_at_wall_short_distance_safeguard(Logger& logg return "caught unexpected failure: " + f.message; } } +// Oreburgh Mine B1F: the entrance hall corridor is traversed to and back by +// running south from (12, 1) to (12, 21), and north from (11, 21) to (11, 1). +UnitTestResult test_oreburgh_mine_hall_corridor(Logger& logger){ + const StoryWorld* world = story_plan_world("OreburghMineB1F", "OreburghMineB1F"); + if (world == nullptr){ + return "OreburghMineB1F world not found."; + } + const SimWorld sim_world{.world = world, .can_run = true}; + const auto test_run = [&](TilePos start, Direction dir, TilePos expected, const char* label){ + GridSim sim(sim_world, start, dir, true); + const SimMove move = sim.hold(dir, 5000ms, SimPace::RUN); + if (move.stop != SimStop::WARP || sim.player().pos != sim_pos(expected)){ + return std::format("{}: expected WARP at {}, got {} at {}.", label, + Pokemon::to_string(expected), sim_stop_name(move.stop), Pokemon::to_string(nearest_tile(sim.player().pos))); + } + logger.log(std::format("{} hall run reached {} in {} ms.", label, Pokemon::to_string(expected), move.time.count())); + return std::string{}; + }; + std::string err = test_run({12, 1}, Direction::SOUTH, {12, 21}, "Southbound"); + if (!err.empty()){ + return err; + } + err = test_run({11, 21}, Direction::NORTH, {11, 1}, "Northbound"); + return err.empty() ? UnitTestResult(true) : UnitTestResult(err); +} + struct AutoStoryGridSimInput{ std::string name; std::function body; @@ -703,6 +729,10 @@ const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { .input = {"check_at_wall safeguard rejects legs stalled well short of expected distance", test_wall_leg_check_at_wall_short_distance_safeguard}, .expectation = {}, }, + { + .input = {"01.03, Oreburgh Mine B1F entrance hall corridor runs to and back", test_oreburgh_mine_hall_corridor}, + .expectation = {}, + }, }; void add_tests_AutoStory_GridSim(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 413cad45cb..102832d5ee 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -853,32 +853,6 @@ UnitTestResult test_exit_ravaged_path(Logger& logger){ return run_exit_test(logger, "01.09", r81_old_cave_exit(), SimMisses{.fade = 0, .banner = std::nullopt}, r81_below_the_mouth()); } -// Oreburgh Mine B1F: the entrance hall corridor is traversed to and back by -// running south from (12, 1) to (12, 21), and north from (11, 21) to (11, 1). -UnitTestResult test_oreburgh_mine_hall_corridor(Logger& logger){ - const StoryWorld* world = story_plan_world("OreburghMineB1F", "OreburghMineB1F"); - if (world == nullptr){ - return "OreburghMineB1F world not found."; - } - const SimWorld sim_world{.world = world, .can_run = true}; - const auto test_run = [&](TilePos start, Direction dir, TilePos expected, const char* label){ - GridSim sim(sim_world, start, dir, true); - const SimMove move = sim.hold(dir, 5000ms, SimPace::RUN); - if (move.stop != SimStop::WARP || sim.player().pos != sim_pos(expected)){ - return std::format("{}: expected WARP at {}, got {} at {}.", label, - Pokemon::to_string(expected), sim_stop_name(move.stop), Pokemon::to_string(nearest_tile(sim.player().pos))); - } - logger.log(std::format("{} hall run reached {} in {} ms.", label, Pokemon::to_string(expected), move.time.count())); - return std::string{}; - }; - std::string err = test_run({12, 1}, Direction::SOUTH, {12, 21}, "Southbound"); - if (!err.empty()){ - return err; - } - err = test_run({11, 21}, Direction::NORTH, {11, 1}, "Northbound"); - return err.empty() ? UnitTestResult(true) : UnitTestResult(err); -} - // Oreburgh Mine B1F: tapping 19 tiles leaves the player 1 tile short of the warp door. StoryStep old_mine_hall_19(std::string name, Direction direction){ StoryStep step; @@ -958,7 +932,6 @@ const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { }}, .expectation = {}}, {.input = {"r75, out of the Oreburgh Gate", test_exit_gate}, .expectation = {}}, {.input = {"r81, out of the Ravaged Path", test_exit_ravaged_path}, .expectation = {}}, - {.input = {"01.03, Oreburgh Mine B1F entrance hall corridor runs to and back", test_oreburgh_mine_hall_corridor}, .expectation = {}}, { .input = {"01.03, a dark frame 1.8 s down the mine's entrance hall is not its mouth (lab-B, 2026-11-08)", [](Logger& logger){ SimExecutor executor(logger, {.fade = {}, .banner = {}, .dark = 1}); From 4d2c7a5446a117b02df259fc6463e749e6899083 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 10:23:50 -0800 Subject: [PATCH 037/166] BDSP AutoStory: red tests for Oreburgh's Center read from its counter lab-B 2026-11-08 09:47: 01.03's run into Oreburgh's Center saw no fade (as at 2026-11-07 17:38 and 20:19, before DarkFrom) and went on to the nurse's counter. pokemon_center_inside() wants black below the floor, which shows only near the entrance, so the heal lined up with a doorway that was not there and failed. The detector test reads the counter, exit mat and doorstep frames (CommandLineTests, skipped without them); the story sim misses 01.03's heal fade, which its stub heal never looks for. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_Actions_Tests.cpp | 39 +++++++++++++++++++ .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 20 ++++++++++ 2 files changed, 59 insertions(+) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.cpp index 6b78029754..49a0dd2313 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.cpp @@ -361,6 +361,41 @@ UnitTestResult test_pokemon_center_inside(Logger& logger){ } +// Oreburgh's Center, lab-B 2026-11-08 (in CommandLineTests under +// PokemonBDSP/AutoStory, skipped without them): 01.03's run in saw no fade +// and stopped at the nurse's counter, the camera in close and the lit floor +// down to the screen's bottom; on the exit mat; and outside on the doorstep +// at sunset, the ground as orange as the Center's back wall. +UnitTestResult test_pokemon_center_counter(Logger& logger){ + struct Case{ + const char* file; + bool inside; + }; + const Case cases[] = { + {.file = "PokemonBDSP/AutoStory/OreburghCenterCounter-20261108-094735.png", .inside = true}, + {.file = "PokemonBDSP/AutoStory/OreburghCenterExitMat-20261108.png", .inside = true}, + {.file = "PokemonBDSP/AutoStory/OreburghCenterDoorstep-20261108.png", .inside = false}, + }; + for (const Case& c : cases){ + const std::string path = UNIT_TEST_RESOURCE_PATH() + c.file; + if (!Filesystem::is_regular_file(path)){ + return UnitTestResult(UnitTestResult::SKIPPED, "Screenshot not found: " + path); + } + const ImageRGB32 screen(path); + const bool inside = pokemon_center_inside(screen); + logger.log(std::string(c.file) + ": inside " + std::to_string(inside)); + if (inside != c.inside){ + return std::string(c.file) + ": expected " + (c.inside ? "inside" : "outside") + + " a Pokemon Center, read " + (inside ? "inside" : "outside") + "."; + } + if (inside && find_lit_doorway(screen)){ + return std::string(c.file) + ": inside, yet a lit doorway was read."; + } + } + return true; +} + + // The School's lamp at night, from its doorsteps' row (2026-10-30): where // the door took us in, the lamp reads within half a tile of the door; a // tile either side, more. @@ -463,6 +498,10 @@ const AutoStoryActionsCase AUTO_STORY_ACTIONS_CASES[] = { .input = {"Pokemon Center inside", test_pokemon_center_inside}, .expectation = {}, }, + { + .input = {"Pokemon Center inside: Oreburgh's counter, exit mat and doorstep", test_pokemon_center_counter}, + .expectation = {}, + }, { .input = {"Jubilife School lamp", test_school_lamp}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 102832d5ee..edd52cfb6b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -889,6 +889,22 @@ UnitTestResult test_story_sim_step_failure(Logger& logger, const std::string& ro return true; } +// lab-B 2026-11-08: 01.03's run into Oreburgh's Center saw no fade and went +// on to the nurse's counter. The heal must find it is inside and go on. +UnitTestResult test_heal_fade_unseen(Logger& logger){ + SimExecutor clean(logger); + run_rows_on(clean, logger, {.from = "01.03", .to = "01.03"}); + for (size_t i = 0; i < clean.misses().fades; i++){ + SimExecutor sim(logger, {.fade = i, .banner = {}}); + run_rows_on(sim, logger, {.from = "01.03", .to = "01.03"}); + const SimRun& run = sim.result(); + if (run.missed_step == "01.03 heal_oreburgh"){ + return run.error.empty() ? UnitTestResult(true) : UnitTestResult(std::format("failed in '{}': {}", run.failed_step, run.error)); + } + } + return "no fade in 01.03 heal_oreburgh to miss: the heal never ran into its door."; +} + struct AutoStoryStorySimInput{ std::string name; std::function body; @@ -942,6 +958,10 @@ const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { }}, .expectation = {}, }, + { + .input = {"01.03, the Center's fade unseen, the heal goes on from the counter (lab-B, 2026-11-08)", test_heal_fade_unseen}, + .expectation = {}, + }, { .input = {"01.03, counted 19 taps south leaves player in hall", [](Logger& logger){ return test_story_sim_step_failure(logger, "01.03", old_mine_hall_19("into_the_coal_room", Direction::SOUTH), "01.03 south_to_the_rock", "warp instead of a stop."); From e5388ccc5ca7b0520cfcd46247c4225795e28a78 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 10:27:06 -0800 Subject: [PATCH 038/166] BDSP AutoStory: a Pokemon Center's inside reads at the nurse's counter too lab-B 2026-11-08 09:47: 01.03's run into Oreburgh's Center saw no fade and went on to the counter, where pokemon_center_inside() read outside: it wanted the black below the floor that shows only near the entrance. It now also reads the counter close up: its red top over its white front, either side of the player. Outside the Center at sunset the ground is as orange as its back wall, but not this red, and nothing below it is white. The heal's run in (run_into_center()) is shared with the story sim, whose heal ran a hold of its own and never missed its fade. A door run that times out logs when the screen went dark before dark_from, to tell an early dark frame from a fade it ignored. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Actions/PokemonBDSP_AutoStory_Center.cpp | 45 ++++++++++++++----- .../Actions/PokemonBDSP_AutoStory_Center.h | 9 ++-- .../PokemonBDSP_AutoStory_StoryExecutor.cpp | 21 ++++----- .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 4 ++ .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 11 +++++ .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 15 +++++++ .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 11 ++++- 7 files changed, 89 insertions(+), 27 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Center.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Center.cpp index cfeae1e1b6..9a58559284 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Center.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Center.cpp @@ -4,6 +4,7 @@ * */ +#include #include #include #include @@ -203,6 +204,38 @@ void log_doorway(VideoStream& stream, const std::string& label, const LitDoorway std::to_string(doorway.x) + ", " + std::to_string(doorway.y) + " of the screen)."); } +// Near the entrance: black below the floor, either side of the step out +// of the door, and the floor lit between them: not a fade (349 in +// Jubilife at night). +bool center_entrance_view(const ImageViewRGB32& screen){ + for (const ImageFloatBox& box : {ImageFloatBox(0.02, 0.95, 0.30, 0.04), ImageFloatBox(0.65, 0.95, 0.33, 0.04)}){ + if (image_stats(extract_box_reference(screen, box)).average.sum() > 90){ + return false; + } + } + return image_stats(extract_box_reference(screen, ImageFloatBox(0.30, 0.55, 0.40, 0.15))).average.sum() > 250; +} + +// At the nurse's counter, the camera in close and the lit floor down to +// the screen's bottom (lab-B 2026-11-08: a run in whose fade went unseen +// stopped there): either side of us, the counter's red top (r 246, g 84) +// over its white front (about 200 each). Outside Oreburgh's Center at +// sunset the ground there is orange (r 218, g 134), with nothing white. +bool center_counter_view(const ImageViewRGB32& screen){ + for (double x : {0.15, 0.56}){ + const FloatPixel top = image_stats(extract_box_reference(screen, ImageFloatBox(x, 0.58, 0.12, 0.03))).average; + const FloatPixel front = image_stats(extract_box_reference(screen, ImageFloatBox(x, 0.66, 0.12, 0.03))).average; + const double front_min = std::min({front.r, front.g, front.b}); + const double front_max = std::max({front.r, front.g, front.b}); + const bool red = top.r >= 120 && top.r > 2 * top.g && top.g > top.b; + const bool white = front_min >= 120 && front_max - front_min <= 40; + if (!red || !white){ + return false; + } + } + return true; +} + } // namespace @@ -216,17 +249,7 @@ bool pokemon_center_inside(const ImageViewRGB32& screen){ const double r = box.average.r, g = box.average.g, b = box.average.b; wall += r >= 140 && r > g + 40 && g > b + 40; } - if (wall < 2){ - return false; - } - // Black below the floor, either side of the step out of the door. - for (const ImageFloatBox& box : {ImageFloatBox(0.02, 0.95, 0.30, 0.04), ImageFloatBox(0.65, 0.95, 0.33, 0.04)}){ - if (image_stats(extract_box_reference(screen, box)).average.sum() > 90){ - return false; - } - } - // And the floor lit between them: not a fade (349 in Jubilife at night). - return image_stats(extract_box_reference(screen, ImageFloatBox(0.30, 0.55, 0.40, 0.15))).average.sum() > 250; + return wall >= 2 && (center_entrance_view(screen) || center_counter_view(screen)); } void fail_if_blacked_out(VideoStream& stream, ProControllerContext& context, const std::string& label){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Center.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Center.h index ded333a567..96a8288af9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Center.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Center.h @@ -31,10 +31,11 @@ struct LitDoorway{ double rows_up; // rows north of the player's tile, roughly: 1 straight ahead }; -// Whether `screen` is the inside of a Pokemon Center seen from its door: -// the orange back wall at the top left, and the black below the entrance -// mat along the bottom edge. Its lit floor reads as a doorway -// (find_lit_doorway()), so this is what says we are in (r126 runs 2, 3). +// Whether `screen` is the inside of a Pokemon Center: the orange back wall +// along the top, and either the black below the entrance mat along the +// bottom edge (seen from the door) or the nurse's counter close up. Its lit +// floor reads as a doorway (find_lit_doorway()), so this is what says we +// are in (r126 runs 2, 3). bool pokemon_center_inside(const ImageViewRGB32& screen); // Finds a lit doorway (a Pokemon Center's or a Poke Mart's) in the upper diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp index e16a01e186..80e5d6bbe8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp @@ -211,19 +211,20 @@ Outcome StoryExecutor::heal(RunState&, const StoryStep& step){ // doorway lineup is for when the run in finds no door: people on the // way can leave the route unsure of the column (r59, Jubilife). Below // Sandgem's door the lineup read 0.7 tile off and stepped us off it (r48). + // With no fade, the run can have gone on in to the counter (lab-B + // 2026-11-08, Oreburgh). route_turn(stream(), context(), Direction::NORTH); - const bool in = m_io.run_into_door(Direction::NORTH, m_walks.can_run()); - stream().log(std::format("[{}] {}: north into the Center: {}.", m_checkpoint, step.name, in ? "faded" : "no door; lining up by sight")); - if (in){ - pbf_wait(context(), 1500ms); - }else{ + const CenterEntry in = run_into_center(m_io, m_walks.can_run(), [this]{ context().wait_for_all_requests(); const VideoSnapshot screen = stream().video().snapshot(); - if (screen && pokemon_center_inside(*screen.frame)){ - stream().log(std::format("[{}] {}: already inside Pokemon Center despite no fade detected.", m_checkpoint, step.name)); - }else{ - enter_lit_door(stream(), context(), label_of(step)); - } + return screen && pokemon_center_inside(*screen.frame); + }, [&]{ + enter_lit_door(stream(), context(), label_of(step)); + }); + stream().log(std::format("[{}] {}: north into the Center: {}.", m_checkpoint, step.name, + in == CenterEntry::FADED ? "faded" : in == CenterEntry::INSIDE ? "no fade, but inside" : "no fade; lined up by sight")); + if (in == CenterEntry::FADED){ + pbf_wait(context(), 1500ms); } talk_to_nurse(stream(), context(), label_of(step)); // Her last line ("We hope to see you again!") can still be up, and a diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index ad3d5f66cd..1b3e30e48d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -192,6 +192,10 @@ bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction stream.log("[Story] run_into_door: white screen fade detected."); }else if (end.ret == 2){ stream.log("[Story] run_into_door: dialog detected."); + }else if (end.went_dark != WallClock::max()){ + // Dark only before dark_from: early, or the door's fade itself. + stream.log(std::format("[Story] run_into_door: timed out; dark {} ms in, before dark_from {} ms.", + std::chrono::duration_cast(end.went_dark - start).count(), dark_from.count())); }else{ stream.log("[Story] run_into_door: timed out without detecting fade."); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index e999b88b76..be662b955a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -50,6 +50,17 @@ std::string label_of(const StoryStep& step){ } // namespace +CenterEntry run_into_center(StoryStepIO& io, bool run, const std::function& inside, const std::function& line_up){ + if (io.run_into_door(Direction::NORTH, run)){ + return CenterEntry::FADED; + } + if (inside()){ + return CenterEntry::INSIDE; + } + line_up(); + return CenterEntry::LINED_UP; +} + void StoryWalkSteps::begin_attempt(const std::string& row){ m_row = row; // A row starts from its save: after the shoes' row, the save has them. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index c5b7493e78..a254b3be5d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -11,6 +11,7 @@ #ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryWalkSteps_H #define PokemonAutomation_PokemonBDSP_AutoStory_StoryWalkSteps_H +#include #include #include #include @@ -23,6 +24,20 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ +// How a run north into a Pokemon Center's door got us in. +enum class CenterEntry{ + FADED, // its fade showed + INSIDE, // no fade, but the inside shows: the run went on in, as + // far as the nurse's counter (lab-B 2026-11-08, Oreburgh) + LINED_UP, // no fade and no inside: lined up with the lit doorway +}; + +// Runs north into the Pokemon Center's door ahead, running with `run`. +// Without a fade, `inside` says whether the Center's inside shows, and if +// not, `line_up` lines up with the lit doorway and walks in (or fails). +CenterEntry run_into_center(StoryStepIO& io, bool run, const std::function& inside, const std::function& line_up); + + // Executes walking and movement-related story steps via StoryStepIO. class StoryWalkSteps{ public: diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index edd52cfb6b..7f23d03e0c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -559,10 +559,17 @@ std::string SimExecutor::off_pose(const Pose& pose) const{ return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), at), Pokemon::to_string(pose)); } +// The program's run into the Center: past its door, the inside shows, a missed fade or not. Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ - if (sync(state.pose) && m_sim.hold(Direction::NORTH, 3000ms, SimPace::RUN).stop != SimStop::WARP){ - return Pokemon::outcome_failed("no_door", step.name + ": no door north of " + to_string(m_sim.player().pos)); + if (!sync(state.pose)){ + return Pokemon::outcome_ok(); } + run_into_center(m_io, m_walks.can_run(), [this]{ + m_misses.fade_unseen = false; + return m_sim.player().warped.has_value(); + }, [&]{ + throw GridSimFailure{step.name + ": no door north of " + to_string(m_sim.player().pos)}; + }); return Pokemon::outcome_ok(); } From be57db15738ed84c5ff2058b32184f036c4856eb Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 11:40:42 -0800 Subject: [PATCH 039/166] BDSP AutoStory: 01.03 lines up below Oreburgh's Center against the walls, as 01.02b does Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 8bee279c95..c09a30b665 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -769,6 +769,14 @@ StoryCheckpoint oreburgh_mine_to_roark(){ anchored(to_walls("up_to_the_mines_sign", {{.direction = NORTH, .tiles = 3}}, "north against the mine's sign (45, 56)"), at(OREBURGH, 45, 57, NORTH)), route("below_the_centers_door_again", below_oreburghs_center(), "up to below the Center's door", "town"), + // The 36-tile run north and the open step east left us off the door's + // column: no fade, and the counter a tile east of the nurse (lab-B + // 2026-11-08 10:39). Line up as 01.02b does, against the walls east + // and north of (48, 22), then one tap west below the door. + legs("south_of_the_centers_door", {{.direction = SOUTH, .tiles = 1}}, "a tap south onto the street"), + anchored(to_walls("against_the_walls_east_of_the_door", {{.direction = EAST, .tiles = 3}, {.direction = NORTH, .tiles = 1}}, + "east against the wall at (49, 22), north against the wall at (48, 20)"), at(OREBURGH, 48, 21, NORTH)), + anchored(legs("below_the_centers_door_lined_up", {{.direction = WEST, .tiles = 1}}, "a tap west below the door"), below_oreburghs_center()), heal("heal_oreburgh", "the nurse; out onto the doorstep, where 01.04 starts", out_of_oreburgh_center()), }); } From f0280b90ac9b85bde97c6ee76eb47dcd2e97a463 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 11:44:36 -0800 Subject: [PATCH 040/166] BDSP AutoStory: grid sim test for 01.03's approach below Oreburgh's Center from off the grid The table's steps from below_the_centers_door_again up to the heal, walked on the grid sim with the start nudged part of a tile by a stick tap, must end on (47, 21) on the grid, and a walk north from there must warp. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 158 ++++++++++++++++++ 1 file changed, 158 insertions(+) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 242d6c59b3..9c81e50310 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -24,7 +24,9 @@ #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" #include "PokemonBDSP_AutoStory_GridSim_Tests.h" namespace PokemonAutomation{ @@ -390,6 +392,158 @@ UnitTestResult test_door_routes(Logger& logger){ } +// The story's walking steps on a GridSim: the route walker's IO and walks +// until something stops us (as the story simulation walks them). Anything +// else fails the walk. +class WalkStepsIO : public StoryStepIO{ +public: + WalkStepsIO(GridSim& sim, GridSimRouteIO& route) + : m_sim(sim) + , m_route(route) + {} + + virtual RouteIO& route() override{ + return m_route; + } + virtual void fight(const std::string& trainer) override{ + unsupported("a fight with " + trainer); + } + virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string& label) override{ + m_sim.tap(direction, ROUTE_TURN_TAP, false); + const Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); + const SimMove move = m_sim.hold(direction, limit, SimPace::WALK); + if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ + m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); + } + } + virtual bool run_until_map(Direction, Milliseconds, const std::string& map, const std::string&) override{ + unsupported("a run onto " + map); + return false; + } + virtual bool run_into_door(Direction, bool, Milliseconds, Milliseconds) override{ + unsupported("a run into a door"); + return false; + } + virtual std::optional tap_to_banner(Direction, const std::string& map, size_t) override{ + unsupported("taps to " + map + "'s banner"); + return std::nullopt; + } + virtual void settle(Button, const std::string& label, bool) override{ + unsupported(label + "'s settle"); + } + +private: + void unsupported(const std::string& what){ + m_route.note(what + " is not simulated here.", RouteNote::FAILURE); + } + + GridSim& m_sim; + GridSimRouteIO& m_route; +}; + +// Row `row`'s steps from `first` up to the one before `last`, and where +// the table has the player before `first`. +struct TableSteps{ + Pose start; + std::vector steps; +}; +std::optional table_steps(const std::string& row, const std::string& first, const std::string& last){ + const std::vector& table = story_checkpoints(); + const auto checkpoint = std::find_if(table.begin(), table.end(), [&row](const StoryCheckpoint& item){ return item.id == row; }); + if (checkpoint == table.end()){ + return std::nullopt; + } + std::optional out; + std::optional at = checkpoint->start; + for (const StoryStep& step : checkpoint->steps){ + if (step.name == last){ + return out; + } + if (step.name == first && at){ + out = TableSteps{*at, {}}; + } + if (out){ + out->steps.push_back(step); + } + at = pose_after_step(at, step); + } + return std::nullopt; +} + +// Where a walk of `steps` from `start`, with the player put part of a tile +// off it by a 100 ms stick tap toward `nudge` from the tile behind, ended +// on the simulation, and why it failed if it did. +struct NudgedWalk{ + SimPos nudged; + SimPos end; + std::string failure; +}; +NudgedWalk walk_nudged(const StoryWorld& world, const TableSteps& table, Direction nudge){ + const TilePos start = story_to_world(world, table.start.map, Pokemon::tiles_of(table.start).front()); + const Direction back = static_cast(((int)nudge + 2) % 4); + GridSim sim({.world = &world, .trainers = story_trainers(world)}, start.next(back), Direction::NORTH, true); + sim.tap(nudge, 100ms, true); + NudgedWalk out{.nudged = sim.player().pos}; + std::vector notes; + GridSimRouteIO route_io(sim, notes); + WalkStepsIO io(sim, route_io); + StoryWalkSteps walk(io); + walk.begin_attempt("01.03"); + Pokemon::RunState state{.pose = table.start}; + try{ + for (const StoryStep& step : table.steps){ + const Pokemon::Outcome outcome = step.kind == StoryStepKind::ROUTE ? walk.route(state, step) + : step.kind == StoryStepKind::LEGS ? walk.legs(state, step) + : Pokemon::outcome_failed("not_a_walk", step.name); + if (!outcome.succeeded()){ + out.failure = step.name + ": " + Pokemon::to_string(outcome); + break; + } + state.pose = step.pose_after ? *step.pose_after : outcome.pose ? *outcome.pose : state.pose; + } + }catch (const GridSimFailure& e){ + out.failure = e.message; + } + out.end = sim.player().pos; + return out; +} + +// lab-B 2026-11-08 10:39: 01.03's route up to below Oreburgh's Center ran +// north 36 to the wall up column 46 and tapped east 1 into the open; the +// heal's run north saw no door and ended at the counter a tile east of the +// nurse. A start part of a tile off the grid (a stick tap, as measured) +// rides along the run north and through the open tap. The table's steps +// up to the heal must end on the grid below the door, (47, 21), from +// either side of the start tile, and a walk north must go in. +UnitTestResult test_oreburgh_center_approach(Logger& logger){ + const std::optional table = table_steps("01.03", "below_the_centers_door_again", "heal_oreburgh"); + if (!table){ + return "01.03 has no below_the_centers_door_again before heal_oreburgh."; + } + const StoryWorld& world = *story_plan_world("OreburghCity", "OreburghCity"); + const TilePos below = story_to_world(world, "OreburghCity", {47, 21}); + for (Direction nudge : {Direction::EAST, Direction::WEST}){ + const NudgedWalk walk = walk_nudged(world, *table, nudge); + const std::string from = std::format("from {} (a stick tap {})", to_string(walk.nudged), direction_name(nudge)); + logger.log(std::format("01.03 below the Center's door {}: ended at {}{}", from, to_string(walk.end), + walk.failure.empty() ? "" : ", failed: " + walk.failure)); + if (on_grid(walk.nudged)){ + return "The stick tap left the player on the grid " + from + "."; + } + if (!walk.failure.empty()){ + return std::format("01.03 below the Center's door {}: failed at {}: {}", from, to_string(walk.end), walk.failure); + } + if (walk.end != sim_pos(below)){ + return std::format("01.03 below the Center's door {}: ended at {}, not on (47, 21).", from, to_string(walk.end)); + } + GridSim door({.world = &world}, below, Direction::NORTH, true); + if (door.hold(Direction::NORTH, 3000ms, SimPace::RUN).stop != SimStop::WARP){ + return "01.03: the walk north from (47, 21) did not go through the Center's door."; + } + } + return true; +} + UnitTestResult test_wandering_npc_mechanics(Logger& logger){ StoryWorld world = make_world({ @@ -705,6 +859,10 @@ const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { .input = {"a stick-tap turn misses the Sandgem Center and Jubilife School doors", test_door_routes}, .expectation = {}, }, + { + .input = {"01.03 lines up below Oreburgh's Center door from a start off the grid", test_oreburgh_center_approach}, + .expectation = {}, + }, { .input = {"wandering NPC movement and deterministic seed behavior", test_wandering_npc_mechanics}, .expectation = {}, From 4f13c19bbee3ceaff17ecf0f88efb3378f425d3c Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 11:57:07 -0800 Subject: [PATCH 041/166] BDSP AutoStory: 01.03 crosses Roark's room against the walls, not on counted taps Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryTable.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index c09a30b665..24fbf5fda5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -699,16 +699,12 @@ StoryCheckpoint route_203_to_oreburgh(){ // from the city's (46, 59) we land on its (12, 1); up, from the coal // room's warp we land on its (11, 21) and come out on the city's (45, 59), // below the mine's sign (the old walk north stopped against it, r103). -std::vector legs_below_roark(){ +std::vector legs_around_the_rock(){ return { {.direction = EAST, .tiles = 1}, {.direction = SOUTH, .tiles = 2}, {.direction = WEST, .tiles = 1}, {.direction = SOUTH, .tiles = 5}, - {.direction = EAST, .tiles = 14}, - {.direction = SOUTH, .tiles = 10}, - {.direction = WEST, .tiles = 2}, - {.direction = SOUTH, .tiles = 2}, }; } @@ -751,8 +747,16 @@ StoryCheckpoint oreburgh_mine_to_roark(){ step_into("into_the_coal_room", SOUTH, "down the entrance hall through the cave mouth", at(MINE, 15, 2, SOUTH)), anchored(to_walls("south_to_the_rock", {{.direction = SOUTH, .tiles = 8}}, "south against the corridor rock (15, 11)"), at(MINE, 15, 9, SOUTH)), - anchored(legs("above_roarks_row", legs_below_roark(), "east around rock, across room, down column 29, and onto Roark's row (27, 28)"), - at(MINE, 27, 28, SOUTH)), + anchored(legs("around_the_rock", legs_around_the_rock(), "east around rock and down column 15"), at(MINE, 15, 16, SOUTH)), + // Across the room and down column 29 against the walls, not on counted + // taps: a wild battle on the taps re-planned from an open leg, and the + // row after was one too far south, under Roark's rocks (lab-B + // 2026-11-08 11:55). The passing run's re-plan clipped east to (29, 16) + // and south to (29, 27) (10:35). + anchored(to_walls("down_column_29", {{.direction = EAST, .tiles = 15}, {.direction = SOUTH, .tiles = 12}}, + "east across the room, south down column 29 to its wall"), at(MINE, 29, 27, SOUTH)), + anchored(legs("above_roarks_row", {{.direction = NORTH, .tiles = 1}, {.direction = WEST, .tiles = 2}, {.direction = SOUTH, .tiles = 2}}, + "up 1, west 2, down onto Roark's row (27, 28)"), at(MINE, 27, 28, SOUTH)), // Counted taps along the open row 29 drifted (lab-B 2026-11-07: south 3 // moved 2): west on row 28 stops at the rock (19, 28) east of Roark, // south stops at the wall under row 29, two tiles from below him. From 7c617c1f9b9f846b2632e1291cff17e9020f4e0d Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 12:00:39 -0800 Subject: [PATCH 042/166] BDSP AutoStory: grid sim test for 01.03 across Roark's room from a row off A wild battle on the counted taps through Roark's room (lab-B 2026-11-08 11:55) left the player a row off; the old taps then ended a row too far south and the walk west went under Roark's rocks. From (15, 16) and a row south of it, the table's steps must end on (27, 28), then beside the rock on (20, 29); the old taps must miss from the row south. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 94 +++++++++++++++++-- 1 file changed, 88 insertions(+), 6 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 9c81e50310..89c4ba8bf9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" @@ -478,12 +479,14 @@ struct NudgedWalk{ SimPos end; std::string failure; }; -NudgedWalk walk_nudged(const StoryWorld& world, const TableSteps& table, Direction nudge){ - const TilePos start = story_to_world(world, table.start.map, Pokemon::tiles_of(table.start).front()); - const Direction back = static_cast(((int)nudge + 2) % 4); - GridSim sim({.world = &world, .trainers = story_trainers(world)}, start.next(back), Direction::NORTH, true); - sim.tap(nudge, 100ms, true); - NudgedWalk out{.nudged = sim.player().pos}; +// Where each of `table`'s steps, walked on `sim` from wherever its player +// stands, left the player, and why the walk failed if it did. +struct StepsWalk{ + std::vector> ends; + std::string failure; +}; +StepsWalk walk_steps(GridSim& sim, const TableSteps& table){ + StepsWalk out; std::vector notes; GridSimRouteIO route_io(sim, notes); WalkStepsIO io(sim, route_io); @@ -495,6 +498,7 @@ NudgedWalk walk_nudged(const StoryWorld& world, const TableSteps& table, Directi const Pokemon::Outcome outcome = step.kind == StoryStepKind::ROUTE ? walk.route(state, step) : step.kind == StoryStepKind::LEGS ? walk.legs(state, step) : Pokemon::outcome_failed("not_a_walk", step.name); + out.ends.emplace_back(step.name, sim.player().pos); if (!outcome.succeeded()){ out.failure = step.name + ": " + Pokemon::to_string(outcome); break; @@ -504,6 +508,15 @@ NudgedWalk walk_nudged(const StoryWorld& world, const TableSteps& table, Directi }catch (const GridSimFailure& e){ out.failure = e.message; } + return out; +} +NudgedWalk walk_nudged(const StoryWorld& world, const TableSteps& table, Direction nudge){ + const TilePos start = story_to_world(world, table.start.map, Pokemon::tiles_of(table.start).front()); + const Direction back = static_cast(((int)nudge + 2) % 4); + GridSim sim({.world = &world, .trainers = story_trainers(world)}, start.next(back), Direction::NORTH, true); + sim.tap(nudge, 100ms, true); + NudgedWalk out{.nudged = sim.player().pos}; + out.failure = walk_steps(sim, table).failure; out.end = sim.player().pos; return out; } @@ -545,6 +558,71 @@ UnitTestResult test_oreburgh_center_approach(Logger& logger){ } +// Where `table`'s steps, walked from `start` instead of where the table +// has the player, failed or left the player off `checks`' tiles; empty if +// they did not. +std::string walk_misses(const StoryWorld& world, const TableSteps& table, const TilePos& start, + const std::vector>& checks, Logger& logger){ + GridSim sim({.world = &world, .trainers = story_trainers(world)}, start, Direction::SOUTH, true); + const StepsWalk walk = walk_steps(sim, table); + std::string ends; + for (const auto& [name, end] : walk.ends){ + ends += std::format(" {} {}", name, to_string(end)); + } + logger.log(std::format("from {}:{}{}", Pokemon::to_string(start), ends, walk.failure.empty() ? "" : ", failed: " + walk.failure)); + if (!walk.failure.empty()){ + return std::format("from {}: failed at {}: {}", Pokemon::to_string(start), to_string(sim.player().pos), walk.failure); + } + for (const auto& [name, tile] : checks){ + const auto end = std::find_if(walk.ends.begin(), walk.ends.end(), [&name](const auto& item){ return item.first == name; }); + if (end == walk.ends.end() || end->second != sim_pos(tile)){ + return std::format("from {}: {} ended{}, not on {}.", Pokemon::to_string(start), name, + end == walk.ends.end() ? " nowhere" : " at " + to_string(end->second), Pokemon::to_string(tile)); + } + } + return {}; +} + +// Roark's room the old way: counted taps across the room, down column 29 +// and onto his row, then west against the rock east of him. +TableSteps old_taps_across_roarks_room(const StoryStep& beside_the_rock){ + StoryStep taps; + taps.kind = StoryStepKind::LEGS; + taps.name = "above_roarks_row"; + taps.legs = { + {.direction = Direction::EAST, .tiles = 14}, {.direction = Direction::SOUTH, .tiles = 10}, + {.direction = Direction::WEST, .tiles = 2}, {.direction = Direction::SOUTH, .tiles = 2}, + }; + return {Pokemon::tile_pose("OreburghMine", {TilePos{15, 16}}, Direction::SOUTH), {taps, beside_the_rock}}; +} + +// lab-B 2026-11-08 11:55: a wild battle on 01.03's counted taps through +// Roark's room re-planned from an open leg and left us a row off; the taps +// after landed a row too far south, the walk west to the rock east of Roark +// went under his rocks, and no one answered the talk. From (15, 16), where +// the table has us before the room, and from a row south of it, the walk +// across must end on Roark's row at (27, 28), then against the rock at +// (20, 29). The old taps miss from the row south. +UnitTestResult test_roarks_room_from_a_row_off(Logger& logger){ + const std::optional table = table_steps("01.03", "down_column_29", "below_roark"); + if (!table){ + return "01.03 has no down_column_29 before below_roark."; + } + const StoryWorld& world = *story_plan_world("OreburghMine", "OreburghMine"); + const std::vector> checks = {{"above_roarks_row", {27, 28}}, {"beside_roarks_rock", {20, 29}}}; + for (const TilePos& start : {TilePos{15, 16}, TilePos{15, 17}}){ + const std::string miss = walk_misses(world, *table, start, checks, logger); + if (!miss.empty()){ + return "01.03 across Roark's room " + miss; + } + } + const std::string old_miss = walk_misses(world, old_taps_across_roarks_room(table->steps.back()), {15, 17}, checks, logger); + if (old_miss.empty()){ + return "The old taps across Roark's room reached (20, 29) from a row south: the test no longer shows the console's failure."; + } + return true; +} + UnitTestResult test_wandering_npc_mechanics(Logger& logger){ StoryWorld world = make_world({ "#######", @@ -863,6 +941,10 @@ const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { .input = {"01.03 lines up below Oreburgh's Center door from a start off the grid", test_oreburgh_center_approach}, .expectation = {}, }, + { + .input = {"01.03 crosses Roark's room to beside his rock from a row off (lab-B, 2026-11-08)", test_roarks_room_from_a_row_off}, + .expectation = {}, + }, { .input = {"wandering NPC movement and deterministic seed behavior", test_wandering_npc_mechanics}, .expectation = {}, From 24d7fe3774ff13237f8ad24a6e3581455d845dab Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 12:05:08 -0800 Subject: [PATCH 043/166] BDSP AutoStory: the old crate cut runs from where down_column_29 leaves us above_roarks_row now starts at (29, 27); the old cut south into the crate at (29, 28) steps north 1 first, as the old taps stood on (29, 26). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 7f23d03e0c..087b34cf24 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -870,15 +870,14 @@ StoryStep old_mine_hall_19(std::string name, Direction direction){ } // Oreburgh Mine: stepping south at col 29 without bypassing the crate -// hits the wooden crate at (29, 28) on the south leg, a tile down. +// hits the wooden crate at (29, 28) on the south leg, a tile down. From +// (29, 27), where down_column_29 leaves us, as the old taps reached (29, 26). StoryStep old_coal_room_crate_cut(){ StoryStep step; step.kind = StoryStepKind::LEGS; step.name = "above_roarks_row"; step.legs = { - {.direction = Direction::EAST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 2}, - {.direction = Direction::WEST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 5}, - {.direction = Direction::EAST, .tiles = 14}, {.direction = Direction::SOUTH, .tiles = 10}, + {.direction = Direction::NORTH, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 2}, {.direction = Direction::WEST, .tiles = 11}, }; return step; From 53fbfcae0ddf823e0129d02227b08f48b3cca9ed Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 12:45:20 -0800 Subject: [PATCH 044/166] BDSP AutoStory: 01.03 taps across Roark's room to his corner Restores the counted legs across the coal room (E1, S2, W1, S5, E14, S10, W2, S2 from (15, 9)) and adds west 7 to Roark's east corner (20, 28), the north wall above it and his rock to its west; then south 1 against the wall to (20, 29). Replaces around_the_rock, down_column_29 and above_roarks_row. Recovery walk tests: a scripted wild battle on the S5, E14 and S10 legs, with the walker's open legs of more than a tile overshooting one as on lab-B 2026-11-08 11:55, must still end on (20, 28) facing west, then (20, 29). Red until the executor re-plans to the end of the step. The grid sim's old taps from a row off still miss, and the old crate cut is checked as part of to_roarks_corner. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 127 ++++++++++++++++++ .../PokemonBDSP_AutoStory_StoryTable.cpp | 33 ++--- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 41 +++--- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 11 +- 4 files changed, 169 insertions(+), 43 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index f2fb322c31..9294493483 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -8,6 +8,7 @@ * physical cause. Run the real story step and route walker on GridSim. */ #include +#include #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Simulation/PokemonBDSP_AutoStory_GridSim.h" #include "PokemonBDSP_AutoStory_StoryPlaces.h" @@ -146,6 +147,129 @@ class Test_RecoveryWalk : public UnitTest{ private: RecoveryCase m_case; }; + +// The route walker's open legs as lab-B 2026-11-08 11:55 saw one: a leg of +// more than a tile that ends on open ground, not at a wall, goes a tile +// past where it was planned to stop (there, south 5 went 6). The walker is +// not told. A single tap stays tile-exact, and so do the story's own +// counted taps. +class OvershootingRouteIO : public GridSimRouteIO{ +public: + OvershootingRouteIO(GridSim& sim, std::vector& notes, std::vector taps) + : GridSimRouteIO(sim, notes, std::move(taps)), m_sim(sim), m_notes(notes) + {} + virtual WalkResult walk_taps(Direction direction, size_t tiles, const std::string& label) override{ + const WalkResult result = GridSimRouteIO::walk_taps(direction, tiles, label); + if (tiles > 1 && label.ends_with("(open)") && result.stop == WalkStop::LIMIT && sim_can_step(m_sim, direction)){ + m_sim.tap(direction, route_ms_per_tile(direction, MoveSpeed::WALK), false); + m_notes.push_back(std::format("[Sim] {}: overshot a tile {} to {}.", label, direction_name(direction), to_string(m_sim.player().pos))); + } + return result; + } +private: + GridSim& m_sim; + std::vector& m_notes; +}; + +// RecoveryStepIO that also walks to walls, as the story simulation does. +class WallStepIO : public RecoveryStepIO{ +public: + WallStepIO(RouteIO& route, GridSim& sim) : RecoveryStepIO(route), m_sim(sim){} + virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string&) override{ + m_sim.tap(direction, ROUTE_TURN_TAP, false); + m_sim.hold(direction, ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles), SimPace::WALK); + } +private: + GridSim& m_sim; +}; + +const Pokemon::StoryStep& story_step(const std::string& row, const std::string& name){ + for (const Pokemon::StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const Pokemon::StoryStep& step : checkpoint.steps){ + if (checkpoint.id == row && step.name == name){ + return step; + } + } + } + throw GridSimFailure{"no step " + name + " in " + row}; +} + +// lab-B 2026-11-08 11:55: a wild battle on 01.03's counted taps across +// Roark's room re-planned to the end of the interrupted leg, the open tile +// (15, 16); the re-plan's open run south overshot a row, and the taps after +// ran a row off, under Roark's rocks. With a wild battle on the input's +// tap, the table's to_roarks_corner from (15, 9) must end on his corner +// (20, 28) facing west, and beside_roarks_rock on (20, 29). +struct CornerInput{ + std::string name; + std::vector battle; +}; +struct CornerExpectation{ + std::string failure = {}; +}; +struct CornerCase{ + CornerInput input; + CornerExpectation expectation; +}; +class Test_RoarksCorner : public UnitTest{ +public: + explicit Test_RoarksCorner(CornerCase data) + : UnitTest("PokemonBDSP::AutoStory - Recovery walk: 01.03 to Roark's corner, " + data.input.name), m_case(std::move(data)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const StoryWorld& world = *story_plan_world("OreburghMine", "OreburghMine"); + GridSim sim({.world = &world}, world.to_world("OreburghMine", {15, 9}), Direction::SOUTH, true); + std::vector notes; + OvershootingRouteIO route(sim, notes, m_case.input.battle); + WallStepIO io(route, sim); + StoryWalkSteps walks(io); + walks.begin_attempt("01.03"); + Pokemon::RunState state{.pose = Pokemon::tile_pose("OreburghMine", {{15, 9}}, Direction::SOUTH), .flags = {}}; + std::string failure; + try{ + for (const char* name : {"to_roarks_corner", "beside_roarks_rock"}){ + const Pokemon::StoryStep& step = story_step("01.03", name); + failure = walks.legs(state, step).failure; + const auto end = story_to_local(world, "OreburghMine", nearest_tile(sim.player().pos)); + logger.log(std::format("{} ended at {}.", name, to_string(sim.player().pos))); + const std::vector tiles = Pokemon::tiles_of(*step.pose_after); + const bool on_tile = end && std::find(tiles.begin(), tiles.end(), *end) != tiles.end(); + if (failure.empty() && (!on_tile || Pokemon::facing_of(*step.pose_after) != sim.player().facing)){ + failure = std::format("{} ended at {} facing {}, not on {}.", name, to_string(sim.player().pos), + direction_name(sim.player().facing), Pokemon::to_string(*step.pose_after)); + } + if (!failure.empty()){ + break; + } + state.pose = *step.pose_after; + } + }catch (const GridSimFailure& error){ + failure = error.message; + } + for (const std::string& note : notes){ + if (note.find("recovery") != std::string::npos || note.find("overshot") != std::string::npos){ + logger.log(note); + } + } + return failure == m_case.expectation.failure ? UnitTestResult(true) + : UnitTestResult("Expected '" + m_case.expectation.failure + "', got '" + failure + "'"); + } +private: + CornerCase m_case; +}; + +const CornerCase CORNER_CASES[] = { + {.input = {.name = "no battle", .battle = {}}, .expectation = {}}, + {.input = {.name = "battle on south 5 tap 3", + .battle = {{.label = "to_roarks_corner", .direction = Direction::SOUTH, .requested_tiles = 5, .tap = 3}}}, .expectation = {}}, + {.input = {.name = "battle on south 5 tap 5", + .battle = {{.label = "to_roarks_corner", .direction = Direction::SOUTH, .requested_tiles = 5, .tap = 5}}}, .expectation = {}}, + {.input = {.name = "battle on east 14 tap 7", + .battle = {{.label = "to_roarks_corner", .direction = Direction::EAST, .requested_tiles = 14, .tap = 7}}}, .expectation = {}}, + {.input = {.name = "battle on south 10 tap 4", + .battle = {{.label = "to_roarks_corner", .direction = Direction::SOUTH, .requested_tiles = 10, .tap = 4}}}, .expectation = {}}, +}; + } // namespace void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ @@ -163,6 +287,9 @@ void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ for (const RecoveryCase& scenario : CASES){ database.add(scenario); } + for (const CornerCase& scenario : CORNER_CASES){ + database.add(scenario); + } } } // namespace PokemonBDSP } // namespace NintendoSwitch diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 24fbf5fda5..91e3a81bb0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -699,12 +699,24 @@ StoryCheckpoint route_203_to_oreburgh(){ // from the city's (46, 59) we land on its (12, 1); up, from the coal // room's warp we land on its (11, 21) and come out on the city's (45, 59), // below the mine's sign (the old walk north stopped against it, r103). -std::vector legs_around_the_rock(){ +// +// Across the coal room to Roark's east corner (20, 28): the north wall above +// it, his rock (19, 28) to its west. A wild battle on a counted tap re-plans +// to the end of the step, and a step that ends in a corner ends that re-plan +// on wall clips. Lab-B 2026-11-08 11:55: the re-plan went only to the end of +// the interrupted leg, the open tile (15, 16); its last leg, south 5 across +// the open room, overshot a row, and the taps after ran under Roark's rocks. +std::vector legs_to_roarks_corner(){ return { {.direction = EAST, .tiles = 1}, {.direction = SOUTH, .tiles = 2}, {.direction = WEST, .tiles = 1}, {.direction = SOUTH, .tiles = 5}, + {.direction = EAST, .tiles = 14}, + {.direction = SOUTH, .tiles = 10}, + {.direction = WEST, .tiles = 2}, + {.direction = SOUTH, .tiles = 2}, + {.direction = WEST, .tiles = 7}, }; } @@ -747,21 +759,12 @@ StoryCheckpoint oreburgh_mine_to_roark(){ step_into("into_the_coal_room", SOUTH, "down the entrance hall through the cave mouth", at(MINE, 15, 2, SOUTH)), anchored(to_walls("south_to_the_rock", {{.direction = SOUTH, .tiles = 8}}, "south against the corridor rock (15, 11)"), at(MINE, 15, 9, SOUTH)), - anchored(legs("around_the_rock", legs_around_the_rock(), "east around rock and down column 15"), at(MINE, 15, 16, SOUTH)), - // Across the room and down column 29 against the walls, not on counted - // taps: a wild battle on the taps re-planned from an open leg, and the - // row after was one too far south, under Roark's rocks (lab-B - // 2026-11-08 11:55). The passing run's re-plan clipped east to (29, 16) - // and south to (29, 27) (10:35). - anchored(to_walls("down_column_29", {{.direction = EAST, .tiles = 15}, {.direction = SOUTH, .tiles = 12}}, - "east across the room, south down column 29 to its wall"), at(MINE, 29, 27, SOUTH)), - anchored(legs("above_roarks_row", {{.direction = NORTH, .tiles = 1}, {.direction = WEST, .tiles = 2}, {.direction = SOUTH, .tiles = 2}}, - "up 1, west 2, down onto Roark's row (27, 28)"), at(MINE, 27, 28, SOUTH)), + anchored(legs("to_roarks_corner", legs_to_roarks_corner(), "east around the rock, across the room, down column 29, west to Roark's rock"), + at(MINE, 20, 28, WEST)), // Counted taps along the open row 29 drifted (lab-B 2026-11-07: south 3 - // moved 2): west on row 28 stops at the rock (19, 28) east of Roark, - // south stops at the wall under row 29, two tiles from below him. - anchored(to_walls("beside_roarks_rock", {{.direction = WEST, .tiles = 7}, {.direction = SOUTH, .tiles = 1}}, - "west against the rock east of Roark, south against the room's wall"), at(MINE, 20, 29, SOUTH)), + // moved 2): south stops at the wall under row 29, two tiles from below him. + anchored(to_walls("beside_roarks_rock", {{.direction = SOUTH, .tiles = 1}}, "south against the room's wall"), + at(MINE, 20, 29, SOUTH)), anchored(legs("below_roark", {{.direction = WEST, .tiles = 2}}, "west 2 to below Roark"), below_roark), talk("roark", "Roark, north of us between his rocks"), scene("roark_smashes_the_rock", below_roark, "his lines, Rock Smash on the rock east of him, and he walks off"), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 89c4ba8bf9..d7d904e286 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -584,8 +584,9 @@ std::string walk_misses(const StoryWorld& world, const TableSteps& table, const } // Roark's room the old way: counted taps across the room, down column 29 -// and onto his row, then west against the rock east of him. -TableSteps old_taps_across_roarks_room(const StoryStep& beside_the_rock){ +// and onto his row from (15, 16), then west against the rock east of him +// and south against the wall. +TableSteps old_taps_across_roarks_room(){ StoryStep taps; taps.kind = StoryStepKind::LEGS; taps.name = "above_roarks_row"; @@ -593,31 +594,25 @@ TableSteps old_taps_across_roarks_room(const StoryStep& beside_the_rock){ {.direction = Direction::EAST, .tiles = 14}, {.direction = Direction::SOUTH, .tiles = 10}, {.direction = Direction::WEST, .tiles = 2}, {.direction = Direction::SOUTH, .tiles = 2}, }; - return {Pokemon::tile_pose("OreburghMine", {TilePos{15, 16}}, Direction::SOUTH), {taps, beside_the_rock}}; + StoryStep walls; + walls.kind = StoryStepKind::LEGS; + walls.name = "beside_roarks_rock"; + walls.variant = "to_wall"; + walls.legs = {{.direction = Direction::WEST, .tiles = 7}, {.direction = Direction::SOUTH, .tiles = 1}}; + return {Pokemon::tile_pose("OreburghMine", {TilePos{15, 16}}, Direction::SOUTH), {taps, walls}}; } // lab-B 2026-11-08 11:55: a wild battle on 01.03's counted taps through -// Roark's room re-planned from an open leg and left us a row off; the taps -// after landed a row too far south, the walk west to the rock east of Roark -// went under his rocks, and no one answered the talk. From (15, 16), where -// the table has us before the room, and from a row south of it, the walk -// across must end on Roark's row at (27, 28), then against the rock at -// (20, 29). The old taps miss from the row south. +// Roark's room re-planned to the end of the interrupted leg, (15, 16), and +// the re-plan's open run south overshot a row; the taps after landed a row +// too far south, the walk west went under Roark's rocks, and no one +// answered the talk. From a row south of (15, 16), the old taps miss +// beside his rock (20, 29): the sim shows the console's failure. The +// wild battle itself: Recovery walk tests, "01.03 to Roark's corner". UnitTestResult test_roarks_room_from_a_row_off(Logger& logger){ - const std::optional table = table_steps("01.03", "down_column_29", "below_roark"); - if (!table){ - return "01.03 has no down_column_29 before below_roark."; - } const StoryWorld& world = *story_plan_world("OreburghMine", "OreburghMine"); - const std::vector> checks = {{"above_roarks_row", {27, 28}}, {"beside_roarks_rock", {20, 29}}}; - for (const TilePos& start : {TilePos{15, 16}, TilePos{15, 17}}){ - const std::string miss = walk_misses(world, *table, start, checks, logger); - if (!miss.empty()){ - return "01.03 across Roark's room " + miss; - } - } - const std::string old_miss = walk_misses(world, old_taps_across_roarks_room(table->steps.back()), {15, 17}, checks, logger); - if (old_miss.empty()){ + const std::string miss = walk_misses(world, old_taps_across_roarks_room(), {15, 17}, {{"beside_roarks_rock", {20, 29}}}, logger); + if (miss.empty()){ return "The old taps across Roark's room reached (20, 29) from a row south: the test no longer shows the console's failure."; } return true; @@ -942,7 +937,7 @@ const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { .expectation = {}, }, { - .input = {"01.03 crosses Roark's room to beside his rock from a row off (lab-B, 2026-11-08)", test_roarks_room_from_a_row_off}, + .input = {"01.03's old taps across Roark's room miss his rock from a row off (lab-B, 2026-11-08)", test_roarks_room_from_a_row_off}, .expectation = {}, }, { diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 087b34cf24..f9df9e07ae 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -870,14 +870,15 @@ StoryStep old_mine_hall_19(std::string name, Direction direction){ } // Oreburgh Mine: stepping south at col 29 without bypassing the crate -// hits the wooden crate at (29, 28) on the south leg, a tile down. From -// (29, 27), where down_column_29 leaves us, as the old taps reached (29, 26). +// hits the wooden crate at (29, 28) on the south leg, a tile down. StoryStep old_coal_room_crate_cut(){ StoryStep step; step.kind = StoryStepKind::LEGS; - step.name = "above_roarks_row"; + step.name = "to_roarks_corner"; step.legs = { - {.direction = Direction::NORTH, .tiles = 1}, + {.direction = Direction::EAST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 2}, + {.direction = Direction::WEST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 5}, + {.direction = Direction::EAST, .tiles = 14}, {.direction = Direction::SOUTH, .tiles = 10}, {.direction = Direction::SOUTH, .tiles = 2}, {.direction = Direction::WEST, .tiles = 11}, }; return step; @@ -982,7 +983,7 @@ const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { }, { .input = {"01.03, cut corner through coal room crate at col 29", [](Logger& logger){ - return test_story_sim_step_failure(logger, "01.03", old_coal_room_crate_cut(), "01.03 above_roarks_row", "short_leg: south 2 moved 1"); + return test_story_sim_step_failure(logger, "01.03", old_coal_room_crate_cut(), "01.03 to_roarks_corner", "short_leg: south 2 moved 1"); }}, .expectation = {}, }, From 6c65b1b2920ef1c87540fa944d3c3829e946526e Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 12:45:20 -0800 Subject: [PATCH 045/166] BDSP AutoStory: a wild battle on counted taps re-plans to the step's end The recovery after a wild battle on a counted-tap leg walked to the end of that leg and went on tapping the legs left. On lab-B 2026-11-08 11:55 that end was the open tile (15, 16); the re-plan's last leg, south 5 across the open room, overshot a row, and every tap after ran a row off, under Roark's rocks. Now the re-plan goes to where the whole step ends (the remaining legs' counted ends, same policy), faces the step's last leg, and skips the legs left: a step that ends in a corner ends the re-plan on wall clips. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 39 ++++++++++++------- .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 4 +- 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index be662b955a..3f57cbeca9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -6,6 +6,7 @@ #include #include +#include #include "Common/Cpp/Color.h" #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" @@ -222,7 +223,7 @@ std::vector counted_ends(const std::vector& starts, const Poke } // namespace Pose StoryWalkSteps::recover_tapped_leg(const Pose& from, const std::vector& starts, - const std::vector& goals, const Pokemon::StoryLeg& leg, const StoryStep& step){ + const std::vector& goals, Direction facing, const Pokemon::StoryLeg& leg, const StoryStep& step){ const StoryWorld* world = story_plan_world(from.map, from.map); if (world == nullptr){ fail(m_io.route(), "interrupted leg has no recovery world: " + from.map); @@ -242,24 +243,29 @@ Pose StoryWalkSteps::recover_tapped_leg(const Pose& from, const std::vector at = Pokemon::tiles_of(from); - for (const Pokemon::StoryLeg& leg : step.legs){ - turn(leg.direction); - const size_t tiles = (size_t)leg.tiles; - const WalkResult walk = m_io.route().walk_taps(leg.direction, tiles, step.name); - log(std::format("[{}] {}: taps {} moved {} of {} tiles.", m_row, step.name, direction_name(leg.direction), walk.moved_chunks, tiles)); - const auto next = counted_ends(at, leg, one_short_ok ? CountedEndPolicy::ONE_SHORT : CountedEndPolicy::EXACT); + for (auto leg = step.legs.begin(); leg != step.legs.end(); ++leg){ + turn(leg->direction); + const size_t tiles = (size_t)leg->tiles; + const WalkResult walk = m_io.route().walk_taps(leg->direction, tiles, step.name); + log(std::format("[{}] {}: taps {} moved {} of {} tiles.", m_row, step.name, direction_name(leg->direction), walk.moved_chunks, tiles)); + const auto next = counted_ends(at, *leg, policy); if (walk.wild_battles > 0){ if (walk.origin == WalkOrigin::MAY_PRECEDE_LEG){ return Pokemon::outcome_failed("encounter_origin_unknown", step.name); @@ -267,11 +273,14 @@ Outcome StoryWalkSteps::tap_legs(const Pose& from, const StoryStep& step){ if (walk.stop != WalkStop::LIMIT && walk.stop != WalkStop::BLOCKED){ return Pokemon::outcome_failed("interrupted_leg_unconfirmed", step.name); } - at = Pokemon::tiles_of(recover_tapped_leg(from, at, next, leg, step)); - continue; + std::vector ends = next; + for (auto rest = std::next(leg); rest != step.legs.end(); ++rest){ + ends = counted_ends(ends, *rest, policy); + } + return Pokemon::outcome_ok(recover_tapped_leg(from, at, ends, step.legs.back().direction, *leg, step)); } if (walk.moved_chunks + (one_short_ok ? 1 : 0) < tiles){ - return Pokemon::outcome_failed("short_leg", std::format("{} {} moved {}", direction_name(leg.direction), tiles, walk.moved_chunks)); + return Pokemon::outcome_failed("short_leg", std::format("{} {} moved {}", direction_name(leg->direction), tiles, walk.moved_chunks)); } at = next; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index a254b3be5d..987904caf6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -66,9 +66,11 @@ class StoryWalkSteps{ private: Pokemon::Pose walk_to(const Pokemon::Pose& from, const Pokemon::Pose& goal, const Pokemon::StoryStep& step); + // After a wild battle on `leg`'s taps from `starts`: walks to one of + // `goals` from wherever the leg could have left us, then faces `facing`. Pokemon::Pose recover_tapped_leg(const Pokemon::Pose& from, const std::vector& starts, const std::vector& goals, - const Pokemon::StoryLeg& leg, const Pokemon::StoryStep& step); + Pokemon::Direction facing, const Pokemon::StoryLeg& leg, const Pokemon::StoryStep& step); Pokemon::Outcome tap_legs(const Pokemon::Pose& from, const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_dialogue(const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_map(const Pokemon::StoryStep& step); From 20551770be8fc6910c75146167590bb31d72d72f Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 12:57:50 -0800 Subject: [PATCH 046/166] BDSP AutoStory: 01.03 routes to the street west of the Center, not below its door The route to below Oreburgh's Center door ran north to the wall up column 46 and stepped east: at 10:39 the step east ended off the door's column, at 12:04 the run, a column east, went through the door into the Center (lab-B 2026-11-08). Route to (44, 22) instead, the last leg west along row 22, then the walls east and north of (48, 22) and a tap west below the door. The grid sim walks the old and the new steps from the table's start and a column off, with open legs overshooting: the old ones miss, the new ones end on (47, 21). OvershootingRouteIO moves to GridSim for both test files. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 23 ---- .../PokemonBDSP_AutoStory_StoryTable.cpp | 16 +-- .../PokemonBDSP_AutoStory_GridSim.cpp | 9 ++ .../PokemonBDSP_AutoStory_GridSim.h | 16 +++ .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 101 +++++++++++++++++- 5 files changed, 130 insertions(+), 35 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index 9294493483..699b707d67 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -148,29 +148,6 @@ class Test_RecoveryWalk : public UnitTest{ RecoveryCase m_case; }; -// The route walker's open legs as lab-B 2026-11-08 11:55 saw one: a leg of -// more than a tile that ends on open ground, not at a wall, goes a tile -// past where it was planned to stop (there, south 5 went 6). The walker is -// not told. A single tap stays tile-exact, and so do the story's own -// counted taps. -class OvershootingRouteIO : public GridSimRouteIO{ -public: - OvershootingRouteIO(GridSim& sim, std::vector& notes, std::vector taps) - : GridSimRouteIO(sim, notes, std::move(taps)), m_sim(sim), m_notes(notes) - {} - virtual WalkResult walk_taps(Direction direction, size_t tiles, const std::string& label) override{ - const WalkResult result = GridSimRouteIO::walk_taps(direction, tiles, label); - if (tiles > 1 && label.ends_with("(open)") && result.stop == WalkStop::LIMIT && sim_can_step(m_sim, direction)){ - m_sim.tap(direction, route_ms_per_tile(direction, MoveSpeed::WALK), false); - m_notes.push_back(std::format("[Sim] {}: overshot a tile {} to {}.", label, direction_name(direction), to_string(m_sim.player().pos))); - } - return result; - } -private: - GridSim& m_sim; - std::vector& m_notes; -}; - // RecoveryStepIO that also walks to walls, as the story simulation does. class WallStepIO : public RecoveryStepIO{ public: diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 91e3a81bb0..6c7810a06b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -775,13 +775,15 @@ StoryCheckpoint oreburgh_mine_to_roark(){ Pokemon::tile_pose(OREBURGH, {TilePos{45, 59}, TilePos{45, 58}}, NORTH)), anchored(to_walls("up_to_the_mines_sign", {{.direction = NORTH, .tiles = 3}}, "north against the mine's sign (45, 56)"), at(OREBURGH, 45, 57, NORTH)), - route("below_the_centers_door_again", below_oreburghs_center(), "up to below the Center's door", "town"), - // The 36-tile run north and the open step east left us off the door's - // column: no fade, and the counter a tile east of the nurse (lab-B - // 2026-11-08 10:39). Line up as 01.02b does, against the walls east - // and north of (48, 22), then one tap west below the door. - legs("south_of_the_centers_door", {{.direction = SOUTH, .tiles = 1}}, "a tap south onto the street"), - anchored(to_walls("against_the_walls_east_of_the_door", {{.direction = EAST, .tiles = 3}, {.direction = NORTH, .tiles = 1}}, + // Not a route to below the door: its run north up column 46 to the wall + // stopped at row 21 and its open step east ended off the door's column + // (no fade; the counter a tile east of the nurse, lab-B 2026-11-08 + // 10:39), and the same run, a column east, went through the door into + // the Center (12:04). Route to the street west of the door, the last leg + // west along row 22, then line up as 01.02b does, against the walls + // east and north of (48, 22), and one tap west below the door. + route("west_of_the_centers_door", at(OREBURGH, 44, 22, WEST), "up to the street west of the Center's door", "town"), + anchored(to_walls("against_the_walls_east_of_the_door", {{.direction = EAST, .tiles = 4}, {.direction = NORTH, .tiles = 1}}, "east against the wall at (49, 22), north against the wall at (48, 20)"), at(OREBURGH, 48, 21, NORTH)), anchored(legs("below_the_centers_door_lined_up", {{.direction = WEST, .tiles = 1}}, "a tap west below the door"), below_oreburghs_center()), heal("heal_oreburgh", "the nurse; out onto the doorstep, where 01.04 starts", out_of_oreburgh_center()), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp index 909766eb48..7b623b74f0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -439,6 +439,15 @@ WalkResult GridSimRouteIO::walk_taps(Direction direction, size_t tiles, const st return result; } +WalkResult OvershootingRouteIO::walk_taps(Direction direction, size_t tiles, const std::string& label){ + const WalkResult result = GridSimRouteIO::walk_taps(direction, tiles, label); + if (tiles > 1 && label.ends_with("(open)") && result.stop == WalkStop::LIMIT && sim_can_step(m_sim, direction)){ + m_sim.tap(direction, route_ms_per_tile(direction, MoveSpeed::WALK), false); + m_notes.push_back(std::format("[Sim] {}: overshot a tile {} to {}.", label, direction_name(direction), to_string(m_sim.player().pos))); + } + return result; +} + void GridSimRouteIO::press(const RouteInput& input){ for (size_t press = 0; press < input.count; press++){ switch (input.kind){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h index 0535e3f043..ba29eb347d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h @@ -221,6 +221,22 @@ class GridSimRouteIO : public RouteIO{ std::vector m_encounters; }; +// The route walker's open legs as lab-B 2026-11-08 11:55 saw one: a leg of +// more than a tile that ends on open ground, not at a wall, goes a tile +// past where it was planned to stop (there, south 5 went 6). The walker is +// not told. A single tap stays tile-exact, and so do the story's own +// counted taps. +class OvershootingRouteIO : public GridSimRouteIO{ +public: + OvershootingRouteIO(GridSim& sim, std::vector& notes, std::vector taps = {}) + : GridSimRouteIO(sim, notes, std::move(taps)), m_sim(sim), m_notes(notes) + {} + virtual WalkResult walk_taps(Pokemon::Direction direction, size_t tiles, const std::string& label) override; +private: + GridSim& m_sim; + std::vector& m_notes; +}; + // What GridSimRouteIO throws for RouteNote::FAILURE. struct GridSimFailure{ std::string message; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index d7d904e286..ab588a0abd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -485,10 +485,13 @@ struct StepsWalk{ std::vector> ends; std::string failure; }; -StepsWalk walk_steps(GridSim& sim, const TableSteps& table){ +// With `overshoot`, the route's open legs overshoot as OvershootingRouteIO's. +StepsWalk walk_steps(GridSim& sim, const TableSteps& table, bool overshoot = false){ StepsWalk out; std::vector notes; - GridSimRouteIO route_io(sim, notes); + GridSimRouteIO plain_io(sim, notes); + OvershootingRouteIO overshooting_io(sim, notes); + GridSimRouteIO& route_io = overshoot ? overshooting_io : plain_io; WalkStepsIO io(sim, route_io); StoryWalkSteps walk(io); walk.begin_attempt("01.03"); @@ -521,7 +524,7 @@ NudgedWalk walk_nudged(const StoryWorld& world, const TableSteps& table, Directi return out; } -// lab-B 2026-11-08 10:39: 01.03's route up to below Oreburgh's Center ran +// lab-B 2026-11-08 10:39: 01.03's old route up to below Oreburgh's Center ran // north 36 to the wall up column 46 and tapped east 1 into the open; the // heal's run north saw no door and ended at the counter a tile east of the // nurse. A start part of a tile off the grid (a stick tap, as measured) @@ -529,9 +532,9 @@ NudgedWalk walk_nudged(const StoryWorld& world, const TableSteps& table, Directi // up to the heal must end on the grid below the door, (47, 21), from // either side of the start tile, and a walk north must go in. UnitTestResult test_oreburgh_center_approach(Logger& logger){ - const std::optional table = table_steps("01.03", "below_the_centers_door_again", "heal_oreburgh"); + const std::optional table = table_steps("01.03", "west_of_the_centers_door", "heal_oreburgh"); if (!table){ - return "01.03 has no below_the_centers_door_again before heal_oreburgh."; + return "01.03 has no west_of_the_centers_door before heal_oreburgh."; } const StoryWorld& world = *story_plan_world("OreburghCity", "OreburghCity"); const TilePos below = story_to_world(world, "OreburghCity", {47, 21}); @@ -558,6 +561,90 @@ UnitTestResult test_oreburgh_center_approach(Logger& logger){ } +// 01.03's old steps up to the heal: a route to below the door, (47, 21), +// whose last legs are a run north to the wall up column 46 and a step east, +// then a tap south, the walls east and north of (48, 22), and a tap west. +TableSteps old_route_to_below_the_center(){ + StoryStep route; + route.kind = StoryStepKind::ROUTE; + route.name = "below_the_centers_door_again"; + route.target = Pokemon::tile_pose("OreburghCity", {TilePos{47, 21}}, Direction::NORTH); + route.variant = "town"; + StoryStep south; + south.kind = StoryStepKind::LEGS; + south.name = "south_of_the_centers_door"; + south.legs = {{.direction = Direction::SOUTH, .tiles = 1}}; + StoryStep walls; + walls.kind = StoryStepKind::LEGS; + walls.name = "against_the_walls_east_of_the_door"; + walls.variant = "to_wall"; + walls.legs = {{.direction = Direction::EAST, .tiles = 3}, {.direction = Direction::NORTH, .tiles = 1}}; + walls.pose_after = Pokemon::tile_pose("OreburghCity", {TilePos{48, 21}}, Direction::NORTH); + StoryStep west; + west.kind = StoryStepKind::LEGS; + west.name = "below_the_centers_door_lined_up"; + west.legs = {{.direction = Direction::WEST, .tiles = 1}}; + west.pose_after = Pokemon::tile_pose("OreburghCity", {TilePos{47, 21}}, Direction::NORTH); + return {Pokemon::tile_pose("OreburghCity", {TilePos{45, 57}}, Direction::NORTH), {route, south, walls, west}}; +} + +// Where `table`'s steps, walked on a GridSim from `start` (the table has +// the player elsewhere) with open legs overshooting, left the player, and +// why they failed if they did; "" if they ended on (47, 21) and a walk +// north from there went through the Center's door. +std::string center_approach_miss(const StoryWorld& world, const TableSteps& table, const TilePos& start, Logger& logger){ + const TilePos below = story_to_world(world, "OreburghCity", {47, 21}); + GridSim sim({.world = &world, .trainers = story_trainers(world)}, story_to_world(world, "OreburghCity", start), Direction::NORTH, true); + const StepsWalk walk = walk_steps(sim, table, true); + std::string ends; + for (const auto& [name, end] : walk.ends){ + ends += std::format(" {} {}", name, to_string(end)); + } + logger.log(std::format("from {}:{}{}", Pokemon::to_string(start), ends, walk.failure.empty() ? "" : ", failed: " + walk.failure)); + if (!walk.failure.empty()){ + return std::format("from {}: failed at {}: {}", Pokemon::to_string(start), to_string(sim.player().pos), walk.failure); + } + if (sim.player().pos != sim_pos(below)){ + return std::format("from {}: ended at {}, not on (47, 21).", Pokemon::to_string(start), to_string(sim.player().pos)); + } + GridSim door({.world = &world}, below, Direction::NORTH, true); + if (door.hold(Direction::NORTH, 3000ms, SimPace::RUN).stop != SimStop::WARP){ + return "the walk north from (47, 21) did not go through the Center's door."; + } + return ""; +} + +// lab-B 2026-11-08, 01.03 up to Oreburgh's Center from below the mine's +// sign, (45, 57): at 10:39 the old route's run north up column 46 stopped +// at row 21 and its step east ended off the door's column; at 12:04 the +// same run went through the door into the Center, so we were a column east +// of where the table had us. From the table's start and from a column east +// of it (and a row south), with open legs overshooting a tile, the old +// steps must miss and the table's must end on (47, 21) below the door. +UnitTestResult test_oreburgh_center_from_off_starts(Logger& logger){ + const StoryWorld& world = *story_plan_world("OreburghCity", "OreburghCity"); + const std::optional table = table_steps("01.03", "west_of_the_centers_door", "heal_oreburgh"); + if (!table){ + return "01.03 has no west_of_the_centers_door before heal_oreburgh."; + } + const std::vector starts{{45, 57}, {46, 57}, {46, 58}}; + bool old_missed = false; + for (const TilePos& start : starts){ + logger.log("Old steps:"); + const std::string old_miss = center_approach_miss(world, old_route_to_below_the_center(), start, logger); + old_missed = old_missed || !old_miss.empty(); + logger.log("Table's steps:"); + const std::string miss = center_approach_miss(world, *table, start, logger); + if (!miss.empty()){ + return "01.03 up to the Center " + miss; + } + } + if (!old_missed){ + return "The old steps reached (47, 21) from every start: the test no longer shows the console's failure."; + } + return true; +} + // Where `table`'s steps, walked from `start` instead of where the table // has the player, failed or left the player off `checks`' tiles; empty if // they did not. @@ -936,6 +1023,10 @@ const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { .input = {"01.03 lines up below Oreburgh's Center door from a start off the grid", test_oreburgh_center_approach}, .expectation = {}, }, + { + .input = {"01.03 reaches below Oreburgh's Center door from a column off, where the old route ran into the Center", test_oreburgh_center_from_off_starts}, + .expectation = {}, + }, { .input = {"01.03's old taps across Roark's room miss his rock from a row off (lab-B, 2026-11-08)", test_roarks_room_from_a_row_off}, .expectation = {}, From c0f8af54af94cc08f631d11b7495c622fd174526 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 13:17:13 -0800 Subject: [PATCH 047/166] BDSP AutoStory: 01.03 comes out of the mine on the decomp's warp tile The coal room's warp lands on the hall's (12, 21), not (11, 21), and the hall's column 12 comes out on the city's (46, 59), east of the mine's sign (Platinum's events.json; BDSP keeps DP's layout). The walk north to the sign never stopped there (lab-B 2026-11-08, 09:46, 10:39, 12:03) and the route after went up the wrong column, at 12:04 through the Center's door. Pin the column from any of the hall's three exit tiles, or a tile north, against the walls east of the mine, then route to the street west of the door and line up from row 22. A recovery-walk test runs the mine's warps on the grid sim: the old steps miss from column 12, the table's reach below the door from every exit. Drops the earlier sim-only overshoot test and the OvershootingRouteIO move. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 189 ++++++++++++++++++ .../PokemonBDSP_AutoStory_StoryTable.cpp | 47 +++-- .../PokemonBDSP_AutoStory_GridSim.cpp | 9 - .../PokemonBDSP_AutoStory_GridSim.h | 16 -- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 107 +--------- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 2 +- 6 files changed, 231 insertions(+), 139 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index 699b707d67..a8dbe37438 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -9,6 +9,9 @@ */ #include #include +#include +#include +#include #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Simulation/PokemonBDSP_AutoStory_GridSim.h" #include "PokemonBDSP_AutoStory_StoryPlaces.h" @@ -148,6 +151,29 @@ class Test_RecoveryWalk : public UnitTest{ RecoveryCase m_case; }; +// The route walker's open legs as lab-B 2026-11-08 11:55 saw one: a leg of +// more than a tile that ends on open ground, not at a wall, goes a tile +// past where it was planned to stop (there, south 5 went 6). The walker is +// not told. A single tap stays tile-exact, and so do the story's own +// counted taps. +class OvershootingRouteIO : public GridSimRouteIO{ +public: + OvershootingRouteIO(GridSim& sim, std::vector& notes, std::vector taps) + : GridSimRouteIO(sim, notes, std::move(taps)), m_sim(sim), m_notes(notes) + {} + virtual WalkResult walk_taps(Direction direction, size_t tiles, const std::string& label) override{ + const WalkResult result = GridSimRouteIO::walk_taps(direction, tiles, label); + if (tiles > 1 && label.ends_with("(open)") && result.stop == WalkStop::LIMIT && sim_can_step(m_sim, direction)){ + m_sim.tap(direction, route_ms_per_tile(direction, MoveSpeed::WALK), false); + m_notes.push_back(std::format("[Sim] {}: overshot a tile {} to {}.", label, direction_name(direction), to_string(m_sim.player().pos))); + } + return result; + } +private: + GridSim& m_sim; + std::vector& m_notes; +}; + // RecoveryStepIO that also walks to walls, as the story simulation does. class WallStepIO : public RecoveryStepIO{ public: @@ -247,6 +273,168 @@ const CornerCase CORNER_CASES[] = { .battle = {{.label = "to_roarks_corner", .direction = Direction::SOUTH, .requested_tiles = 10, .tap = 4}}}, .expectation = {}}, }; +// The Oreburgh Mine's warps, from the decomp's warp events (Platinum's +// res/field/maps/*/events.json; BDSP keeps DP's layout): the city's five +// warp tiles lead to the hall's three 2-1-2, the hall's back a column +// each, and the coal room's warp to the hall's column 12. +struct WarpLink{ + const char* from_map; + TilePos from; + const char* to_map; + TilePos to; +}; +const WarpLink MINE_WARPS[] = { + {"OreburghCity", {44, 59}, "OreburghMineB1F", {11, 1}}, + {"OreburghCity", {45, 59}, "OreburghMineB1F", {11, 1}}, + {"OreburghCity", {46, 59}, "OreburghMineB1F", {12, 1}}, + {"OreburghCity", {47, 59}, "OreburghMineB1F", {13, 1}}, + {"OreburghCity", {48, 59}, "OreburghMineB1F", {13, 1}}, + {"OreburghMineB1F", {11, 1}, "OreburghCity", {45, 59}}, + {"OreburghMineB1F", {12, 1}, "OreburghCity", {46, 59}}, + {"OreburghMineB1F", {13, 1}, "OreburghCity", {47, 59}}, + {"OreburghMine", {15, 1}, "OreburghMineB1F", {12, 21}}, +}; + +// Puts the player on `map`'s `start` and walks north to a warp, then puts +// them where it lands. Returns where, on which map. +std::pair warp_north(GridSim& sim, const std::string& map, const TilePos& start){ + const StoryWorld& from = *story_plan_world(map, map); + sim.place({.world = &from}, from.to_world(map, start), Direction::NORTH); + if (sim.hold(Direction::NORTH, 20000ms, SimPace::WALK).stop != SimStop::WARP){ + throw GridSimFailure{std::format("no warp north of {} on {}", Pokemon::to_string(start), map)}; + } + const std::optional warp = story_to_local(from, map, *sim.player().warped); + for (const WarpLink& link : MINE_WARPS){ + if (link.from_map == map && warp == link.from){ + const StoryWorld& to = *story_plan_world(link.to_map, link.to_map); + sim.place({.world = &to, .trainers = story_trainers(to)}, to.to_world(link.to_map, link.to), Direction::NORTH); + return {link.to_map, link.to}; + } + } + throw GridSimFailure{std::format("no warp known at {} on {}", warp ? Pokemon::to_string(*warp) : "?", map)}; +} + +// 01.03 out of the mine as the table had it before lab-B 2026-11-08: from +// the city's (45, 59) north against the mine's sign (45, 56), a route to +// below the Center's door (47, 21), a tap south, the walls east and north +// of (48, 22), and a tap west. +std::pair> old_steps_out_of_the_mine(){ + const auto step = [](const char* name, std::vector legs, const char* variant, std::optional end){ + Pokemon::StoryStep out; + out.kind = Pokemon::StoryStepKind::LEGS; + out.name = name; + out.legs = std::move(legs); + out.variant = variant; + if (end){ + out.pose_after = Pokemon::tile_pose("OreburghCity", {*end}, Direction::NORTH); + } + return out; + }; + Pokemon::StoryStep route; + route.kind = Pokemon::StoryStepKind::ROUTE; + route.name = "below_the_centers_door_again"; + route.target = Pokemon::tile_pose("OreburghCity", {TilePos{47, 21}}, Direction::NORTH); + route.variant = "town"; + return {Pokemon::tile_pose("OreburghCity", {TilePos{45, 59}, TilePos{45, 58}}, Direction::NORTH), { + step("up_to_the_mines_sign", {{.direction = Direction::NORTH, .tiles = 3}}, "to_wall", TilePos{45, 57}), + route, + step("south_of_the_centers_door", {{.direction = Direction::SOUTH, .tiles = 1}}, "", std::nullopt), + step("against_the_walls_east_of_the_door", {{.direction = Direction::EAST, .tiles = 3}, {.direction = Direction::NORTH, .tiles = 1}}, + "to_wall", TilePos{48, 21}), + step("below_the_centers_door_lined_up", {{.direction = Direction::WEST, .tiles = 1}}, "", TilePos{47, 21}), + }}; +} +// The table's 01.03 steps out of the mine, from where it has us on the +// city to below the Center's door. +std::pair> table_steps_out_of_the_mine(){ + std::vector steps; + for (const Pokemon::StoryCheckpoint& checkpoint : story_checkpoints()){ + bool on = false; + for (const Pokemon::StoryStep& step : checkpoint.steps){ + on = checkpoint.id == "01.03" && (on || step.name == "off_the_mines_warp_tiles") && step.name != "heal_oreburgh"; + if (on){ + steps.push_back(step); + } + } + } + return {*story_step("01.03", "out_of_the_mine").pose_after, steps}; +} + +// Why `steps`, walked on `sim` from where the player stands, the table +// having them on `pose`, with open legs overshooting, did not end on +// (47, 21) with the Center's door north; "" if they did. +std::string center_miss(GridSim& sim, const std::pair>& steps, Logger& logger){ + std::vector notes; + OvershootingRouteIO route(sim, notes, {}); + WallStepIO io(route, sim); + StoryWalkSteps walks(io); + walks.begin_attempt("01.03"); + Pokemon::RunState state{.pose = steps.first, .flags = {}}; + std::string ends; + try{ + for (const Pokemon::StoryStep& step : steps.second){ + const Pokemon::Outcome outcome = step.kind == Pokemon::StoryStepKind::ROUTE ? walks.route(state, step) : walks.legs(state, step); + ends += std::format(" {} {}", step.name, to_string(sim.player().pos)); + if (!outcome.succeeded()){ + return step.name + ": " + Pokemon::to_string(outcome); + } + state.pose = step.pose_after ? *step.pose_after : outcome.pose ? *outcome.pose : state.pose; + } + }catch (const GridSimFailure& error){ + return error.message; + } + logger.log(" " + ends); + const StoryWorld& city = sim.world(); + if (story_to_local(city, "OreburghCity", nearest_tile(sim.player().pos)) != TilePos{47, 21} || !on_grid(sim.player().pos)){ + return std::format("ended at {}, not on (47, 21).", to_string(sim.player().pos)); + } + return sim.hold(Direction::NORTH, 3000ms, SimPace::RUN).stop == SimStop::WARP ? "" : "no door north of (47, 21)."; +} + +// lab-B 2026-11-08 (09:46, 10:39, 12:03): out of the mine, the walk north +// to the mine's sign never stopped on it, and the route after went up the +// wrong column; at 12:04 it ran through the Center's door. The coal room's +// warp lands us on the hall's column 12, which comes out on the city's +// (46, 59), east of the sign. Up the hall from there, or a column either +// side should the walk drift, and with a hold on a tile past the fade, the +// table's steps must end below the Center's door; the old steps must miss +// from column 12. +class Test_MineExit : public UnitTest{ +public: + Test_MineExit() + : UnitTest("PokemonBDSP::AutoStory - Recovery walk: 01.03 out of the mine on the decomp's warps to below the Center's door") + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + for (int column : {12, 11, 13}){ + for (int past : {0, 1}){ + for (bool old : {true, false}){ + const StoryWorld& room = *story_plan_world("OreburghMine", "OreburghMine"); + GridSim sim({.world = &room}, room.to_world("OreburghMine", {15, 2}), Direction::NORTH, true); + const TilePos hall = warp_north(sim, "OreburghMine", {15, 2}).second; + const TilePos out = warp_north(sim, "OreburghMineB1F", {column, hall.y}).second; + if (past > 0){ + sim.tap(Direction::NORTH, route_ms_per_tile(Direction::NORTH, MoveSpeed::WALK), false); + } + const std::string miss = center_miss(sim, old ? old_steps_out_of_the_mine() : table_steps_out_of_the_mine(), logger); + logger.log(std::format("{} steps, coal room to hall {}, up column {} to the city's {}{}: {}", old ? "Old" : "Table's", + Pokemon::to_string(hall), column, Pokemon::to_string(out), past > 0 ? " and a tile on" : "", miss.empty() ? "below the door" : miss)); + if (old && column == 12 && past == 0 && miss.empty()){ + return "The old steps reached below the door from the decomp's exit: the test no longer shows the console's failure."; + } + if (!old && !miss.empty()){ + return std::format("01.03 out of the mine up the hall's column {}: {}", column, miss); + } + } + } + } + }catch (const GridSimFailure& error){ + return error.message; + } + return true; + } +}; + } // namespace void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ @@ -267,6 +455,7 @@ void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ for (const CornerCase& scenario : CORNER_CASES){ database.add(scenario); } + database.add(); } } // namespace PokemonBDSP } // namespace NintendoSwitch diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 6c7810a06b..14aefac7a3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -695,10 +695,16 @@ StoryCheckpoint route_203_to_oreburgh(){ // // The hall is walked on counted taps, not held: it is a cave, and a wild // battle on a hold toward a fade would read as the fade. Its warp tiles -// are only entered on the step after, which meets no wild Pokemon. Down, -// from the city's (46, 59) we land on its (12, 1); up, from the coal -// room's warp we land on its (11, 21) and come out on the city's (45, 59), -// below the mine's sign (the old walk north stopped against it, r103). +// are only entered on the step after, which meets no wild Pokemon. The +// warps are Platinum's (pret/pokeplatinum res/field/maps/*/events.json; +// BDSP keeps DP's layout): the city's (44..48, 59) lead to the hall's +// (11, 1), (11, 1), (12, 1), (13, 1), (13, 1), and the hall's (11..13, 1) +// back to the city's (45..47, 59), a column each. Down, from the city's +// (46, 59) we land on the hall's (12, 1); up, the coal room's warp (15, 1) +// lands us on the hall's (12, 21), not (11, 21), so the walk north up +// column 12 comes out on the city's (46, 59), east of the mine's sign +// (45, 56): the walk north to it never stopped there (lab-B 2026-11-08, +// 09:46, 10:39 and 12:03). // // Across the coal room to Roark's east corner (20, 28): the north wall above // it, his rock (19, 28) to its west. A wild battle on a counted tap re-plans @@ -770,18 +776,29 @@ StoryCheckpoint oreburgh_mine_to_roark(){ scene("roark_smashes_the_rock", below_roark, "his lines, Rock Smash on the rock east of him, and he walks off"), anchored(legs("below_the_coal_rooms_warp", legs_out_of_coal_room(), "east around crate, up column 29, west across row 17, and up corridor to warp doorstep"), at(MINE, 15, 2, NORTH)), - step_into("up_to_the_hall", NORTH, "the warp tile (15, 1)", at(MINE_HALL, 11, 21, NORTH)), + step_into("up_to_the_hall", NORTH, "the warp tile (15, 1)", at(MINE_HALL, 12, 21, NORTH)), + // Out on the warp tile of the hall's column; any of the three, should + // the walk up the hall drift. step_into("out_of_the_mine", NORTH, "up the entrance hall and out to the city", - Pokemon::tile_pose(OREBURGH, {TilePos{45, 59}, TilePos{45, 58}}, NORTH)), - anchored(to_walls("up_to_the_mines_sign", {{.direction = NORTH, .tiles = 3}}, "north against the mine's sign (45, 56)"), - at(OREBURGH, 45, 57, NORTH)), - // Not a route to below the door: its run north up column 46 to the wall - // stopped at row 21 and its open step east ended off the door's column - // (no fade; the counter a tile east of the nurse, lab-B 2026-11-08 - // 10:39), and the same run, a column east, went through the door into - // the Center (12:04). Route to the street west of the door, the last leg - // west along row 22, then line up as 01.02b does, against the walls - // east and north of (48, 22), and one tap west below the door. + Pokemon::tile_pose(OREBURGH, {TilePos{46, 59}, TilePos{45, 59}, TilePos{47, 59}, TilePos{46, 58}, TilePos{45, 58}, TilePos{47, 58}}, NORTH)), + // Pin the column whichever warp tile we came out on, or a tile north + // of it should the run go on past the fade, with no tap against the + // sign (45, 56): a tap north onto row 58 or 57, east against the wall + // at (49, 58) or (50, 57), a tap north, east against the wall at + // (50, 57) or (50, 56), then south against the wall at (49, 58). + legs("off_the_mines_warp_tiles", {{.direction = NORTH, .tiles = 1}}, "a tap north off the mine's warp tiles"), + anchored(to_walls("east_of_the_mine", {{.direction = EAST, .tiles = 4}}, "east against the wall at (49, 58) or (50, 57)"), + Pokemon::tile_pose(OREBURGH, {TilePos{48, 58}, TilePos{49, 57}}, EAST)), + legs("north_of_row_58", {{.direction = NORTH, .tiles = 1}}, "a tap north onto row 57 or 56"), + anchored(to_walls("against_the_walls_east_of_the_mine", {{.direction = EAST, .tiles = 1}, {.direction = SOUTH, .tiles = 1}}, + "east against the wall at (50, 57) or (50, 56), south against the wall at (49, 58)"), at(OREBURGH, 49, 57, SOUTH)), + // Not a route to below the door: believing us on column 45 when we + // were on 46, its run north to the wall and its open step east ended + // off the door's column (no fade; the counter a tile east of the nurse, + // lab-B 2026-11-08 10:39), and the run went through the door into the + // Center (12:04). Route to the street west of the door, (44, 22), then + // line up as 01.02b does, against the walls east and north of (48, 22), + // and tap west below the door. route("west_of_the_centers_door", at(OREBURGH, 44, 22, WEST), "up to the street west of the Center's door", "town"), anchored(to_walls("against_the_walls_east_of_the_door", {{.direction = EAST, .tiles = 4}, {.direction = NORTH, .tiles = 1}}, "east against the wall at (49, 22), north against the wall at (48, 20)"), at(OREBURGH, 48, 21, NORTH)), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp index 7b623b74f0..909766eb48 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -439,15 +439,6 @@ WalkResult GridSimRouteIO::walk_taps(Direction direction, size_t tiles, const st return result; } -WalkResult OvershootingRouteIO::walk_taps(Direction direction, size_t tiles, const std::string& label){ - const WalkResult result = GridSimRouteIO::walk_taps(direction, tiles, label); - if (tiles > 1 && label.ends_with("(open)") && result.stop == WalkStop::LIMIT && sim_can_step(m_sim, direction)){ - m_sim.tap(direction, route_ms_per_tile(direction, MoveSpeed::WALK), false); - m_notes.push_back(std::format("[Sim] {}: overshot a tile {} to {}.", label, direction_name(direction), to_string(m_sim.player().pos))); - } - return result; -} - void GridSimRouteIO::press(const RouteInput& input){ for (size_t press = 0; press < input.count; press++){ switch (input.kind){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h index ba29eb347d..0535e3f043 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h @@ -221,22 +221,6 @@ class GridSimRouteIO : public RouteIO{ std::vector m_encounters; }; -// The route walker's open legs as lab-B 2026-11-08 11:55 saw one: a leg of -// more than a tile that ends on open ground, not at a wall, goes a tile -// past where it was planned to stop (there, south 5 went 6). The walker is -// not told. A single tap stays tile-exact, and so do the story's own -// counted taps. -class OvershootingRouteIO : public GridSimRouteIO{ -public: - OvershootingRouteIO(GridSim& sim, std::vector& notes, std::vector taps = {}) - : GridSimRouteIO(sim, notes, std::move(taps)), m_sim(sim), m_notes(notes) - {} - virtual WalkResult walk_taps(Pokemon::Direction direction, size_t tiles, const std::string& label) override; -private: - GridSim& m_sim; - std::vector& m_notes; -}; - // What GridSimRouteIO throws for RouteNote::FAILURE. struct GridSimFailure{ std::string message; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index ab588a0abd..ef73e9251d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -485,13 +485,10 @@ struct StepsWalk{ std::vector> ends; std::string failure; }; -// With `overshoot`, the route's open legs overshoot as OvershootingRouteIO's. -StepsWalk walk_steps(GridSim& sim, const TableSteps& table, bool overshoot = false){ +StepsWalk walk_steps(GridSim& sim, const TableSteps& table){ StepsWalk out; std::vector notes; - GridSimRouteIO plain_io(sim, notes); - OvershootingRouteIO overshooting_io(sim, notes); - GridSimRouteIO& route_io = overshoot ? overshooting_io : plain_io; + GridSimRouteIO route_io(sim, notes); WalkStepsIO io(sim, route_io); StoryWalkSteps walk(io); walk.begin_attempt("01.03"); @@ -528,9 +525,10 @@ NudgedWalk walk_nudged(const StoryWorld& world, const TableSteps& table, Directi // north 36 to the wall up column 46 and tapped east 1 into the open; the // heal's run north saw no door and ended at the counter a tile east of the // nurse. A start part of a tile off the grid (a stick tap, as measured) -// rides along the run north and through the open tap. The table's steps -// up to the heal must end on the grid below the door, (47, 21), from -// either side of the start tile, and a walk north must go in. +// rides along a run and through an open tap. The table's steps from its +// route to the street, up to the heal, must end on the grid below the +// door, (47, 21), from either side of the start tile, and a walk north +// must go in. UnitTestResult test_oreburgh_center_approach(Logger& logger){ const std::optional table = table_steps("01.03", "west_of_the_centers_door", "heal_oreburgh"); if (!table){ @@ -561,90 +559,6 @@ UnitTestResult test_oreburgh_center_approach(Logger& logger){ } -// 01.03's old steps up to the heal: a route to below the door, (47, 21), -// whose last legs are a run north to the wall up column 46 and a step east, -// then a tap south, the walls east and north of (48, 22), and a tap west. -TableSteps old_route_to_below_the_center(){ - StoryStep route; - route.kind = StoryStepKind::ROUTE; - route.name = "below_the_centers_door_again"; - route.target = Pokemon::tile_pose("OreburghCity", {TilePos{47, 21}}, Direction::NORTH); - route.variant = "town"; - StoryStep south; - south.kind = StoryStepKind::LEGS; - south.name = "south_of_the_centers_door"; - south.legs = {{.direction = Direction::SOUTH, .tiles = 1}}; - StoryStep walls; - walls.kind = StoryStepKind::LEGS; - walls.name = "against_the_walls_east_of_the_door"; - walls.variant = "to_wall"; - walls.legs = {{.direction = Direction::EAST, .tiles = 3}, {.direction = Direction::NORTH, .tiles = 1}}; - walls.pose_after = Pokemon::tile_pose("OreburghCity", {TilePos{48, 21}}, Direction::NORTH); - StoryStep west; - west.kind = StoryStepKind::LEGS; - west.name = "below_the_centers_door_lined_up"; - west.legs = {{.direction = Direction::WEST, .tiles = 1}}; - west.pose_after = Pokemon::tile_pose("OreburghCity", {TilePos{47, 21}}, Direction::NORTH); - return {Pokemon::tile_pose("OreburghCity", {TilePos{45, 57}}, Direction::NORTH), {route, south, walls, west}}; -} - -// Where `table`'s steps, walked on a GridSim from `start` (the table has -// the player elsewhere) with open legs overshooting, left the player, and -// why they failed if they did; "" if they ended on (47, 21) and a walk -// north from there went through the Center's door. -std::string center_approach_miss(const StoryWorld& world, const TableSteps& table, const TilePos& start, Logger& logger){ - const TilePos below = story_to_world(world, "OreburghCity", {47, 21}); - GridSim sim({.world = &world, .trainers = story_trainers(world)}, story_to_world(world, "OreburghCity", start), Direction::NORTH, true); - const StepsWalk walk = walk_steps(sim, table, true); - std::string ends; - for (const auto& [name, end] : walk.ends){ - ends += std::format(" {} {}", name, to_string(end)); - } - logger.log(std::format("from {}:{}{}", Pokemon::to_string(start), ends, walk.failure.empty() ? "" : ", failed: " + walk.failure)); - if (!walk.failure.empty()){ - return std::format("from {}: failed at {}: {}", Pokemon::to_string(start), to_string(sim.player().pos), walk.failure); - } - if (sim.player().pos != sim_pos(below)){ - return std::format("from {}: ended at {}, not on (47, 21).", Pokemon::to_string(start), to_string(sim.player().pos)); - } - GridSim door({.world = &world}, below, Direction::NORTH, true); - if (door.hold(Direction::NORTH, 3000ms, SimPace::RUN).stop != SimStop::WARP){ - return "the walk north from (47, 21) did not go through the Center's door."; - } - return ""; -} - -// lab-B 2026-11-08, 01.03 up to Oreburgh's Center from below the mine's -// sign, (45, 57): at 10:39 the old route's run north up column 46 stopped -// at row 21 and its step east ended off the door's column; at 12:04 the -// same run went through the door into the Center, so we were a column east -// of where the table had us. From the table's start and from a column east -// of it (and a row south), with open legs overshooting a tile, the old -// steps must miss and the table's must end on (47, 21) below the door. -UnitTestResult test_oreburgh_center_from_off_starts(Logger& logger){ - const StoryWorld& world = *story_plan_world("OreburghCity", "OreburghCity"); - const std::optional table = table_steps("01.03", "west_of_the_centers_door", "heal_oreburgh"); - if (!table){ - return "01.03 has no west_of_the_centers_door before heal_oreburgh."; - } - const std::vector starts{{45, 57}, {46, 57}, {46, 58}}; - bool old_missed = false; - for (const TilePos& start : starts){ - logger.log("Old steps:"); - const std::string old_miss = center_approach_miss(world, old_route_to_below_the_center(), start, logger); - old_missed = old_missed || !old_miss.empty(); - logger.log("Table's steps:"); - const std::string miss = center_approach_miss(world, *table, start, logger); - if (!miss.empty()){ - return "01.03 up to the Center " + miss; - } - } - if (!old_missed){ - return "The old steps reached (47, 21) from every start: the test no longer shows the console's failure."; - } - return true; -} - // Where `table`'s steps, walked from `start` instead of where the table // has the player, failed or left the player off `checks`' tiles; empty if // they did not. @@ -947,7 +861,8 @@ UnitTestResult test_wall_leg_check_at_wall_short_distance_safeguard(Logger& logg } } // Oreburgh Mine B1F: the entrance hall corridor is traversed to and back by -// running south from (12, 1) to (12, 21), and north from (11, 21) to (11, 1). +// running south from (12, 1) to (12, 21), and north from (12, 21), where the +// coal room's warp lands us, to (12, 1). UnitTestResult test_oreburgh_mine_hall_corridor(Logger& logger){ const StoryWorld* world = story_plan_world("OreburghMineB1F", "OreburghMineB1F"); if (world == nullptr){ @@ -968,7 +883,7 @@ UnitTestResult test_oreburgh_mine_hall_corridor(Logger& logger){ if (!err.empty()){ return err; } - err = test_run({11, 21}, Direction::NORTH, {11, 1}, "Northbound"); + err = test_run({12, 21}, Direction::NORTH, {12, 1}, "Northbound"); return err.empty() ? UnitTestResult(true) : UnitTestResult(err); } @@ -1023,10 +938,6 @@ const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { .input = {"01.03 lines up below Oreburgh's Center door from a start off the grid", test_oreburgh_center_approach}, .expectation = {}, }, - { - .input = {"01.03 reaches below Oreburgh's Center door from a column off, where the old route ran into the Center", test_oreburgh_center_from_off_starts}, - .expectation = {}, - }, { .input = {"01.03's old taps across Roark's room miss his rock from a row off (lab-B, 2026-11-08)", test_roarks_room_from_a_row_off}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index f9df9e07ae..c6a90f07ff 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -977,7 +977,7 @@ const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { }, { .input = {"01.03, counted 19 taps north leaves player in hall", [](Logger& logger){ - return test_story_sim_step_failure(logger, "01.03", old_mine_hall_19("out_of_the_mine", Direction::NORTH), "01.03 up_to_the_mines_sign", "warp instead of a stop."); + return test_story_sim_step_failure(logger, "01.03", old_mine_hall_19("out_of_the_mine", Direction::NORTH), "01.03 east_of_the_mine", "warp instead of a stop."); }}, .expectation = {}, }, From 77bcef9a4d7253d1b83c9f771d8373996dac5927 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 13:18:30 -0800 Subject: [PATCH 048/166] BDSP AutoStory: the mine-exit test maps names through story_to_world and reports exceptions Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index a8dbe37438..d16f2aa8f5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -12,6 +12,7 @@ #include #include #include +#include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Simulation/PokemonBDSP_AutoStory_GridSim.h" #include "PokemonBDSP_AutoStory_StoryPlaces.h" @@ -299,7 +300,7 @@ const WarpLink MINE_WARPS[] = { // them where it lands. Returns where, on which map. std::pair warp_north(GridSim& sim, const std::string& map, const TilePos& start){ const StoryWorld& from = *story_plan_world(map, map); - sim.place({.world = &from}, from.to_world(map, start), Direction::NORTH); + sim.place({.world = &from}, story_to_world(from, map, start), Direction::NORTH); if (sim.hold(Direction::NORTH, 20000ms, SimPace::WALK).stop != SimStop::WARP){ throw GridSimFailure{std::format("no warp north of {} on {}", Pokemon::to_string(start), map)}; } @@ -307,7 +308,7 @@ std::pair warp_north(GridSim& sim, const std::string& map, for (const WarpLink& link : MINE_WARPS){ if (link.from_map == map && warp == link.from){ const StoryWorld& to = *story_plan_world(link.to_map, link.to_map); - sim.place({.world = &to, .trainers = story_trainers(to)}, to.to_world(link.to_map, link.to), Direction::NORTH); + sim.place({.world = &to, .trainers = story_trainers(to)}, story_to_world(to, link.to_map, link.to), Direction::NORTH); return {link.to_map, link.to}; } } @@ -410,7 +411,7 @@ class Test_MineExit : public UnitTest{ for (int past : {0, 1}){ for (bool old : {true, false}){ const StoryWorld& room = *story_plan_world("OreburghMine", "OreburghMine"); - GridSim sim({.world = &room}, room.to_world("OreburghMine", {15, 2}), Direction::NORTH, true); + GridSim sim({.world = &room}, story_to_world(room, "OreburghMine", {15, 2}), Direction::NORTH, true); const TilePos hall = warp_north(sim, "OreburghMine", {15, 2}).second; const TilePos out = warp_north(sim, "OreburghMineB1F", {column, hall.y}).second; if (past > 0){ @@ -430,6 +431,8 @@ class Test_MineExit : public UnitTest{ } }catch (const GridSimFailure& error){ return error.message; + }catch (const Exception& error){ + return std::string(error.name()) + ": " + error.message(); } return true; } From f29a4d42648fb6e44faef98d740938d8f610a919 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 13:20:36 -0800 Subject: [PATCH 049/166] BDSP AutoStory: the mine-exit test is a table of cases, old steps expected to miss Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 77 ++++++++++++------- 1 file changed, 49 insertions(+), 28 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index d16f2aa8f5..09108b0eae 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -398,44 +398,63 @@ std::string center_miss(GridSim& sim, const std::pair 0){ - sim.tap(Direction::NORTH, route_ms_per_tile(Direction::NORTH, MoveSpeed::WALK), false); - } - const std::string miss = center_miss(sim, old ? old_steps_out_of_the_mine() : table_steps_out_of_the_mine(), logger); - logger.log(std::format("{} steps, coal room to hall {}, up column {} to the city's {}{}: {}", old ? "Old" : "Table's", - Pokemon::to_string(hall), column, Pokemon::to_string(out), past > 0 ? " and a tile on" : "", miss.empty() ? "below the door" : miss)); - if (old && column == 12 && past == 0 && miss.empty()){ - return "The old steps reached below the door from the decomp's exit: the test no longer shows the console's failure."; - } - if (!old && !miss.empty()){ - return std::format("01.03 out of the mine up the hall's column {}: {}", column, miss); - } - } - } + const StoryWorld& room = *story_plan_world("OreburghMine", "OreburghMine"); + GridSim sim({.world = &room}, story_to_world(room, "OreburghMine", {15, 2}), Direction::NORTH, true); + const TilePos hall = warp_north(sim, "OreburghMine", {15, 2}).second; + const TilePos out = warp_north(sim, "OreburghMineB1F", {m_case.input.hall_column, hall.y}).second; + if (m_case.input.past_the_fade){ + sim.tap(Direction::NORTH, route_ms_per_tile(Direction::NORTH, MoveSpeed::WALK), false); } + miss = center_miss(sim, m_case.input.old_steps ? old_steps_out_of_the_mine() : table_steps_out_of_the_mine(), logger); + logger.log(std::format("Coal room to the hall's {}, up column {} to the city's {}: {}", Pokemon::to_string(hall), + m_case.input.hall_column, Pokemon::to_string(out), miss.empty() ? "below the door" : miss)); }catch (const GridSimFailure& error){ - return error.message; + miss = error.message; }catch (const Exception& error){ - return std::string(error.name()) + ": " + error.message(); + miss = std::string(error.name()) + ": " + error.message(); + } + if (miss.empty() != m_case.expectation.below_the_door){ + return miss.empty() ? "Reached below the door: the test no longer shows the console's failure." : miss; } return true; } +private: + MineExitCase m_case; +}; + +const MineExitCase MINE_EXIT_CASES[] = { + {.input = {.name = "old steps from the hall's column 12", .hall_column = 12, .old_steps = true}, .expectation = {.below_the_door = false}}, + {.input = {.name = "old steps from the hall's column 13", .hall_column = 13, .old_steps = true}, .expectation = {.below_the_door = false}}, + {.input = {.name = "from the hall's column 12", .hall_column = 12}, .expectation = {}}, + {.input = {.name = "from the hall's column 11", .hall_column = 11}, .expectation = {}}, + {.input = {.name = "from the hall's column 13", .hall_column = 13}, .expectation = {}}, + {.input = {.name = "from the hall's column 12, a tile past the fade", .hall_column = 12, .past_the_fade = true}, .expectation = {}}, + {.input = {.name = "from the hall's column 11, a tile past the fade", .hall_column = 11, .past_the_fade = true}, .expectation = {}}, + {.input = {.name = "from the hall's column 13, a tile past the fade", .hall_column = 13, .past_the_fade = true}, .expectation = {}}, }; } // namespace @@ -458,7 +477,9 @@ void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ for (const CornerCase& scenario : CORNER_CASES){ database.add(scenario); } - database.add(); + for (const MineExitCase& scenario : MINE_EXIT_CASES){ + database.add(scenario); + } } } // namespace PokemonBDSP } // namespace NintendoSwitch From 65e145a3bf168ba796d648ed50cb5f84591b815a Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 13:44:02 -0800 Subject: [PATCH 050/166] BDSP AutoStory: a battle on a route leg's first input re-plans too A wild battle on the first tap or hold of a route leg (WalkOrigin:: MAY_PRECEDE_LEG) failed the walk with encounter_origin_unknown, also in the recovery walk after a battle on counted taps. A battle that began before the leg found us on the tile the leg before ended on, so the open leg's tiles from its start hold either way: plan again from them, as for any battle on an open leg, within run()'s eight plans. A wall leg walks on to its wall. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 40 +++++++++++++++++-- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 13 +++--- 2 files changed, 44 insertions(+), 9 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index 09108b0eae..70d3217824 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -29,21 +29,50 @@ using namespace std::chrono_literals; using Pokemon::Direction; using Pokemon::TilePos; +// A wild battle in the recovery walk itself, on its first input of the +// kind: one the console cannot tell from a battle before that input began +// (WalkOrigin::MAY_PRECEDE_LEG). +enum class RecoveryBattle{ NONE, FIRST_TAP, FIRST_HOLD }; + class InterruptingRouteIO : public GridSimRouteIO{ public: InterruptingRouteIO(GridSim& sim, std::vector& notes, - std::vector taps, size_t interrupted_holds) - : GridSimRouteIO(sim, notes, std::move(taps)), m_left(interrupted_holds) + std::vector taps, size_t interrupted_holds, RecoveryBattle recovery_battle = RecoveryBattle::NONE) + : GridSimRouteIO(sim, notes, std::move(taps)), m_notes(notes), m_left(interrupted_holds), m_recovery_battle(recovery_battle) {} virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override{ if (m_left > 0){ m_left--; return {.stop = WalkStop::LIMIT, .walked = 400ms, .wild_battles = 1}; } + if (take_recovery_battle(RecoveryBattle::FIRST_HOLD, walk.label)){ + return {.stop = WalkStop::LIMIT, .walked = 400ms, .wild_battles = 1, .origin = WalkOrigin::MAY_PRECEDE_LEG}; + } return GridSimRouteIO::walk_to_wall(walk); } + virtual WalkResult walk_taps(Direction direction, size_t tiles, const std::string& label) override{ + if (take_recovery_battle(RecoveryBattle::FIRST_TAP, label)){ + WalkResult result = GridSimRouteIO::walk_taps(direction, tiles - 1, label); + result.wild_battles++; + result.moved_chunks++; + result.origin = WalkOrigin::MAY_PRECEDE_LEG; + return result; + } + return GridSimRouteIO::walk_taps(direction, tiles, label); + } private: + bool take_recovery_battle(RecoveryBattle kind, const std::string& label){ + if (m_recovery_battle != kind || label.find("recovery") == std::string::npos){ + return false; + } + m_recovery_battle = RecoveryBattle::NONE; + m_notes.push_back("[Sim] a wild battle on the first input of " + label); + return true; + } + + std::vector& m_notes; size_t m_left; + RecoveryBattle m_recovery_battle; }; // Only walking is needed for this real LEGS step. Unexpected story actions @@ -95,6 +124,7 @@ struct RecoveryInput{ SimEncounterPhase phase = SimEncounterPhase::BEFORE_MOVEMENT; WalkOrigin origin = WalkOrigin::CURRENT_LEG; size_t interrupted_holds = 0; + RecoveryBattle recovery_battle = RecoveryBattle::NONE; }; struct RecoveryExpectation{ std::string failure = {}; @@ -123,7 +153,7 @@ class Test_RecoveryWalk : public UnitTest{ .requested_tiles = m_case.input.tiles, .tap = tap, .phase = m_case.input.phase, .origin = m_case.input.origin}); } std::vector notes; - InterruptingRouteIO route(sim, notes, std::move(taps), m_case.input.interrupted_holds); + InterruptingRouteIO route(sim, notes, std::move(taps), m_case.input.interrupted_holds, m_case.input.recovery_battle); RecoveryStepIO io(route); StoryWalkSteps walks(io); walks.begin_attempt("01.03"); @@ -468,6 +498,10 @@ void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ {.input = {.name = "last west leg recovers position and facing", .taps = {9}, .direction = Direction::WEST, .tiles = 9}, .expectation = {.failure = ""}}, {.input = {.name = "repeat the interrupted recovery hold", .taps = {5}, .interrupted_holds = 1}, .expectation = {.failure = ""}}, {.input = {.name = "recovery hold budget exhausted", .taps = {5}, .interrupted_holds = 10}, .expectation = {.failure = "recovery budget"}}, + // A second battle, in the recovery walk, on its first tap or hold + // (MC seeds 717266 and 331438): the walk plans again to the step's end. + {.input = {.name = "battle on the recovery's first tap", .taps = {5}, .recovery_battle = RecoveryBattle::FIRST_TAP}, .expectation = {.failure = ""}}, + {.input = {.name = "battle on the recovery's first hold", .taps = {5}, .recovery_battle = RecoveryBattle::FIRST_HOLD}, .expectation = {.failure = ""}}, {.input = {.name = "first input may belong to previous leg", .taps = {1}}, .expectation = {.failure = "encounter_origin_unknown"}}, {.input = {.name = "late encounter origin unknown", .taps = {5}, .origin = WalkOrigin::MAY_PRECEDE_LEG}, .expectation = {.failure = "encounter_origin_unknown"}}, }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index cf02a9920e..74ce6f56e1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -417,10 +417,9 @@ bool RouteWalker::finish_interrupted_wall(LegWalk& walk, Milliseconds limit){ if (walk.result.wild_battles == 0){ return false; } + // A battle that may have begun before the hold changes nothing here: + // from where the leg began, it ends at its wall however far it got. for (size_t again = 0; again < 3 && walk.result.wild_battles > 0; again++){ - if (walk.result.origin == WalkOrigin::MAY_PRECEDE_LEG){ - fail(m_io, "encounter_origin_unknown: " + walk.label); - } if (walk.result.stop != WalkStop::LIMIT && walk.result.stop != WalkStop::BLOCKED){ fail(m_io, "unconfirmed transition/dialogue during wall recovery: " + walk.label); } @@ -579,10 +578,12 @@ LegNext RouteWalker::open_leg(LegWalk& walk){ return LegNext::NEXT_LEG; } +// Where an open leg's battle left us: any tile of the leg from where it +// began, none moved to all. A battle that may have begun before the leg +// (WalkOrigin::MAY_PRECEDE_LEG) found us on the tile the leg before ended +// on, since a battle starts on a tile stepped onto, so the same tiles +// hold. Planning again from them is bounded by run()'s plans. LegNext RouteWalker::interrupted_open_leg(LegWalk& walk){ - if (walk.result.origin == WalkOrigin::MAY_PRECEDE_LEG){ - fail(m_io, "encounter_origin_unknown: " + walk.label); - } if (walk.result.stop != WalkStop::LIMIT && walk.result.stop != WalkStop::BLOCKED){ fail(m_io, "interrupted open leg has an unconfirmed dialogue/transition: " + walk.label); } From f2567a2aa2d796863d68ed4d4b19d2055f147bef Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 13:47:19 -0800 Subject: [PATCH 051/166] BDSP AutoStory: a battle on a counted leg's first tap re-plans to the step's end tap_legs failed with encounter_origin_unknown when the battle came on a leg's first tap (WalkOrigin::MAY_PRECEDE_LEG). Such a battle began on the tile the leg before ended on, so the leg's prefixes from its start still hold: localize from them and re-plan to the step's end, as for a battle later in the leg. The Monte Carlo found it on 01.03's to_roarks_corner (seed 90037). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 11 +++++++++-- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 8 ++++---- .../AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h | 4 +++- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index 70d3217824..4e1f966f1a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -302,6 +302,11 @@ const CornerCase CORNER_CASES[] = { .battle = {{.label = "to_roarks_corner", .direction = Direction::EAST, .requested_tiles = 14, .tap = 7}}}, .expectation = {}}, {.input = {.name = "battle on south 10 tap 4", .battle = {{.label = "to_roarks_corner", .direction = Direction::SOUTH, .requested_tiles = 10, .tap = 4}}}, .expectation = {}}, + // On a leg's first tap the battle may have begun before it (MC seed 90037). + {.input = {.name = "battle on east 14 tap 1", + .battle = {{.label = "to_roarks_corner", .direction = Direction::EAST, .requested_tiles = 14, .tap = 1}}}, .expectation = {}}, + {.input = {.name = "battle on south 10 tap 1", + .battle = {{.label = "to_roarks_corner", .direction = Direction::SOUTH, .requested_tiles = 10, .tap = 1}}}, .expectation = {}}, }; // The Oreburgh Mine's warps, from the decomp's warp events (Platinum's @@ -502,8 +507,10 @@ void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ // (MC seeds 717266 and 331438): the walk plans again to the step's end. {.input = {.name = "battle on the recovery's first tap", .taps = {5}, .recovery_battle = RecoveryBattle::FIRST_TAP}, .expectation = {.failure = ""}}, {.input = {.name = "battle on the recovery's first hold", .taps = {5}, .recovery_battle = RecoveryBattle::FIRST_HOLD}, .expectation = {.failure = ""}}, - {.input = {.name = "first input may belong to previous leg", .taps = {1}}, .expectation = {.failure = "encounter_origin_unknown"}}, - {.input = {.name = "late encounter origin unknown", .taps = {5}, .origin = WalkOrigin::MAY_PRECEDE_LEG}, .expectation = {.failure = "encounter_origin_unknown"}}, + // A battle that may have begun before the leg: localized from the + // leg's tiles all the same, and re-planned to the step's end. + {.input = {.name = "first input may belong to previous leg", .taps = {1}}, .expectation = {.failure = ""}}, + {.input = {.name = "late encounter origin unknown", .taps = {5}, .origin = WalkOrigin::MAY_PRECEDE_LEG}, .expectation = {.failure = ""}}, }; for (const RecoveryCase& scenario : CASES){ database.add(scenario); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index 3f57cbeca9..baf3751582 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -252,7 +252,10 @@ Pose StoryWalkSteps::recover_tapped_leg(const Pose& from, const std::vectordirection), walk.moved_chunks, tiles)); const auto next = counted_ends(at, *leg, policy); if (walk.wild_battles > 0){ - if (walk.origin == WalkOrigin::MAY_PRECEDE_LEG){ - return Pokemon::outcome_failed("encounter_origin_unknown", step.name); - } if (walk.stop != WalkStop::LIMIT && walk.stop != WalkStop::BLOCKED){ return Pokemon::outcome_failed("interrupted_leg_unconfirmed", step.name); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h index 0d3d5f6b7a..f83f45ce07 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h @@ -44,7 +44,9 @@ const char* walk_stop_name(WalkStop stop); using WalkArrived = std::function; // An encounter already active at the first input, or found only after a -// leg, may belong to earlier movement. Never localize from this leg alone. +// leg, may belong to earlier movement: it began on the tile that movement +// ended on, so the leg's tiles from its start, none moved to all, still +// hold where we are. enum class WalkOrigin{ CURRENT_LEG, MAY_PRECEDE_LEG }; // Result metrics and terminal state returned by automated walking execution. From 08c93788948cd2b2c42a86e06d88810ff83480b9 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 14:07:30 -0800 Subject: [PATCH 052/166] BDSP AutoStory: the mine-exit test wants 01.03 straight up column 46, past the Hiker Red: the table's steps out of the mine still round the Hiker's rows west of column 46 to the street west of the Center's door. The test now walks the steps with Oreburgh's Hiker on the city (seed sweep too), traces where each walk left the player, and keeps 13:50's steps as a case. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 291 +++++++++++++----- 1 file changed, 221 insertions(+), 70 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index 4e1f966f1a..794a08bc30 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -331,9 +331,19 @@ const WarpLink MINE_WARPS[] = { {"OreburghMine", {15, 1}, "OreburghMineB1F", {12, 21}}, }; +// Oreburgh's Hiker, who wanders (46..48, 25..27) from (47, 26) on the +// Diamond decomp's map: across column 46, the walk north to the Center. +SimWanderer oreburgh_hiker(uint64_t seed, Milliseconds start){ + const StoryWorld& city = *story_plan_world("OreburghCity", "OreburghCity"); + const TilePos first = story_to_world(city, "OreburghCity", {46, 25}); + const TilePos last = story_to_world(city, "OreburghCity", {48, 27}); + return {.name = "hiker_0", .box = {first.x, first.y, last.x, last.y}, .pos = story_to_world(city, "OreburghCity", {47, 26}), + .seed = seed, .step_interval = 2000ms, .time_offset = start}; +} + // Puts the player on `map`'s `start` and walks north to a warp, then puts -// them where it lands. Returns where, on which map. -std::pair warp_north(GridSim& sim, const std::string& map, const TilePos& start){ +// them where it lands, with `wanderers` about. Returns where, on which map. +std::pair warp_north(GridSim& sim, const std::string& map, const TilePos& start, std::vector wanderers = {}){ const StoryWorld& from = *story_plan_world(map, map); sim.place({.world = &from}, story_to_world(from, map, start), Direction::NORTH); if (sim.hold(Direction::NORTH, 20000ms, SimPace::WALK).stop != SimStop::WARP){ @@ -343,52 +353,85 @@ std::pair warp_north(GridSim& sim, const std::string& map, for (const WarpLink& link : MINE_WARPS){ if (link.from_map == map && warp == link.from){ const StoryWorld& to = *story_plan_world(link.to_map, link.to_map); - sim.place({.world = &to, .trainers = story_trainers(to)}, story_to_world(to, link.to_map, link.to), Direction::NORTH); + sim.place({.world = &to, .trainers = story_trainers(to), .wanderers = std::move(wanderers)}, + story_to_world(to, link.to_map, link.to), Direction::NORTH); return {link.to_map, link.to}; } } throw GridSimFailure{std::format("no warp known at {} on {}", warp ? Pokemon::to_string(*warp) : "?", map)}; } +// A LEGS step on Oreburgh City, after which the player stands on one of +// `end` facing `facing` (nowhere said if `end` is empty). +Pokemon::StoryStep city_legs(const char* name, std::vector legs, const char* variant, + std::vector end = {}, Direction facing = Direction::NORTH +){ + Pokemon::StoryStep out; + out.kind = Pokemon::StoryStepKind::LEGS; + out.name = name; + out.legs = std::move(legs); + out.variant = variant; + if (!end.empty()){ + out.pose_after = Pokemon::tile_pose("OreburghCity", end, facing); + } + return out; +} +// A planned route on Oreburgh City to `target`, facing `facing`. +Pokemon::StoryStep city_route(const char* name, TilePos target, Direction facing){ + Pokemon::StoryStep out; + out.kind = Pokemon::StoryStepKind::ROUTE; + out.name = name; + out.target = Pokemon::tile_pose("OreburghCity", {target}, facing); + out.variant = "town"; + out.pose_after = out.target; + return out; +} + +using CitySteps = std::pair>; + // 01.03 out of the mine as the table had it before lab-B 2026-11-08: from // the city's (45, 59) north against the mine's sign (45, 56), a route to // below the Center's door (47, 21), a tap south, the walls east and north // of (48, 22), and a tap west. -std::pair> old_steps_out_of_the_mine(){ - const auto step = [](const char* name, std::vector legs, const char* variant, std::optional end){ - Pokemon::StoryStep out; - out.kind = Pokemon::StoryStepKind::LEGS; - out.name = name; - out.legs = std::move(legs); - out.variant = variant; - if (end){ - out.pose_after = Pokemon::tile_pose("OreburghCity", {*end}, Direction::NORTH); - } - return out; - }; - Pokemon::StoryStep route; - route.kind = Pokemon::StoryStepKind::ROUTE; - route.name = "below_the_centers_door_again"; - route.target = Pokemon::tile_pose("OreburghCity", {TilePos{47, 21}}, Direction::NORTH); - route.variant = "town"; +CitySteps old_steps_out_of_the_mine(){ + Pokemon::StoryStep route = city_route("below_the_centers_door_again", {47, 21}, Direction::NORTH); + route.pose_after.reset(); return {Pokemon::tile_pose("OreburghCity", {TilePos{45, 59}, TilePos{45, 58}}, Direction::NORTH), { - step("up_to_the_mines_sign", {{.direction = Direction::NORTH, .tiles = 3}}, "to_wall", TilePos{45, 57}), + city_legs("up_to_the_mines_sign", {{.direction = Direction::NORTH, .tiles = 3}}, "to_wall", {{45, 57}}), route, - step("south_of_the_centers_door", {{.direction = Direction::SOUTH, .tiles = 1}}, "", std::nullopt), - step("against_the_walls_east_of_the_door", {{.direction = Direction::EAST, .tiles = 3}, {.direction = Direction::NORTH, .tiles = 1}}, - "to_wall", TilePos{48, 21}), - step("below_the_centers_door_lined_up", {{.direction = Direction::WEST, .tiles = 1}}, "", TilePos{47, 21}), + city_legs("south_of_the_centers_door", {{.direction = Direction::SOUTH, .tiles = 1}}, ""), + city_legs("against_the_walls_east_of_the_door", {{.direction = Direction::EAST, .tiles = 3}, {.direction = Direction::NORTH, .tiles = 1}}, + "to_wall", {{48, 21}}), + city_legs("below_the_centers_door_lined_up", {{.direction = Direction::WEST, .tiles = 1}}, "", {{47, 21}}), + }}; +} +// 01.03 out of the mine as the table had it at lab-B 2026-11-08 13:50: pin +// the column against the walls east of the mine, route to the street west +// of the door, (44, 22), and line up against the walls east and north of +// (48, 22). Its route goes round the Hiker's rows west of column 46. +CitySteps previous_steps_out_of_the_mine(){ + return {Pokemon::tile_pose("OreburghCity", {TilePos{46, 59}, TilePos{45, 59}, TilePos{47, 59}, TilePos{46, 58}, TilePos{45, 58}, TilePos{47, 58}}, + Direction::NORTH), { + city_legs("off_the_mines_warp_tiles", {{.direction = Direction::NORTH, .tiles = 1}}, ""), + city_legs("east_of_the_mine", {{.direction = Direction::EAST, .tiles = 4}}, "to_wall", {{48, 58}, {49, 57}}, Direction::EAST), + city_legs("north_of_row_58", {{.direction = Direction::NORTH, .tiles = 1}}, ""), + city_legs("against_the_walls_east_of_the_mine", {{.direction = Direction::EAST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 1}}, + "to_wall", {{49, 57}}, Direction::SOUTH), + city_route("west_of_the_centers_door", {44, 22}, Direction::WEST), + city_legs("against_the_walls_east_of_the_door", {{.direction = Direction::EAST, .tiles = 4}, {.direction = Direction::NORTH, .tiles = 1}}, + "to_wall", {{48, 21}}), + city_legs("below_the_centers_door_lined_up", {{.direction = Direction::WEST, .tiles = 1}}, "", {{47, 21}}), }}; } // The table's 01.03 steps out of the mine, from where it has us on the // city to below the Center's door. -std::pair> table_steps_out_of_the_mine(){ +CitySteps table_steps_out_of_the_mine(){ std::vector steps; for (const Pokemon::StoryCheckpoint& checkpoint : story_checkpoints()){ bool on = false; for (const Pokemon::StoryStep& step : checkpoint.steps){ - on = checkpoint.id == "01.03" && (on || step.name == "off_the_mines_warp_tiles") && step.name != "heal_oreburgh"; - if (on){ + on = checkpoint.id == "01.03" && step.name != "heal_oreburgh" && (on || step.name == "out_of_the_mine"); + if (on && step.name != "out_of_the_mine"){ steps.push_back(step); } } @@ -396,53 +439,120 @@ std::pair> table_steps_out_of_the return {*story_step("01.03", "out_of_the_mine").pose_after, steps}; } -// Why `steps`, walked on `sim` from where the player stands, the table -// having them on `pose`, with open legs overshooting, did not end on -// (47, 21) with the Center's door north; "" if they did. -std::string center_miss(GridSim& sim, const std::pair>& steps, Logger& logger){ +// OvershootingRouteIO that keeps where each walk and tap left the player. +class TracingRouteIO : public OvershootingRouteIO{ +public: + TracingRouteIO(GridSim& sim, std::vector& notes) + : OvershootingRouteIO(sim, notes, {}), m_sim(sim) + {} + virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override{ + const WalkResult result = OvershootingRouteIO::walk_to_wall(walk); + m_trail.push_back(m_sim.player().pos); + return result; + } + virtual WalkResult walk_taps(Direction direction, size_t tiles, const std::string& label) override{ + const WalkResult result = OvershootingRouteIO::walk_taps(direction, tiles, label); + m_trail.push_back(m_sim.player().pos); + return result; + } + void mark(){ + m_trail.push_back(m_sim.player().pos); + } + const std::vector& trail() const{ + return m_trail; + } +private: + GridSim& m_sim; + std::vector m_trail; +}; + +// How `steps` went: why they did not end on (47, 21) with the Center's +// door north ("" if they did), and whether the walk stood west of column +// 46 on the way. +struct CenterWalk{ + std::string miss; + bool west_of_column_46 = false; +}; +bool went_west_of_column_46(const StoryWorld& city, const std::vector& trail){ + return std::any_of(trail.begin(), trail.end(), [&city](const SimPos& pos){ + const std::optional tile = story_to_local(city, "OreburghCity", nearest_tile(pos)); + return tile && tile->x < 46; + }); +} +std::string walk_city_steps(StoryWalkSteps& walks, TracingRouteIO& route, const CitySteps& steps, Logger& logger){ + Pokemon::RunState state{.pose = steps.first, .flags = {}}; + std::string ends; + for (const Pokemon::StoryStep& step : steps.second){ + const Pokemon::Outcome outcome = step.kind == Pokemon::StoryStepKind::ROUTE ? walks.route(state, step) : walks.legs(state, step); + route.mark(); + ends += std::format(" {} {}", step.name, to_string(route.trail().back())); + if (!outcome.succeeded()){ + return step.name + ": " + Pokemon::to_string(outcome); + } + state.pose = step.pose_after ? *step.pose_after : outcome.pose ? *outcome.pose : state.pose; + } + logger.log(" " + ends); + return ""; +} +// Walks `steps` on `sim` from where the player stands, the table having +// them on `steps.first`, with open legs overshooting. +CenterWalk center_walk(GridSim& sim, const CitySteps& steps, Logger& logger){ std::vector notes; - OvershootingRouteIO route(sim, notes, {}); + TracingRouteIO route(sim, notes); WallStepIO io(route, sim); StoryWalkSteps walks(io); walks.begin_attempt("01.03"); - Pokemon::RunState state{.pose = steps.first, .flags = {}}; - std::string ends; + CenterWalk out; try{ - for (const Pokemon::StoryStep& step : steps.second){ - const Pokemon::Outcome outcome = step.kind == Pokemon::StoryStepKind::ROUTE ? walks.route(state, step) : walks.legs(state, step); - ends += std::format(" {} {}", step.name, to_string(sim.player().pos)); - if (!outcome.succeeded()){ - return step.name + ": " + Pokemon::to_string(outcome); - } - state.pose = step.pose_after ? *step.pose_after : outcome.pose ? *outcome.pose : state.pose; - } + out.miss = walk_city_steps(walks, route, steps, logger); }catch (const GridSimFailure& error){ - return error.message; + out.miss = error.message; + }catch (const Exception& error){ + out.miss = std::string(error.name()) + ": " + error.message(); + } + for (const std::string& note : notes){ + if (note.find("waiting") != std::string::npos || note.find("tiles to the wall") != std::string::npos){ + logger.log(" " + note); + } } - logger.log(" " + ends); const StoryWorld& city = sim.world(); + out.west_of_column_46 = went_west_of_column_46(city, route.trail()); + if (!out.miss.empty()){ + return out; + } if (story_to_local(city, "OreburghCity", nearest_tile(sim.player().pos)) != TilePos{47, 21} || !on_grid(sim.player().pos)){ - return std::format("ended at {}, not on (47, 21).", to_string(sim.player().pos)); + out.miss = std::format("ended at {}, not on (47, 21).", to_string(sim.player().pos)); + }else if (sim.hold(Direction::NORTH, 3000ms, SimPace::RUN).stop != SimStop::WARP){ + out.miss = "no door north of (47, 21)."; } - return sim.hold(Direction::NORTH, 3000ms, SimPace::RUN).stop == SimStop::WARP ? "" : "no door north of (47, 21)."; + return out; } // lab-B 2026-11-08 (09:46, 10:39, 12:03): out of the mine, the walk north // to the mine's sign never stopped on it, and the route after went up the // wrong column; at 12:04 it ran through the Center's door. The coal room's // warp lands us on the hall's column 12, which comes out on the city's -// (46, 59), east of the sign. Up the hall from there, or a column either -// side should the walk drift, and with a hold on a tile past the fade, the -// table's steps must end below the Center's door; the old steps miss from -// column 12. +// (46, 59), east of the sign. At 13:50 the steps that pinned the column +// east of the mine went astray too: the hold east from (48, 57) moved 0 +// where the map has (49, 57) open. The table now runs straight north up +// column 46 to the wall at (46, 20), waiting for Oreburgh's Hiker when he +// wanders into the column, and taps east below the door. From the hall's +// column 12, with or without a tile past the fade, and with the Hiker at +// any seed and start time, its steps must end below the door, (47, 21), +// and walk in, never west of column 46. From the hall's other columns the +// count north is far off the map's and the walk must fail. +enum class MineExitSteps{ OLD, PREVIOUS, TABLE }; struct MineExitInput{ std::string name; int hall_column = 12; bool past_the_fade = false; - bool old_steps = false; + MineExitSteps steps = MineExitSteps::TABLE; + // Every seed and start time of the Hiker's, not just the first. + bool every_hiker = false; }; struct MineExitExpectation{ bool below_the_door = true; + std::optional west_of_column_46 = false; }; struct MineExitCase{ MineExitInput input; @@ -455,41 +565,82 @@ class Test_MineExit : public UnitTest{ , m_case(std::move(data)) {} virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - std::string miss; + const std::vector seeds = m_case.input.every_hiker ? std::vector{0, 1, 2, 7, 42, 100, 999, 1337} : std::vector{0}; + const std::vector starts = m_case.input.every_hiker + ? std::vector{0ms, 500ms, 1200ms, 2000ms, 3500ms, 5000ms} : std::vector{0ms}; + for (uint64_t seed : seeds){ + for (Milliseconds start : starts){ + const std::string failure = run_once(oreburgh_hiker(seed, start), logger); + if (!failure.empty()){ + return std::format("the Hiker's seed {}, {} ms in: {}", seed, start.count(), failure); + } + } + } + return true; + } +private: + CitySteps steps() const{ + switch (m_case.input.steps){ + case MineExitSteps::OLD: + return old_steps_out_of_the_mine(); + case MineExitSteps::PREVIOUS: + return previous_steps_out_of_the_mine(); + case MineExitSteps::TABLE: + break; + } + return table_steps_out_of_the_mine(); + } + std::string run_once(const SimWanderer& hiker, Logger& logger) const{ + CenterWalk walk; try{ const StoryWorld& room = *story_plan_world("OreburghMine", "OreburghMine"); GridSim sim({.world = &room}, story_to_world(room, "OreburghMine", {15, 2}), Direction::NORTH, true); const TilePos hall = warp_north(sim, "OreburghMine", {15, 2}).second; - const TilePos out = warp_north(sim, "OreburghMineB1F", {m_case.input.hall_column, hall.y}).second; + const TilePos out = warp_north(sim, "OreburghMineB1F", {m_case.input.hall_column, hall.y}, {hiker}).second; if (m_case.input.past_the_fade){ sim.tap(Direction::NORTH, route_ms_per_tile(Direction::NORTH, MoveSpeed::WALK), false); } - miss = center_miss(sim, m_case.input.old_steps ? old_steps_out_of_the_mine() : table_steps_out_of_the_mine(), logger); - logger.log(std::format("Coal room to the hall's {}, up column {} to the city's {}: {}", Pokemon::to_string(hall), - m_case.input.hall_column, Pokemon::to_string(out), miss.empty() ? "below the door" : miss)); + walk = center_walk(sim, steps(), logger); + logger.log(std::format("Coal room to the hall's {}, up column {} to the city's {}: {}{}", Pokemon::to_string(hall), + m_case.input.hall_column, Pokemon::to_string(out), walk.miss.empty() ? "below the door" : walk.miss, + walk.west_of_column_46 ? ", west of column 46 on the way" : "")); }catch (const GridSimFailure& error){ - miss = error.message; - }catch (const Exception& error){ - miss = std::string(error.name()) + ": " + error.message(); + walk.miss = error.message; } - if (miss.empty() != m_case.expectation.below_the_door){ - return miss.empty() ? "Reached below the door: the test no longer shows the console's failure." : miss; + if (walk.miss.empty() != m_case.expectation.below_the_door){ + return walk.miss.empty() ? "Reached below the door: the test no longer shows the console's failure." : walk.miss; } - return true; + if (m_case.expectation.west_of_column_46 && walk.west_of_column_46 != *m_case.expectation.west_of_column_46){ + return walk.west_of_column_46 ? "The walk went west of column 46." : "The walk stayed on column 46 and east."; + } + return ""; } -private: + MineExitCase m_case; }; const MineExitCase MINE_EXIT_CASES[] = { - {.input = {.name = "old steps from the hall's column 12", .hall_column = 12, .old_steps = true}, .expectation = {.below_the_door = false}}, - {.input = {.name = "old steps from the hall's column 13", .hall_column = 13, .old_steps = true}, .expectation = {.below_the_door = false}}, + {.input = {.name = "old steps from the hall's column 12", .hall_column = 12, .steps = MineExitSteps::OLD}, + .expectation = {.below_the_door = false, .west_of_column_46 = std::nullopt}}, + {.input = {.name = "old steps from the hall's column 13", .hall_column = 13, .steps = MineExitSteps::OLD}, + .expectation = {.below_the_door = false, .west_of_column_46 = std::nullopt}}, + // The steps of 13:50 reach the door on the map, round the Hiker's rows + // to the west. + {.input = {.name = "13:50's steps from the hall's column 12", .hall_column = 12, .steps = MineExitSteps::PREVIOUS}, + .expectation = {.below_the_door = true, .west_of_column_46 = true}}, {.input = {.name = "from the hall's column 12", .hall_column = 12}, .expectation = {}}, - {.input = {.name = "from the hall's column 11", .hall_column = 11}, .expectation = {}}, - {.input = {.name = "from the hall's column 13", .hall_column = 13}, .expectation = {}}, {.input = {.name = "from the hall's column 12, a tile past the fade", .hall_column = 12, .past_the_fade = true}, .expectation = {}}, - {.input = {.name = "from the hall's column 11, a tile past the fade", .hall_column = 11, .past_the_fade = true}, .expectation = {}}, - {.input = {.name = "from the hall's column 13, a tile past the fade", .hall_column = 13, .past_the_fade = true}, .expectation = {}}, + {.input = {.name = "from the hall's column 12, the Hiker at every seed and start time", .hall_column = 12, .every_hiker = true}, + .expectation = {}}, + {.input = {.name = "from the hall's column 12, a tile past the fade, the Hiker at every seed and start time", .hall_column = 12, + .past_the_fade = true, .every_hiker = true}, .expectation = {}}, + // Off column 46 the run north is not the map's 37 or 38 tiles: up + // column 45 it stops at the mine's sign, up column 47 it goes through + // the Center's door. + {.input = {.name = "from the hall's column 11", .hall_column = 11}, + .expectation = {.below_the_door = false, .west_of_column_46 = std::nullopt}}, + {.input = {.name = "from the hall's column 13", .hall_column = 13}, + .expectation = {.below_the_door = false, .west_of_column_46 = std::nullopt}}, }; } // namespace From 0738cd55b562d1dd685cdea289663a015a1cbe59 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 14:13:28 -0800 Subject: [PATCH 053/166] BDSP AutoStory: 01.03 runs straight north up column 46 to the Center Out of the mine on the city's (46, 59) (the decomp's warp from the hall's column 12), or a tile north past the fade, the walk holds north up column 46 to the wall west of the Center's door, (46, 20), then taps east below the door and heals. Replaces the steps that pinned the column against the walls east of the mine and routed to the street west of the door: at 13:50 a hold east from (48, 57) moved 0 where the map has (49, 57) open, and the walk went astray. The new LEGS variant "counted_wall" counts the hold's tiles by time against the map's (37 from (46, 58), 38 from (46, 59)), waits when Oreburgh's Hiker (46..48, 25..27) stops it short, and fails when the count is far off rather than taking the wall as reached. The mine-exit sim test goes green across the Hiker's seeds and start times; from the hall's columns 11 and 13 the count fails loudly. Drops the off-grid approach test of the replaced steps; the 19-taps story sim now fails on map_mismatch. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryExecutor.h | 4 +- .../PokemonBDSP_AutoStory_StoryTable.cpp | 41 +++++-------- ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 2 +- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 31 ++++++++++ .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 1 + .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 61 ------------------- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 2 +- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 59 ++++++++++++++++++ .../PokemonBDSP_AutoStory_PlannedRoute.h | 18 ++++++ 9 files changed, 130 insertions(+), 89 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h index 9ae892480c..ca78ffe2e2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h @@ -123,7 +123,9 @@ class StoryExecutor : public Pokemon::StoryStepExecutor{ // may end a tile short (a door lined up by sight after). Variant // "to_wall": each leg walks until something stops it, for at most its // tiles' time, as measured on the console; the pose is then unknown - // unless the step gives one. + // unless the step gives one. Variant "counted_wall": its one leg walks + // to the wall, waiting out anyone walking about in the way, and fails + // when the tiles walked are far off the map's from the step's start. virtual Pokemon::Outcome legs(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; // One D-pad step `direction`, turning first: onto a scene's trigger or // into a door. Variant "to_banner": one tap into a cave mouth, then diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 14aefac7a3..006a03ddb0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -777,32 +777,23 @@ StoryCheckpoint oreburgh_mine_to_roark(){ anchored(legs("below_the_coal_rooms_warp", legs_out_of_coal_room(), "east around crate, up column 29, west across row 17, and up corridor to warp doorstep"), at(MINE, 15, 2, NORTH)), step_into("up_to_the_hall", NORTH, "the warp tile (15, 1)", at(MINE_HALL, 12, 21, NORTH)), - // Out on the warp tile of the hall's column; any of the three, should - // the walk up the hall drift. + // Out on the city's (46, 59), the warp tile of the hall's column 12 + // (the decomp's warp: the hall's (12, 1) to the city's (46, 59)), or + // a tile north should the walk go on past the fade. On the console + // (lab-B 2026-11-08 13:50) a tap north and a hold east to the wall + // matched the map only from column 46. step_into("out_of_the_mine", NORTH, "up the entrance hall and out to the city", - Pokemon::tile_pose(OREBURGH, {TilePos{46, 59}, TilePos{45, 59}, TilePos{47, 59}, TilePos{46, 58}, TilePos{45, 58}, TilePos{47, 58}}, NORTH)), - // Pin the column whichever warp tile we came out on, or a tile north - // of it should the run go on past the fade, with no tap against the - // sign (45, 56): a tap north onto row 58 or 57, east against the wall - // at (49, 58) or (50, 57), a tap north, east against the wall at - // (50, 57) or (50, 56), then south against the wall at (49, 58). - legs("off_the_mines_warp_tiles", {{.direction = NORTH, .tiles = 1}}, "a tap north off the mine's warp tiles"), - anchored(to_walls("east_of_the_mine", {{.direction = EAST, .tiles = 4}}, "east against the wall at (49, 58) or (50, 57)"), - Pokemon::tile_pose(OREBURGH, {TilePos{48, 58}, TilePos{49, 57}}, EAST)), - legs("north_of_row_58", {{.direction = NORTH, .tiles = 1}}, "a tap north onto row 57 or 56"), - anchored(to_walls("against_the_walls_east_of_the_mine", {{.direction = EAST, .tiles = 1}, {.direction = SOUTH, .tiles = 1}}, - "east against the wall at (50, 57) or (50, 56), south against the wall at (49, 58)"), at(OREBURGH, 49, 57, SOUTH)), - // Not a route to below the door: believing us on column 45 when we - // were on 46, its run north to the wall and its open step east ended - // off the door's column (no fade; the counter a tile east of the nurse, - // lab-B 2026-11-08 10:39), and the run went through the door into the - // Center (12:04). Route to the street west of the door, (44, 22), then - // line up as 01.02b does, against the walls east and north of (48, 22), - // and tap west below the door. - route("west_of_the_centers_door", at(OREBURGH, 44, 22, WEST), "up to the street west of the Center's door", "town"), - anchored(to_walls("against_the_walls_east_of_the_door", {{.direction = EAST, .tiles = 4}, {.direction = NORTH, .tiles = 1}}, - "east against the wall at (49, 22), north against the wall at (48, 20)"), at(OREBURGH, 48, 21, NORTH)), - anchored(legs("below_the_centers_door_lined_up", {{.direction = WEST, .tiles = 1}}, "a tap west below the door"), below_oreburghs_center()), + Pokemon::tile_pose(OREBURGH, {TilePos{46, 59}, TilePos{46, 58}}, NORTH)), + // Straight north up column 46 to the wall west of the Center's door, + // (46, 20): 37 tiles from (46, 58), 38 from (46, 59). Oreburgh's + // Hiker wanders (46..48, 25..27) across it, and the walk waits for + // him. The column was the one the console stopped on at 10:39, and + // it keeps off the street east of the mine, where at 13:50 a hold + // east from (48, 57) moved 0 though the map has (49, 57) open, and + // the walk after went astray. + anchored(legs("north_to_the_centers_wall", {{.direction = NORTH, .tiles = 37}}, + "north up column 46 to the wall west of the Center's door", "counted_wall"), at(OREBURGH, 46, 21, NORTH)), + anchored(legs("east_below_the_centers_door", {{.direction = EAST, .tiles = 1}}, "a tap east below the door"), below_oreburghs_center()), heal("heal_oreburgh", "the nurse; out onto the doorstep, where 01.04 starts", out_of_oreburgh_center()), }); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index c914e56cb8..c16b365d7f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -38,7 +38,7 @@ using Pokemon::TilePos; const std::map>& built_in_variants(){ static const std::map> variants{ {StoryStepKind::ROUTE, {"", "town", "robust", "line"}}, - {StoryStepKind::LEGS, {"", "one_short_ok", "to_wall", "to_dialogue", "to_map"}}, + {StoryStepKind::LEGS, {"", "one_short_ok", "to_wall", "counted_wall", "to_dialogue", "to_map"}}, {StoryStepKind::STEP, {"", "to_banner", "tap"}}, {StoryStepKind::MASH, {"", "a"}}, {StoryStepKind::BATTLE, {"", "doubles", "starter"}}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index baf3751582..514efc1725 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -287,7 +287,38 @@ Outcome StoryWalkSteps::tap_legs(const Pose& from, const StoryStep& step){ return Pokemon::outcome_ok(Pokemon::tile_pose(from.map, at, step.legs.back().direction)); } +// A LEGS step "counted_wall": its one leg held to the wall, its tiles +// counted against the map's from each tile the table may have us on +// (walk_counted_wall_leg()). The leg's tiles are the table's reading of +// the map, and must be among them. +Outcome StoryWalkSteps::counted_wall(const Pose& from, const StoryStep& step){ + const StoryWorld* world = story_plan_world(from.map, from.map); + const std::vector starts = Pokemon::tiles_of(from); + if (step.legs.size() != 1 || world == nullptr || starts.empty()){ + return Pokemon::outcome_failed("counted_wall", std::format("{} legs from {}", step.legs.size(), Pokemon::to_string(from))); + } + const Pokemon::StoryLeg& leg = step.legs.front(); + size_t fewest = SIZE_MAX; + size_t most = 0; + for (const TilePos& pos : starts){ + const size_t tiles = slide_to_wall(*world, story_to_world(*world, from.map, pos), leg.direction).tiles; + fewest = std::min(fewest, tiles); + most = std::max(most, tiles); + } + if ((size_t)leg.tiles < fewest || (size_t)leg.tiles > most){ + return Pokemon::outcome_failed("map_mismatch", + std::format("{} {} where the map has {} to {}", direction_name(leg.direction), leg.tiles, fewest, most)); + } + turn(leg.direction); + walk_counted_wall_leg(m_io.route(), {.direction = leg.direction, .fewest = fewest, .most = most, + .speed = m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK, .label = label_of(step)}); + return Pokemon::outcome_ok(); +} + Outcome StoryWalkSteps::legs(RunState& state, const StoryStep& step){ + if (step.variant == "counted_wall"){ + return counted_wall(state.pose, step); + } if (step.variant == "to_wall"){ for (const Pokemon::StoryLeg& leg : step.legs){ m_io.walk_until_stopped(leg.direction, (size_t)leg.tiles, label_of(step)); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index 987904caf6..a25435dd55 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -72,6 +72,7 @@ class StoryWalkSteps{ const std::vector& starts, const std::vector& goals, Pokemon::Direction facing, const Pokemon::StoryLeg& leg, const Pokemon::StoryStep& step); Pokemon::Outcome tap_legs(const Pokemon::Pose& from, const Pokemon::StoryStep& step); + Pokemon::Outcome counted_wall(const Pokemon::Pose& from, const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_dialogue(const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_map(const Pokemon::StoryStep& step); Pokemon::Outcome tap_to_banner(const Pokemon::StoryStep& step); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index ef73e9251d..190f7409da 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -471,14 +471,6 @@ std::optional table_steps(const std::string& row, const std::string& return std::nullopt; } -// Where a walk of `steps` from `start`, with the player put part of a tile -// off it by a 100 ms stick tap toward `nudge` from the tile behind, ended -// on the simulation, and why it failed if it did. -struct NudgedWalk{ - SimPos nudged; - SimPos end; - std::string failure; -}; // Where each of `table`'s steps, walked on `sim` from wherever its player // stands, left the player, and why the walk failed if it did. struct StepsWalk{ @@ -510,55 +502,6 @@ StepsWalk walk_steps(GridSim& sim, const TableSteps& table){ } return out; } -NudgedWalk walk_nudged(const StoryWorld& world, const TableSteps& table, Direction nudge){ - const TilePos start = story_to_world(world, table.start.map, Pokemon::tiles_of(table.start).front()); - const Direction back = static_cast(((int)nudge + 2) % 4); - GridSim sim({.world = &world, .trainers = story_trainers(world)}, start.next(back), Direction::NORTH, true); - sim.tap(nudge, 100ms, true); - NudgedWalk out{.nudged = sim.player().pos}; - out.failure = walk_steps(sim, table).failure; - out.end = sim.player().pos; - return out; -} - -// lab-B 2026-11-08 10:39: 01.03's old route up to below Oreburgh's Center ran -// north 36 to the wall up column 46 and tapped east 1 into the open; the -// heal's run north saw no door and ended at the counter a tile east of the -// nurse. A start part of a tile off the grid (a stick tap, as measured) -// rides along a run and through an open tap. The table's steps from its -// route to the street, up to the heal, must end on the grid below the -// door, (47, 21), from either side of the start tile, and a walk north -// must go in. -UnitTestResult test_oreburgh_center_approach(Logger& logger){ - const std::optional table = table_steps("01.03", "west_of_the_centers_door", "heal_oreburgh"); - if (!table){ - return "01.03 has no west_of_the_centers_door before heal_oreburgh."; - } - const StoryWorld& world = *story_plan_world("OreburghCity", "OreburghCity"); - const TilePos below = story_to_world(world, "OreburghCity", {47, 21}); - for (Direction nudge : {Direction::EAST, Direction::WEST}){ - const NudgedWalk walk = walk_nudged(world, *table, nudge); - const std::string from = std::format("from {} (a stick tap {})", to_string(walk.nudged), direction_name(nudge)); - logger.log(std::format("01.03 below the Center's door {}: ended at {}{}", from, to_string(walk.end), - walk.failure.empty() ? "" : ", failed: " + walk.failure)); - if (on_grid(walk.nudged)){ - return "The stick tap left the player on the grid " + from + "."; - } - if (!walk.failure.empty()){ - return std::format("01.03 below the Center's door {}: failed at {}: {}", from, to_string(walk.end), walk.failure); - } - if (walk.end != sim_pos(below)){ - return std::format("01.03 below the Center's door {}: ended at {}, not on (47, 21).", from, to_string(walk.end)); - } - GridSim door({.world = &world}, below, Direction::NORTH, true); - if (door.hold(Direction::NORTH, 3000ms, SimPace::RUN).stop != SimStop::WARP){ - return "01.03: the walk north from (47, 21) did not go through the Center's door."; - } - } - return true; -} - - // Where `table`'s steps, walked from `start` instead of where the table // has the player, failed or left the player off `checks`' tiles; empty if // they did not. @@ -934,10 +877,6 @@ const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { .input = {"a stick-tap turn misses the Sandgem Center and Jubilife School doors", test_door_routes}, .expectation = {}, }, - { - .input = {"01.03 lines up below Oreburgh's Center door from a start off the grid", test_oreburgh_center_approach}, - .expectation = {}, - }, { .input = {"01.03's old taps across Roark's room miss his rock from a row off (lab-B, 2026-11-08)", test_roarks_room_from_a_row_off}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index c6a90f07ff..85f4792206 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -977,7 +977,7 @@ const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { }, { .input = {"01.03, counted 19 taps north leaves player in hall", [](Logger& logger){ - return test_story_sim_step_failure(logger, "01.03", old_mine_hall_19("out_of_the_mine", Direction::NORTH), "01.03 east_of_the_mine", "warp instead of a stop."); + return test_story_sim_step_failure(logger, "01.03", old_mine_hall_19("out_of_the_mine", Direction::NORTH), "01.03 north_to_the_centers_wall", "map_mismatch"); }}, .expectation = {}, }, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index 74ce6f56e1..014870b7b5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -882,6 +882,65 @@ void talk_to_npc( fail(io, talk.label + ": no side of " + describe(maps, talk.npc) + " started a dialogue."); } +namespace{ + +// Waits for the way at most this often in one counted leg: Oreburgh's +// Hiker tries a step every 2 s, and may stay or keep to the column. +constexpr size_t COUNTED_WALL_WAITS = 8; + +// A count by time is off by a tile or so a stop. Short of the wall by more +// than WAIT_SHORT_OF is someone in the way (Oreburgh's Hiker stops us 4 +// to 7 tiles short of the Center's wall); past COUNT_SLACK either way at +// the end, the walk is not where the step has us. +constexpr size_t COUNTED_WALL_WAIT_SHORT_OF = 2; +constexpr size_t COUNTED_WALL_COUNT_SLACK = 3; + +// One hold of `leg` to the wall; fails on anything but a stop or the time. +WalkResult hold_counted_wall_leg(RouteIO& io, const CountedWallLeg& leg){ + const WalkResult result = io.walk_to_wall({.direction = leg.direction, + .limit = wall_limit({.direction = leg.direction, .tiles = leg.most}), .label = leg.label, + .options = {.arrived = nullptr, .pace = DpadPace::RUN}}); + if (result.stop != WalkStop::BLOCKED && result.stop != WalkStop::LIMIT){ + fail(io, leg.label + ": " + walk_stop_name(result.stop) + " instead of a stop."); + } + if (result.wild_battles > 0){ + fail(io, leg.label + ": a wild battle on the way; the count of tiles is lost."); + } + return result; +} + +} // namespace + +size_t walk_counted_wall_leg(RouteIO& io, const CountedWallLeg& leg){ + const Milliseconds per_tile = route_ms_per_tile(leg.direction, leg.speed); + const size_t slack = COUNTED_WALL_COUNT_SLACK; + size_t walked = 0; + for (size_t waits = 0;; waits++){ + const WalkResult result = hold_counted_wall_leg(io, leg); + walked += tiles_moved(result, per_tile); + if (result.stop == WalkStop::LIMIT){ + // The stop went unseen: we must be held against the wall. + if (!io.holding_against_wall(leg.direction, leg.label + ": at the wall?")){ + fail(io, leg.label + ": ran out of time after about " + std::to_string(walked) + " tiles, short of the wall."); + } + break; + } + if (walked + COUNTED_WALL_WAIT_SHORT_OF >= leg.fewest || waits == COUNTED_WALL_WAITS){ + break; + } + io.note("[Route] " + leg.label + ": stopped after about " + std::to_string(walked) + + " tiles, short of the wall; waiting for the way to clear.", RouteNote::WARNING); + io.press(WAIT_FOR_THE_WAY); + } + io.note(std::format("[Route] {}: about {} tiles to the wall; the map has {} to {}.", leg.label, walked, leg.fewest, leg.most), + RouteNote::LOG); + if (walked + slack < leg.fewest || walked > leg.most + slack){ + fail(io, std::format("{}: about {} tiles to the wall, where the map has {} to {}: not where the step has us.", + leg.label, walked, leg.fewest, leg.most)); + } + return walked; +} + } // namespace PokemonBDSP diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h index 5995c93a17..0f6efccc0a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h @@ -113,6 +113,24 @@ void talk_to_npc( RouteTrainers& trainers, const NpcTalk& talk ); +// A leg held toward a wall the map has between `fewest` and `most` tiles +// ahead (from each tile the player may stand on), its tiles counted by time +// at `speed`. +struct CountedWallLeg{ + Pokemon::Direction direction; + size_t fewest; + size_t most; + MoveSpeed speed; + std::string label; +}; +// Walks `leg` to its wall and returns about how many tiles it took. Someone +// walking about who stops it short is waited for, and the walk goes on +// (Oreburgh's Hiker crosses column 46 on rows 25 to 27). Fails when the +// count is far off the map's: a walk that went astray is not at its wall +// (lab-B 2026-11-08 13:50: a hold east from (48, 57) moved 0 where the map +// has (49, 57) open), nor is one through a door or into a dialogue. +size_t walk_counted_wall_leg(RouteIO& io, const CountedWallLeg& leg); + } // namespace PokemonBDSP From d71d6b50f3d26dac62b207d705f43187ee6a0b0a Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 14:34:48 -0800 Subject: [PATCH 054/166] BDSP AutoStory 01.04: drop the brightness check for starting in the gym At night (game clock 00:25) the street in front of Oreburgh's Center measured 88, under the gym's 90 threshold, so 01.04 skipped the walk west and talked to the nurse as Roark. 01.04 always starts on the doorstep, so the check had no case to serve. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_Events_Oreburgh.cpp | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Oreburgh.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Oreburgh.cpp index 797e93f38e..ccc6b9aa81 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Oreburgh.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Oreburgh.cpp @@ -41,18 +41,15 @@ namespace{ // 36 to 48 px, so 18 or 19 of them missed the door by a part of a tile. constexpr size_t GYM_DPAD_TAPS_WEST_OF_CENTER = 20; -const uint64_t GYM_DARKER_THAN = 90; void oreburgh_street_to_gym(VideoStream& stream, ProControllerContext& context){ // From the Center's doorstep, straight west along its row to below the // gym's door, then north through it, all on the D-pad (whole tiles; see - // GYM_DPAD_TAPS_WEST_OF_CENTER). A save inside the gym: already there. - // The gym's rock floor is darker than the street (mean brightness 75 - // against 104, r74), which indoors() does not tell apart. + // GYM_DPAD_TAPS_WEST_OF_CENTER). 01.04 always starts on the doorstep: its + // own save, or the walk out of the Center after a loss. A brightness + // check for "already in the gym" (gym 75 against street 104 by day, r74) + // read the street at night (88, game clock 00:25) as the gym and talked + // to the nurse as Roark (lab-B, 2026-11-08 14:25). context.wait_for_all_requests(); - if (in_dim_cave(stream, GYM_DARKER_THAN)){ - stream.log("[Route] 01.04: already in the gym."); - return; - } dpad_tiles(stream, context, DPAD_LEFT, GYM_DPAD_TAPS_WEST_OF_CENTER, "west to the gym's door"); if (dpad_through_door_north(stream, context, "Oreburgh Gym door")){ return; From aa19dfa7f152d0684cf4d5db4cf27e191af7c30f Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 14:56:28 -0800 Subject: [PATCH 055/166] BDSP AutoStory 01.04: 21 taps from below the Center's door to the Gym's 01.03's heal now leaves us below Oreburgh's Center door (47, 21); with only moving taps counted, the old 20 ended on (27, 21), a tile east of the Gym's door (lab-B, 2026-11-08 14:51). The route record now starts there with 21 taps, a StoryMaps test traces them to the Gym's doorstep (red with 20), and the walk tries the columns either side of the door before failing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_Events_Oreburgh.cpp | 14 +++++++++- .../PokemonBDSP_AutoStory_RouteRecords.cpp | 6 ++-- .../PokemonBDSP_AutoStory_StoryMaps_Tests.cpp | 28 +++++++++++++++++++ 3 files changed, 44 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Oreburgh.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Oreburgh.cpp index ccc6b9aa81..c19193dc48 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Oreburgh.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Oreburgh.cpp @@ -39,7 +39,10 @@ namespace{ // time). By hand, after a stick exit, it took 22 taps; the hand exit and // count did not carry over to the program's. Stick holds drift: 160 ms moved // 36 to 48 px, so 18 or 19 of them missed the door by a part of a tile. -constexpr size_t GYM_DPAD_TAPS_WEST_OF_CENTER = 20; +// 2026-11-08 14:51 (lab-B): 01.03's heal now leaves us below the Center's +// door (47, 21), and with only moving taps counted, 20 ended on (27, 21), +// a tile east of the gym's door (26, 20). The map's columns give 21. +constexpr size_t GYM_DPAD_TAPS_WEST_OF_CENTER = 21; void oreburgh_street_to_gym(VideoStream& stream, ProControllerContext& context){ // From the Center's doorstep, straight west along its row to below the @@ -54,6 +57,15 @@ void oreburgh_street_to_gym(VideoStream& stream, ProControllerContext& context){ if (dpad_through_door_north(stream, context, "Oreburgh Gym door")){ return; } + // The gym's wall stopped us: try the column west, then the one east. + dpad_tiles(stream, context, DPAD_LEFT, 1, "a column west of the gym's door"); + if (dpad_through_door_north(stream, context, "Oreburgh Gym door")){ + return; + } + dpad_tiles(stream, context, DPAD_RIGHT, 2, "a column east of the gym's door"); + if (dpad_through_door_north(stream, context, "Oreburgh Gym door")){ + return; + } fail_step(stream, "Oreburgh: no column near the gym's door went in."); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp index 00c53d3832..9e72dad6ec 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp @@ -94,10 +94,10 @@ std::vector segment01_records_to_oreburgh(){ {Direction::EAST, 0, LegEnd::TRANSITION, "into the Oreburgh Gate"}, {Direction::EAST, 0, LegEnd::TRANSITION, "through the Gate into Oreburgh City"}, }, "route203_to_oreburgh(); no start tile: Barry stops us on whichever row we came along"}, - {"01.04", "Oreburgh Pokemon Center doorstep to the Gym", "Oreburgh City", "OreburghCity", true, map_point("OreburghCity", "pokemon_center_doorstep"), { - {Direction::WEST, 20, LegEnd::COUNT, "D-pad taps along the Center's row to below the Gym's door"}, + {"01.04", "Oreburgh Pokemon Center doorstep to the Gym", "Oreburgh City", "OreburghCity", true, Pokemon::TilePos{47, 21}, { + {Direction::WEST, 21, LegEnd::COUNT, "D-pad taps along the Center's row to below the Gym's door"}, {Direction::NORTH, 1, LegEnd::DOOR, "into the Gym (the fade)"}, - }, "oreburgh_street_to_gym(); 20 taps measured on the console (r204 to r215, 3 runs on the same tile); the decomp's Center door is at x 47, the taps say the doorstep is x 46"}, + }, "oreburgh_street_to_gym(); 21 taps; 20 were measured from (46, 21) on the console (r204 to r215, 3 runs on the same tile), and 01.03's heal leaves us below the Center's door (47, 21) (lab-B 2026-11-08 14:51: 20 taps from there ended a tile east of the Gym's door)"}, {"01.04", "Inside the Oreburgh Gym", "Oreburgh Gym", "OreburghGym", true, map_point("OreburghGym", "entrance"), { {Direction::NORTH, 0, LegEnd::NPC, "up column 5 from the entrance to Roark on row 3; the Youngsters at (4, 18) and (7, 11) see the column and stop us on rows 18 and 11 on the way"}, }, "oreburgh_gym_battles(); the Gym's grid from the Diamond decomp (land_data 0228), its trainers and their sight from the events file (zone_event 0046)"}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp index 141fedf46f..48fe3d547e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp @@ -202,6 +202,30 @@ UnitTestResult test_oreburgh_mine_hall(Logger& logger){ return true; } +// 01.04: the D-pad taps west from below Oreburgh's Center door end below +// the Gym's door, where the step north goes in. Red with 20 taps: they ended +// on (27, 21), a tile east of the door (lab-B, 2026-11-08 14:51). +UnitTestResult test_oreburgh_center_to_gym_taps(Logger& logger){ + const RouteRecords::RouteRecord* record = nullptr; + for (const RouteRecords::RouteRecord& item : RouteRecords::all()){ + if (item.checkpoint == "01.04" && item.map_file == "OreburghCity"){ + record = &item; + } + } + if (record == nullptr || !record->start || record->legs.empty()){ + return "No 01.04 record on Oreburgh City with a start tile and legs."; + } + const StoryWorld city = alone("OreburghCity"); + const RouteRecords::RouteLeg& west = record->legs.front(); + const TilePos end = trace_legs(city, *record->start, {{west.direction, west.tiles, false}}).back(); + const TilePos doorstep = map_point("OreburghCity", "gym_doorstep"); + if (end != doorstep){ + return std::format("{} taps west end on ({}, {}), not below the Gym's door ({}, {}).", west.tiles, end.x, end.y, doorstep.x, doorstep.y); + } + logger.log(std::format("Oreburgh: {} taps west from below the Center's door reach the Gym's doorstep.", west.tiles)); + return true; +} + // Each traceable record with a start tile starts on ground, and its legs // counted in whole tiles trace on its map up to the first leg that ends // some other way. @@ -288,6 +312,10 @@ const StoryMapsCase STORY_MAPS_CASES[] = { .input = {"Oreburgh Mine B1F: the entrance hall corridor and warps", test_oreburgh_mine_hall}, .expectation = {}, }, + { + .input = {"Oreburgh: 01.04's taps from the Center's door to the Gym's", test_oreburgh_center_to_gym_taps}, + .expectation = {}, + }, { .input = {"Route records: counted legs trace on their maps", test_route_records}, .expectation = {}, From 0116fe8a2ebda7935d6f82f5855e75dac3298520 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 14:58:06 -0800 Subject: [PATCH 056/166] BDSP AutoStory 01.04: take the Gym's taps from the map's doors The count west from below the Center's door is the columns between the Center's and the Gym's doors on Oreburgh's map, not a hand count. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_Events_Oreburgh.cpp | 30 ++++++++----------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Oreburgh.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Oreburgh.cpp index c19193dc48..ad5b2079fe 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Oreburgh.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Oreburgh.cpp @@ -11,6 +11,7 @@ #include "CommonFramework/VideoPipeline/VideoFeed.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h" @@ -28,32 +29,27 @@ using namespace std::chrono_literals; namespace{ -// Oreburgh, from the street in front of the Pokemon Center (its door or its -// front wall) into the gym, as walked by hand on 2026-10-29: west to the -// cliff, south to the posts, a row up, then 17 tiles east is the gym door's -// column. The hold is checked by the door itself: walk north, and if the -// gym's wall stops us, try the columns either side. -// D-pad moves from the Center's doorstep (as walk_out_of_center() leaves us -// there) to below the gym's door: 20. The program's own runs landed 2 tiles -// west with 22 and 1 tile west with 21 (r217d, r218d, the same tiles each -// time). By hand, after a stick exit, it took 22 taps; the hand exit and -// count did not carry over to the program's. Stick holds drift: 160 ms moved -// 36 to 48 px, so 18 or 19 of them missed the door by a part of a tile. -// 2026-11-08 14:51 (lab-B): 01.03's heal now leaves us below the Center's -// door (47, 21), and with only moving taps counted, 20 ended on (27, 21), -// a tile east of the gym's door (26, 20). The map's columns give 21. -constexpr size_t GYM_DPAD_TAPS_WEST_OF_CENTER = 21; +// 01.04 starts below Oreburgh's Center door (47, 21): 01.03's heal and +// the walk out after a loss both leave us there. The Gym's door is on the +// same street, so the D-pad taps west are the columns between the two +// doors on the map (21). A hand count of 20, from before the maps, ended +// a tile east of the Gym's door (lab-B, 2026-11-08 14:51). +size_t gym_taps_west_of_center(){ + const Pokemon::TilePos center = map_point("OreburghCity", "pokemon_center_door"); + const Pokemon::TilePos gym = map_point("OreburghCity", "gym_door"); + return static_cast(center.x - gym.x); +} void oreburgh_street_to_gym(VideoStream& stream, ProControllerContext& context){ // From the Center's doorstep, straight west along its row to below the // gym's door, then north through it, all on the D-pad (whole tiles; see - // GYM_DPAD_TAPS_WEST_OF_CENTER). 01.04 always starts on the doorstep: its + // gym_taps_west_of_center()). 01.04 always starts on the doorstep: its // own save, or the walk out of the Center after a loss. A brightness // check for "already in the gym" (gym 75 against street 104 by day, r74) // read the street at night (88, game clock 00:25) as the gym and talked // to the nurse as Roark (lab-B, 2026-11-08 14:25). context.wait_for_all_requests(); - dpad_tiles(stream, context, DPAD_LEFT, GYM_DPAD_TAPS_WEST_OF_CENTER, "west to the gym's door"); + dpad_tiles(stream, context, DPAD_LEFT, gym_taps_west_of_center(), "west to the gym's door"); if (dpad_through_door_north(stream, context, "Oreburgh Gym door")){ return; } From 4fc67012cced62bba9106bcc00f443ad1ac6094f Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 15:07:34 -0800 Subject: [PATCH 057/166] BDSP AutoStory: settle after a trainer battle before the Potion Roark's lines after the battle pause for the badge's fanfare; the old "finish the dialogue" stopped in the pause and the Potion's menu failed under his next line (lab-B, 2026-11-08 15:06). Press B on text until the overworld shows with no box for 5 s. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Actions/PokemonBDSP_AutoStory_Talks.cpp | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp index ca70e7b09f..7fd7918154 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp @@ -72,9 +72,27 @@ bool talk_or_fight(VideoStream& stream, ProControllerContext& context, const std route_status(stream, "Fighting " + label + "."); fight_story_battle(stream, context, label, format); // Lines after the battle (Roark's badge, r211d) keep the menu - // from opening: finish them before the Potion. - if (dialogue_opens(stream, context, 3000ms)){ - finish_dialogue(stream, context, BUTTON_B, label + " after the battle"); + // from opening: finish them before the Potion. They pause for + // the badge's fanfare, so "no box for a moment" is not the end: + // after four lines Roark went quiet, the Potion's menu opened + // under his next line and failed (lab-B, 2026-11-08 15:06). + // Done once the overworld shows with no box for 5 s. + auto calm_since = std::chrono::steady_clock::now(); + const auto give_up = calm_since + 60s; + while (std::chrono::steady_clock::now() < give_up){ + context.wait_for_all_requests(); + const auto after = stream.video().snapshot(); + const bool box = after && dialog.detect(*after.frame); + if (box || !after || !overworld.detect(*after.frame)){ + calm_since = std::chrono::steady_clock::now(); + }else if (std::chrono::steady_clock::now() - calm_since >= 5s){ + break; + } + if (box){ + pbf_press_button(context, BUTTON_B, 80ms, 1100ms); + }else{ + pbf_wait(context, 300ms); + } } if (!in_pokemon_center(stream)){ use_potion_first_pokemon(stream, context, 0.8); From 30f5f33f534aad6d6fdada337300d3ba05c7bf75 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 15:08:48 -0800 Subject: [PATCH 058/166] BDSP AutoStory: settle after a trainer battle in its own function Keeps talk_or_fight() under the code-health length limit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Actions/PokemonBDSP_AutoStory_Talks.cpp | 56 +++++++++++-------- 1 file changed, 33 insertions(+), 23 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp index 7fd7918154..c7bb6ce399 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp @@ -53,6 +53,38 @@ bool dialogue_opens(VideoStream& stream, ProControllerContext& context, Millisec return wait_until(stream, context, timeout, {{dialog}}) == 0; } +namespace{ + +// Lines after a trainer battle (Roark's badge, r211d) keep the menu from +// opening: finish them before the Potion. They pause for the badge's +// fanfare, so "no box for a moment" is not the end: after four lines Roark +// went quiet, the Potion's menu opened under his next line and failed +// (lab-B, 2026-10-31 09:45 and 2026-11-08 15:06). Done once the overworld +// shows with no box for 5 s. +void settle_after_battle(VideoStream& stream, ProControllerContext& context){ + ShortDialogDetector dialog; + OverworldDetector overworld; + auto calm_since = std::chrono::steady_clock::now(); + const auto give_up = calm_since + 60s; + while (std::chrono::steady_clock::now() < give_up){ + context.wait_for_all_requests(); + const auto frame = stream.video().snapshot(); + const bool box = frame && dialog.detect(*frame.frame); + if (box || !frame || !overworld.detect(*frame.frame)){ + calm_since = std::chrono::steady_clock::now(); + }else if (std::chrono::steady_clock::now() - calm_since >= 5s){ + return; + } + if (box){ + pbf_press_button(context, BUTTON_B, 80ms, 1100ms); + }else{ + pbf_wait(context, 300ms); + } + } +} + +} // namespace + bool talk_or_fight(VideoStream& stream, ProControllerContext& context, const std::string& label, TalkExpect expect, BattleFormat format){ ShortDialogDetector dialog; OverworldDetector overworld; @@ -71,29 +103,7 @@ bool talk_or_fight(VideoStream& stream, ProControllerContext& context, const std if (battle_menu.detect(*frame.frame) || battle_menu_standard.detect(*frame.frame) || black.detect(*frame.frame)){ route_status(stream, "Fighting " + label + "."); fight_story_battle(stream, context, label, format); - // Lines after the battle (Roark's badge, r211d) keep the menu - // from opening: finish them before the Potion. They pause for - // the badge's fanfare, so "no box for a moment" is not the end: - // after four lines Roark went quiet, the Potion's menu opened - // under his next line and failed (lab-B, 2026-11-08 15:06). - // Done once the overworld shows with no box for 5 s. - auto calm_since = std::chrono::steady_clock::now(); - const auto give_up = calm_since + 60s; - while (std::chrono::steady_clock::now() < give_up){ - context.wait_for_all_requests(); - const auto after = stream.video().snapshot(); - const bool box = after && dialog.detect(*after.frame); - if (box || !after || !overworld.detect(*after.frame)){ - calm_since = std::chrono::steady_clock::now(); - }else if (std::chrono::steady_clock::now() - calm_since >= 5s){ - break; - } - if (box){ - pbf_press_button(context, BUTTON_B, 80ms, 1100ms); - }else{ - pbf_wait(context, 300ms); - } - } + settle_after_battle(stream, context); if (!in_pokemon_center(stream)){ use_potion_first_pokemon(stream, context, 0.8); } From b7b74431cee1e1a36982d2e37dc08f5561ce1c33 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 15:27:44 -0800 Subject: [PATCH 059/166] BDSP AutoStory: running out of Potions ends the doses, not the run After Roark the Bag's only Potion went on the first dose and the second found the Medicine pocket empty; that failed the checkpoint with the badge won (lab-B, 2026-11-08 15:26). No Potion left now logs and goes on; the next Center heals. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Actions/PokemonBDSP_AutoStory_Bag.cpp | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Bag.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Bag.cpp index 0cf1365c69..6230464190 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Bag.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Bag.cpp @@ -203,7 +203,7 @@ void bag_back_to_overworld(VideoStream& stream, ProControllerContext& context, c } } -enum class Dose{ HEALED, GIVEN }; +enum class Dose{ HEALED, GIVEN, NONE_LEFT }; // One Potion on the lead, from the overworld, its HP read before and after // in the Bag. HEALED when no dose is needed (HP full, or above @@ -212,14 +212,11 @@ enum class Dose{ HEALED, GIVEN }; Dose potion_dose(VideoStream& stream, ProControllerContext& context, size_t dose, double heal_below){ stream.log("[Potion] Finding Bag/Medicine/Potion; dose " + std::to_string(dose + 1) + "/3."); if (!find_bag_item_by_name(stream, context, "potion", 1, 5)){ - if (dose == 0 && heal_below < 1.0){ - // Only a check: without Potions there is nothing to do here. - stream.log("[Potion] No Potion in the Bag; skipping the HP check.", COLOR_ORANGE); - return Dose::HEALED; - } - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - "Potion: Could not verify Potion in the Medicine pocket.", - stream); + // No Potion left is not a failure: the next Center heals. After Roark + // the one Potion went on the first dose and the second found the + // Medicine pocket empty (lab-B, 2026-11-08 15:26). + stream.log("[Potion] No Potion left in the Bag after " + std::to_string(dose) + " dose(s); going on.", COLOR_ORANGE); + return Dose::NONE_LEFT; } const double before = confirmed_potion_hp(stream, context); stream.log("[Potion] Slot 1 HP bar before use=" + std::to_string(before * 100) + "%."); @@ -405,7 +402,12 @@ void use_potion_first_pokemon(VideoStream& stream, ProControllerContext& context OverlayBoxScope hp_overlay(stream.overlay(), COLOR_GREEN, {0.137, 0.160, 0.202, 0.016}, ""); bool healed = false; for (size_t dose = 0; dose < 3 && !healed; dose++){ - healed = potion_dose(stream, context, dose, heal_below) == Dose::HEALED; + const Dose result = potion_dose(stream, context, dose, heal_below); + if (result == Dose::NONE_LEFT){ + bag_back_to_overworld(stream, context, "Potion: No overworld after finding no Potion."); + return; + } + healed = result == Dose::HEALED; if (!healed){ pbf_mash_button(context, BUTTON_B, 2000ms); context.wait_for_all_requests(); From 02efdf91e5f4d4dbf742a7e75021edf538351872 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 15:42:29 -0800 Subject: [PATCH 060/166] BDSP AutoStory: log banner reads while waiting for a map's banner The Oreburgh Gate entry missed its banner twice on the console though a hand probe saw it 1.5 s after the fade; the wait now logs each distinct read and, on giving up, the darkest frame and the last read. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index 1b3e30e48d..da952f731b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -212,18 +212,34 @@ enum class TapLook{ // Looks for the location banner `banner` (and, if `dark_too`, the fade) // for up to `wait`. +// Logs each distinct banner read and how the wait ended: the Oreburgh Gate's +// entry missed its banner twice (lab-B, 2026-11-08 15:31 and 15:39) though +// a hand probe saw it 1.5 s after the fade, and nothing said why. TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const std::string& banner, Milliseconds wait, bool dark_too){ - const WallClock deadline = current_time() + wait; + const WallClock start = current_time(); + const WallClock deadline = start + wait; + std::string last_read; + double darkest = 255; while (true){ context.wait_for_all_requests(); const VideoSnapshot screen = stream.video().snapshot(); - if (screen && location_banner_matches(read_location_banner(*screen.frame), banner)){ + const std::string read = screen ? read_location_banner(*screen.frame) : ""; + if (!read.empty() && read != last_read){ + stream.log(std::format("[Banner] read \"{}\" after {} ms, looking for \"{}\".", + read, std::chrono::duration_cast(current_time() - start).count(), banner)); + last_read = read; + } + if (screen && location_banner_matches(read, banner)){ return TapLook::BANNER; } - if (dark_too && screen && image_average(*screen.frame).sum() / 3 < FADE_DARKNESS){ + const double brightness = screen ? image_average(*screen.frame).sum() / 3 : 255; + darkest = std::min(darkest, brightness); + if (dark_too && brightness < FADE_DARKNESS){ return TapLook::DARK; } if (current_time() >= deadline){ + stream.log(std::format("[Banner] no \"{}\" in {} ms; darkest frame {:.0f}, last read \"{}\".", + banner, wait.count(), darkest, last_read)); return TapLook::NOTHING; } context.wait_for(100ms); From 81c993afff543b18fd748b206e93dd7a19cf87cd Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 15:49:10 -0800 Subject: [PATCH 061/166] BDSP AutoStory: keep a frame every 500 ms while waiting for a banner The Oreburgh Gate's entry read no banner twice; whether the game showed none or the check missed it needs the frames. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index da952f731b..4e2ba91a15 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -6,7 +6,10 @@ #include #include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Filesystem/Filesystem.h" #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/GlobalAutoPaths.h" #include "CommonFramework/ImageTools/ImageStats.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" #include "CommonTools/Async/InferenceRoutines.h" @@ -220,9 +223,18 @@ TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const const WallClock deadline = start + wait; std::string last_read; double darkest = 255; + // Every 500 ms of a long wait (the one after a fade) a frame goes to + // Screenshots/AutoStory/banner/, to see what the game showed. + const std::string folder = SCREENSHOTS_PATH() + "AutoStory/banner/"; + WallClock next_frame = start; while (true){ context.wait_for_all_requests(); const VideoSnapshot screen = stream.video().snapshot(); + if (!dark_too && screen && current_time() >= next_frame){ + Filesystem::create_directories(Filesystem::Path(folder)); + screen.frame->save(folder + now_to_filestring() + "-" + normalize_location_name(banner) + ".png"); + next_frame += 500ms; + } const std::string read = screen ? read_location_banner(*screen.frame) : ""; if (!read.empty() && read != last_read){ stream.log(std::format("[Banner] read \"{}\" after {} ms, looking for \"{}\".", From e3c811efacd5a892a4e156f3341c4d3281ae7c52 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 15:49:43 -0800 Subject: [PATCH 062/166] BDSP AutoStory: banner-wait frame and log helpers Keeps look_after_tap() under the code-health length limit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index 4e2ba91a15..299796c325 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -215,6 +215,19 @@ enum class TapLook{ // Looks for the location banner `banner` (and, if `dark_too`, the fade) // for up to `wait`. +void keep_banner_frame(const ImageViewRGB32& frame, const std::string& folder, const std::string& banner){ + Filesystem::create_directories(Filesystem::Path(folder)); + frame.save(folder + now_to_filestring() + "-" + normalize_location_name(banner) + ".png"); +} +void log_new_banner_read(VideoStream& stream, const std::string& read, std::string& last_read, const std::string& banner, WallClock start){ + if (read.empty() || read == last_read){ + return; + } + stream.log(std::format("[Banner] read \"{}\" after {} ms, looking for \"{}\".", + read, std::chrono::duration_cast(current_time() - start).count(), banner)); + last_read = read; +} + // Logs each distinct banner read and how the wait ended: the Oreburgh Gate's // entry missed its banner twice (lab-B, 2026-11-08 15:31 and 15:39) though // a hand probe saw it 1.5 s after the fade, and nothing said why. @@ -231,16 +244,11 @@ TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const context.wait_for_all_requests(); const VideoSnapshot screen = stream.video().snapshot(); if (!dark_too && screen && current_time() >= next_frame){ - Filesystem::create_directories(Filesystem::Path(folder)); - screen.frame->save(folder + now_to_filestring() + "-" + normalize_location_name(banner) + ".png"); + keep_banner_frame(*screen.frame, folder, banner); next_frame += 500ms; } const std::string read = screen ? read_location_banner(*screen.frame) : ""; - if (!read.empty() && read != last_read){ - stream.log(std::format("[Banner] read \"{}\" after {} ms, looking for \"{}\".", - read, std::chrono::duration_cast(current_time() - start).count(), banner)); - last_read = read; - } + log_new_banner_read(stream, read, last_read, banner, start); if (screen && location_banner_matches(read, banner)){ return TapLook::BANNER; } From 95b2960c55b7ef939c530a1f1f68128de07593b6 Mon Sep 17 00:00:00 2001 From: dayfine Date: Sun, 8 Nov 2026 15:58:54 -0800 Subject: [PATCH 063/166] BDSP AutoStory 01.05: run into the Oreburgh Gate from Barry's spot The open walk to the tile beside the Gate's mouth slid onto the warp, the banner came and went unwatched, and the tap step took the Gate's dim floor for its fade and waited for a banner already gone (lab-B, 2026-11-08, four runs; frames kept). One door run west until the fade replaces the walk and the tap. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 006a03ddb0..a6e5a30c63 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -628,9 +628,15 @@ StoryCheckpoint oreburgh_to_route_203(){ "west along the street, north up the stairs west of the houses, west along the Gate's row", "town"), step_into("barrys_trigger", WEST, "the trigger (6, 12..15)"), scene("barry_bumps_into_us", at(OREBURGH, 5, 13, EAST), "Barry runs into us, talks of Eterna, and leaves (assumed: the push)"), - route("by_the_gate", next_to(OREBURGH, "gate_mouth", EAST, WEST), "west to the Gate's warp tile (2, 13)"), - // The warp's other end is the Gate's (27, 22), beside its east mouth. - tap_into("into_oreburgh_gate", WEST, "the Gate's mouth (1, 13)", arrival(GATE, {27, 22}, WEST)), + // Straight west from where Barry leaves us into the Gate's mouth + // (1, 13), running until the fade; the warp's other end is the + // Gate's (27, 22), beside its east mouth. Not an open walk to the + // tile beside the mouth and then a tap: that walk slid onto the warp + // (screen change 177 at 1.6 s), the banner came and went unwatched, + // and the tap step took the Gate's dim floor for its fade and waited + // for a banner already gone (lab-B, 2026-11-08 15:31, 15:39, 15:47, + // 15:54; frames in Screenshots/AutoStory/banner/). + step_into("into_oreburgh_gate", WEST, "the Gate's mouth (1, 13)", arrival(GATE, {27, 22}, WEST)), route("through_the_gate", at(GATE, 4, 22, WEST), "west along row 22 to the warp tile by the west mouth (3, 22)"), // Route 203's banner or a failure here: the old walk west "until the // banner" went on into the pond's pocket (r75). 01.06 heads south. From 013c4bd561fe2078934505f60b0d3f9c12daafc1 Mon Sep 17 00:00:00 2001 From: Di Fan <26423504+dayfine@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:50:53 -0800 Subject: [PATCH 064/166] BDSP AutoStory: routes stop short of warps; a dim cave floor is not a tap's fade (#269) * BDSP AutoStory: no route ends beside a warp walking toward it 01.05's open walk west to (2, 13), beside the Oreburgh Gate's mouth, slid onto the warp (lab-B 2026-11-08, four runs). A table test plans every ROUTE step as the walker does and fails on an open leg that may end on the tile before a door it walks toward. It flagged 01.05's old by_the_gate and four more: 00.03 above_the_door_again (now counted legs from the west), 01.02 by_the_east_mouth and 01.05 through_the_gate (two tiles short of the Gate's mouths, the taps go the rest), and 01.03 above_the_mine (two rows above the warp row, the door run goes on). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: the story sim's old steps in their own file Moved unchanged out of StorySim_Tests.cpp, which is at the 1000-line limit: r75's and r81's old cave exits and the old mine steps. The next commit adds 01.05's old tap into the Oreburgh Gate beside them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: a dim cave floor is not a tap step's fade On lab-B (2026-11-08 15:31 to 15:54) 01.05's walk slid into the Oreburgh Gate, and its tap step read the Gate's floor (about 46) as the fade and waited 8 s for a banner already gone. A look after a tap is the fade only when black (< 25) or a drop to dark from the look before the tap (tap_faded()). A banner before the first tap means the walk before took us through: the step ends with no tap. A tap step taps at most two past the door its map has ahead, so one begun through the warp with its banner gone fails a few tiles in, not across the Gate. Tests: tap_faded() on the Gate's floor and real fades; the story sim's 01.05 tap step begun through the Gate's mouth, banner up and gone (red before: 24 taps across the Gate); GridSim's part-tile offset taking the warp on the old open walk west. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: mark the tap step's fade and through-already checks as stopgaps Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --------- Co-authored-by: Claude Opus 5.5 --- .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 48 ++++++-- .../PokemonBDSP_AutoStory_StoryStepIO.h | 9 +- .../PokemonBDSP_AutoStory_StoryTable.cpp | 11 +- ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 81 +++++++++++++ .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 48 +++++++- .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 2 +- .../PokemonBDSP_AutoStory_Walk_Tests.cpp | 33 ++++++ .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 28 +++++ .../PokemonBDSP_AutoStory_OldStorySteps.cpp | 90 +++++++++++++++ .../PokemonBDSP_AutoStory_OldStorySteps.h | 54 +++++++++ .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 107 +++++++----------- SerialPrograms/cmake/SourceFiles.cmake | 2 + 12 files changed, 427 insertions(+), 86 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index 299796c325..43df0cf73f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -213,8 +213,11 @@ enum class TapLook{ BANNER, }; -// Looks for the location banner `banner` (and, if `dark_too`, the fade) -// for up to `wait`. +// The mean of r, g and b over the screen, 0 to 255; 255 with no frame. +double brightness_of(const VideoSnapshot& screen){ + return screen ? image_average(*screen.frame).sum() / 3 : 255; +} + void keep_banner_frame(const ImageViewRGB32& frame, const std::string& folder, const std::string& banner){ Filesystem::create_directories(Filesystem::Path(folder)); frame.save(folder + now_to_filestring() + "-" + normalize_location_name(banner) + ".png"); @@ -228,10 +231,12 @@ void log_new_banner_read(VideoStream& stream, const std::string& read, std::stri last_read = read; } +// Looks for the location banner `banner` for up to `wait`, and with +// `before` (the brightness before the tap) for the fade (tap_faded()). // Logs each distinct banner read and how the wait ended: the Oreburgh Gate's // entry missed its banner twice (lab-B, 2026-11-08 15:31 and 15:39) though // a hand probe saw it 1.5 s after the fade, and nothing said why. -TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const std::string& banner, Milliseconds wait, bool dark_too){ +TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const std::string& banner, Milliseconds wait, std::optional before){ const WallClock start = current_time(); const WallClock deadline = start + wait; std::string last_read; @@ -243,7 +248,7 @@ TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const while (true){ context.wait_for_all_requests(); const VideoSnapshot screen = stream.video().snapshot(); - if (!dark_too && screen && current_time() >= next_frame){ + if (!before && screen && current_time() >= next_frame){ keep_banner_frame(*screen.frame, folder, banner); next_frame += 500ms; } @@ -252,9 +257,9 @@ TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const if (screen && location_banner_matches(read, banner)){ return TapLook::BANNER; } - const double brightness = screen ? image_average(*screen.frame).sum() / 3 : 255; + const double brightness = brightness_of(screen); darkest = std::min(darkest, brightness); - if (dark_too && brightness < FADE_DARKNESS){ + if (before && tap_faded(*before, brightness)){ return TapLook::DARK; } if (current_time() >= deadline){ @@ -269,6 +274,19 @@ TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const } // namespace +// Black as the Gym's door fades (< 25), or a drop to dark: a look under +// FADE_DARKNESS is not a fade by itself, since a cave's floor is that dim +// (the Oreburgh Gate's about 46, lab-B 2026-11-08), but a fade into a cave +// from a lit street goes from about 120 to 45..64. +// TODO(#268 slice 3): stopgap. A uniform-screen fade watcher (the shared +// Black/WhiteScreen stddev test, as in upstream #1717) should replace this +// brightness drop; remove it once that watcher passes the Gate frames. +constexpr double TAP_FADE_BLACK = 25; +constexpr double TAP_FADE_DROP = 0.7; +bool tap_faded(double before, double after){ + return after < TAP_FADE_BLACK || (after < FADE_DARKNESS && after < before * TAP_FADE_DROP); +} + ConsoleStoryStepIO::ConsoleStoryStepIO(VideoStream& stream, ProControllerContext& context) : m_stream(stream) , m_context(context) @@ -305,15 +323,26 @@ bool ConsoleStoryStepIO::run_into_door(Direction direction, bool run, Millisecon // A held walk can carry on past a fade that goes unseen: out of the Gym it // walked on south (r219g), and through the Oreburgh Gate's west mouth on // west into a pocket by Route 203's pond (r75). Taps during the fade are -// eaten. +// eaten. The banner before the first tap means we are through already: +// the walk before slid onto the warp (lab-B 2026-11-08 15:31). +// TODO(#268 slice 2): stopgap. The "through already" check sees only a +// banner still on screen; once walkers report the fade or banner they saw +// (WalkResult::warp), read that instead and remove this check. std::optional ConsoleStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ const std::string& banner = story_banner_name(map); + m_context.wait_for_all_requests(); + VideoSnapshot screen = m_stream.video().snapshot(); + if (screen && location_banner_matches(read_location_banner(*screen.frame), banner)){ + m_stream.log("[Banner] \"" + banner + "\" shows before the first tap: through already."); + return 0; + } for (size_t tap = 1; tap <= max_taps; tap++){ + const double before = brightness_of(screen); pbf_press_dpad(m_context, dpad_toward(direction), 160ms, 0ms); - TapLook look = look_after_tap(m_stream, m_context, banner, 1500ms, true); + TapLook look = look_after_tap(m_stream, m_context, banner, 1500ms, before); const bool faded = look == TapLook::DARK; if (faded){ - look = look_after_tap(m_stream, m_context, banner, 8000ms, false); + look = look_after_tap(m_stream, m_context, banner, 8000ms, std::nullopt); } if (look == TapLook::BANNER){ m_context.wait_for(1000ms); @@ -322,6 +351,7 @@ std::optional ConsoleStoryStepIO::tap_to_banner(Direction direction, con if (faded){ break; } + screen = m_stream.video().snapshot(); } return std::nullopt; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h index 52470d8fcd..a48007ee2f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h @@ -51,7 +51,8 @@ class StoryStepIO{ // D-pad taps `direction` one at a time, each looked at, toward a door // or cave mouth, until the fade (then no more taps) and the location // banner of `map` (a JSON map's name), for at most `max_taps`. Returns - // the taps it took, or nothing if no banner showed. + // the taps it took (0 if the banner shows before the first: through + // already), or nothing if no banner showed. virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) = 0; // Presses through any text until the overworld is quiet; with `fade`, a // fade must come first (a map change). Fails otherwise. @@ -59,6 +60,12 @@ class StoryStepIO{ }; +// Whether a look after a tap toward a door or a cave mouth shows its fade, +// from its brightness `after` and that of the look before the tap, +// `before` (the mean of r, g and b, 0 to 255). +bool tap_faded(double before, double after); + + // The console. class ConsoleStoryStepIO : public StoryStepIO{ public: diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index a6e5a30c63..2f7cb7123d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -124,6 +124,8 @@ StoryStep make(StoryStepKind kind, std::string name, std::string why){ step.why = std::move(why); return step; } +// A route toward a door or a warp stops two tiles short, not beside it: an +// open walk there can slide onto it (01.05, lab-B 2026-11-08). StoryStep route(std::string name, Pose target, std::string why, std::string costs = ""){ StoryStep step = make(StoryStepKind::ROUTE, std::move(name), std::move(why)); step.target = std::move(target); @@ -337,7 +339,8 @@ std::vector lake_and_pokedex(){ // Line up on the table's corner west first: a plan from either tile // ran east into Mom at (7, 8), who talks (r29). route("by_the_counter", at(HOME, 4, 8, WEST), "west against the table's corner (3, 8)"), - route("above_the_door_again", at(HOME, 6, 9, SOUTH), "to above the door"), + anchored(legs("above_the_door_again", {{.direction = EAST, .tiles = 1}, {.direction = SOUTH, .tiles = 1}, {.direction = EAST, .tiles = 1}}, + "east, south past the wall (4, 9), and east to above the door: not south toward it"), at(HOME, 6, 9, EAST)), step_into("out_of_the_house_again", SOUTH, "onto the door's tile (6, 10), and out", at(TWINLEAF, "house_doorstep", SOUTH)), // Through the grass now, with a starter: wild battles are run from. route("short_of_dawn", at(ROUTE_201, 63, 5, EAST), "Twinleaf, then east along Route 201 to its east edge"), @@ -637,7 +640,7 @@ StoryCheckpoint oreburgh_to_route_203(){ // for a banner already gone (lab-B, 2026-11-08 15:31, 15:39, 15:47, // 15:54; frames in Screenshots/AutoStory/banner/). step_into("into_oreburgh_gate", WEST, "the Gate's mouth (1, 13)", arrival(GATE, {27, 22}, WEST)), - route("through_the_gate", at(GATE, 4, 22, WEST), "west along row 22 to the warp tile by the west mouth (3, 22)"), + route("through_the_gate", at(GATE, 5, 22, WEST), "west along row 22 to two tiles short of the west mouth's warp (3, 22)"), // Route 203's banner or a failure here: the old walk west "until the // banner" went on into the pond's pocket (r75). 01.06 heads south. tap_into("out_of_oreburgh_gate", WEST, "the west mouth (3, 22)", out_of_oreburgh_gate()), @@ -674,7 +677,7 @@ StoryCheckpoint route_203_to_oreburgh(){ // can come up a moment after them; the scene's B closes it. scene("the_hiker", at(GATE, 7, 22, EAST), "HM Rock Smash, then the Hidden Moves card"), route("past_curtis", at(GATE, 20, 22, EAST), "east along row 22 past Camper Curtis's column (17), fighting him"), - route("by_the_east_mouth", at(GATE, 27, 22, EAST), "east past Picnicker Diana's column (24), fighting her"), + route("by_the_east_mouth", at(GATE, 26, 22, EAST), "east past Picnicker Diana's column (24), fighting her, to two short of the mouth"), tap_into("into_oreburgh", EAST, "the Gate's east mouth (28, 22)", arrival(OREBURGH, map_point(OREBURGH, "gate_mouth").next(EAST), EAST)), route("west_of_the_welcome", at(OREBURGH, 9, 13, EAST), "east along row 13"), @@ -766,7 +769,7 @@ StoryCheckpoint oreburgh_center_heal(){ StoryCheckpoint oreburgh_mine_to_roark(){ const Pose below_roark = next_to(MINE, "roark", SOUTH, NORTH); return row("01.03", "Oreburgh Mine to Roark", out_of_oreburgh_center(), { - route("above_the_mine", at(OREBURGH, 46, 58, SOUTH), "down the door's column to above the mine's warp tiles", "town"), + route("above_the_mine", at(OREBURGH, 46, 57, SOUTH), "down the door's column to two above the mine's warp tiles (44..48, 59)", "town"), step_into("into_the_mine", SOUTH, "the warp tile (46, 59)", at(MINE_HALL, 12, 1, SOUTH)), step_into("into_the_coal_room", SOUTH, "down the entrance hall through the cave mouth", at(MINE, 15, 2, SOUTH)), anchored(to_walls("south_to_the_rock", {{.direction = SOUTH, .tiles = 8}}, "south against the corridor rock (15, 11)"), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index c16b365d7f..a6797a9190 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -19,7 +19,10 @@ #include "Data/PokemonBDSP_AutoStory_PlanCosts.h" #include "Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "Data/PokemonBDSP_AutoStory_StoryMaps.h" +#include "Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "Actions/PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_StoryTable_Tests.h" @@ -218,6 +221,80 @@ UnitTestResult test_route204_north_line(Logger& logger){ return true; } +// The legs a ROUTE step from `from` plans, as walk_route() plans them (the +// step's costs, then the default ones), on `world`; nothing if none. +std::optional> route_step_plan(const StoryWorld& world, const Pokemon::Pose& from, const Pokemon::StoryStep& step){ + std::vector start; + for (const TilePos& pos : Pokemon::tiles_of(from)){ + start.push_back(story_to_world(world, from.map, pos)); + } + std::vector targets; + for (const TilePos& pos : Pokemon::tiles_of(*step.target)){ + targets.push_back(story_to_world(world, step.target->map, pos)); + } + const auto goal = [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }; + std::optional> legs = plan_recovered_route(world, start, goal, *story_route_costs(step.variant)); + return legs ? legs : plan_recovered_route(world, start, goal, RobustPlanCosts()); +} + +// Why `planned` may slide into a door or a warp, or "": an open leg (not to +// a wall) that may end on the tile before one, walking toward it. A part of +// a tile too far takes the warp (lab-B 2026-11-08 15:31 to 15:54: 01.05's +// open walk west to (2, 13), beside the Oreburgh Gate's mouth, slid into +// the Gate, and the tap after it waited for a banner already gone). The +// maps draw every warp as a door tile, cave mouths too. +std::string slides_into_door(const StoryWorld& world, const PlannedLeg& planned){ + if (planned.leg.ends_at_wall){ + return ""; + } + for (const TilePos& pos : planned.after){ + const TilePos ahead = pos.next(planned.leg.direction); + if (world.tile(ahead) == Pokemon::TileKind::DOOR){ + return std::format("the open leg {} may end on {}, the tile before the door {}", + to_string(planned.leg), describe(world, pos), describe(world, ahead)); + } + } + return ""; +} + +// No ROUTE step of the table plans an open leg that ends before a door it +// walks toward: a door is gone through by a step that runs or taps into it +// from where the route ends on a wall or off its line. Where a row's steps +// leave the player is followed from its start through each step's target +// or pose_after; a route from an unknown place is not checked. +UnitTestResult test_story_routes_stop_short_of_doors(Logger& logger){ + std::vector found; + size_t checked = 0; + for (const StoryCheckpoint& row : story_checkpoints()){ + std::optional at = row.start; + for (const Pokemon::StoryStep& step : row.steps){ + const bool known = at && !Pokemon::tiles_of(*at).empty(); + const StoryWorld* world = step.kind == StoryStepKind::ROUTE && known + ? story_plan_world(at->map, step.target->map) : nullptr; + if (step.kind == StoryStepKind::ROUTE && world == nullptr){ + logger.log(std::format("{} {}: not checked, from {}.", row.id, step.name, at ? Pokemon::to_string(*at) : "nowhere known")); + } + const std::optional> legs = world ? route_step_plan(*world, *at, step) : std::nullopt; + checked += legs ? 1 : 0; + for (const PlannedLeg& planned : legs ? *legs : std::vector{}){ + const std::string why = slides_into_door(*world, planned); + if (!why.empty()){ + found.push_back(std::format("{} {}: {}.", row.id, step.name, why)); + } + } + at = step.kind == StoryStepKind::ROUTE ? step.target + : step.pose_after ? step.pose_after + : step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP ? std::nullopt : at; + } + } + logger.log(std::format("{} routes planned.", checked)); + std::string out; + for (const std::string& line : found){ + out += "\n " + line; + } + return found.empty() ? UnitTestResult(true) : UnitTestResult("Open legs that end before a door they walk toward:" + out); +} + struct AutoStoryStoryTableInput{ std::string name; @@ -270,6 +347,10 @@ const AutoStoryStoryTableCase AUTO_STORY_STORY_TABLE_CASES[] = { .input = {"Route 204 North: the line into Floaroma", test_route204_north_line}, .expectation = {}, }, + { + .input = {"Story table: no open leg ends before a door it walks toward (lab-B, 2026-11-08)", test_story_routes_stop_short_of_doors}, + .expectation = {}, + }, }; void add_tests_AutoStory_StoryTable(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index 514efc1725..8a0d50e0b9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -158,16 +158,52 @@ Outcome StoryWalkSteps::leg_to_map(const StoryStep& step){ return arrived ? Pokemon::outcome_ok() : Pokemon::outcome_failed("no_banner", map); } +namespace{ +// Taps toward a door with no table door ahead of it. +constexpr size_t TAPS_TO_BANNER = 30; +// How many taps `direction` a tap step from `from` takes at most: the +// tiles to the door its map has ahead of every tile of `from`, and two +// more; TAPS_TO_BANNER where the map has none. A step through already, +// its banner gone, then stops a few tiles on (lab-B 2026-11-08: 01.05's +// walk slid into the Oreburgh Gate, whose row 22 runs 24 tiles on). +size_t taps_to_banner(const Pose& from, Direction direction){ + size_t most = 0; + try{ + const Pokemon::MapData& map = story_map(from.map); + for (const TilePos& pos : Pokemon::tiles_of(from)){ + const size_t tiles = Pokemon::tiles_to_door(map, pos, direction); + TilePos door = pos; + for (size_t i = 0; i < tiles; i++){ + door = door.next(direction); + } + if (tiles == 0 || map.tiles.at(door) != Pokemon::TileKind::DOOR){ + return TAPS_TO_BANNER; + } + most = std::max(most, tiles); + } + }catch (...){ + return TAPS_TO_BANNER; + } + return most == 0 ? TAPS_TO_BANNER : most + 2; +} +} // namespace + // A STEP "to_banner": D-pad taps toward a door or cave mouth until the fade // and pose_after's map's location banner. No banner fails the step right -// there. -Outcome StoryWalkSteps::tap_to_banner(const StoryStep& step){ +// there; a banner before any tap means the walk before took us through. +Outcome StoryWalkSteps::tap_to_banner(const Pose& from, const StoryStep& step){ const std::string map = step.pose_after ? step.pose_after->map : ""; - const std::optional taps = m_io.tap_to_banner(step.direction, map, 30); + const size_t limit = taps_to_banner(from, step.direction); + const std::optional taps = m_io.tap_to_banner(step.direction, map, limit); if (!taps){ - return Pokemon::outcome_failed("no_banner", map); + return Pokemon::outcome_failed("no_banner", std::format("{} in {} taps {}: through already, its banner gone?", + map, limit, direction_name(step.direction))); + } + if (*taps == 0){ + log(std::format("[{}] {}: {}'s banner before any tap: through already.", m_row, step.name, map)); + }else{ + log(std::format("[{}] {}: {}'s banner after {} taps {}.", m_row, step.name, map, *taps, direction_name(step.direction))); } - log(std::format("[{}] {}: {}'s banner after {} taps {}.", m_row, step.name, map, *taps, direction_name(step.direction))); return Pokemon::outcome_ok(); } @@ -340,7 +376,7 @@ Outcome StoryWalkSteps::legs(RunState& state, const StoryStep& step){ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ if (step.variant == "to_banner"){ turn(step.direction); - return tap_to_banner(step); + return tap_to_banner(state.pose, step); } if (step.variant == "tap"){ // No separate turn tap first: at 1 tile from the door, a turn tap diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index a25435dd55..a7c4aad024 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -75,7 +75,7 @@ class StoryWalkSteps{ Pokemon::Outcome counted_wall(const Pokemon::Pose& from, const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_dialogue(const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_map(const Pokemon::StoryStep& step); - Pokemon::Outcome tap_to_banner(const Pokemon::StoryStep& step); + Pokemon::Outcome tap_to_banner(const Pokemon::Pose& from, const Pokemon::StoryStep& step); void turn(Pokemon::Direction direction); void log(const std::string& text); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp index 252f0ef541..4bacc207a3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp @@ -15,6 +15,7 @@ #include "Utils/PokemonBDSP_AutoStory_Location.h" #include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "Actions/PokemonBDSP_AutoStory_Talks.h" +#include "PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP_AutoStory_Walk_Tests.h" namespace PokemonAutomation{ @@ -120,6 +121,34 @@ UnitTestResult test_door_fade(Logger&){ return true; } +// A tap step's fade is a real one: black, or a drop to dark from the look +// before the tap. The Oreburgh Gate's floor, about 46 before and after a +// tap inside it, is no fade: read as one, the tap into the Gate from +// Oreburgh, already through, waited 8 s for a banner gone (lab-B, +// 2026-11-08 15:31 to 15:54). +UnitTestResult test_tap_fade(Logger&){ + struct Case{ + std::string name; + double before; + double after; + bool faded; + }; + const std::vector cases{ + {.name = "inside the Gate, its floor", .before = 46, .after = 46, .faded = false}, + {.name = "inside the Gate, a darker patch", .before = 52, .after = 44, .faded = false}, + {.name = "on a street", .before = 120, .after = 112, .faded = false}, + {.name = "the street into the Gate's mouth, to black", .before = 120, .after = 8, .faded = true}, + {.name = "the street into a cave, a dim fade (45 to 64 measured)", .before = 120, .after = 60, .faded = true}, + {.name = "out of the Gate, from its floor to black", .before = 46, .after = 12, .faded = true}, + }; + for (const Case& item : cases){ + if (tap_faded(item.before, item.after) != item.faded){ + return item.name + (item.faded ? ": no fade read." : ": read as a fade."); + } + } + return true; +} + UnitTestResult test_location_banner(Logger&){ struct Case{ @@ -285,6 +314,10 @@ const AutoStoryWalkCase AUTO_STORY_WALK_CASES[] = { .input = {"out of a door needs its fade", test_door_fade}, .expectation = {}, }, + { + .input = {"a tap into a door fades to black or drops to dark, not a dim floor (lab-B, 2026-11-08)", test_tap_fade}, + .expectation = {}, + }, { .input = {"location banner match", test_location_banner}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 190f7409da..11ccb344d4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -562,6 +562,30 @@ UnitTestResult test_roarks_room_from_a_row_off(Logger& logger){ return true; } +// lab-B 2026-11-08 15:31 to 15:54: 01.05's open walk west 3 from (5, 13), +// where Barry's push leaves us, to (2, 13) beside the Oreburgh Gate's mouth +// (1, 13) went on into the Gate. D-pad taps move whole tiles but keep a +// part-tile offset: 0.375 of a tile west of (5, 13), the three taps take +// the warp; on the tile, they stop beside it. +UnitTestResult test_gate_walk_part_tile_off(Logger&){ + const StoryWorld& world = *story_plan_world("OreburghCity", "OreburghCity"); + for (const bool off : {false, true}){ + GridSim sim({.world = &world}, story_to_world(world, "OreburghCity", {5, 13}), Direction::WEST, true); + if (off){ + sim.tap(Direction::WEST, 60ms, true); + } + SimStop stop = SimStop::DONE; + for (int tap = 0; tap < 3 && stop == SimStop::DONE; tap++){ + stop = sim.tap(Direction::WEST, 160ms, false).stop; + } + if ((stop == SimStop::WARP) != off){ + return std::format("{} (5, 13): three taps west ended {} at {}.", off ? "0.375 west of" : "on", + sim_stop_name(stop), to_string(sim.player().pos)); + } + } + return true; +} + UnitTestResult test_wandering_npc_mechanics(Logger& logger){ StoryWorld world = make_world({ "#######", @@ -909,6 +933,10 @@ const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { .input = {"01.03, Oreburgh Mine B1F entrance hall corridor runs to and back", test_oreburgh_mine_hall_corridor}, .expectation = {}, }, + { + .input = {"01.05, a part of a tile off, the old open walk west takes the Gate's warp (lab-B, 2026-11-08)", test_gate_walk_part_tile_off}, + .expectation = {}, + }, }; void add_tests_AutoStory_GridSim(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp new file mode 100644 index 0000000000..657513f382 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp @@ -0,0 +1,90 @@ +/* BDSP AutoStory - Old story steps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP_AutoStory_OldStorySteps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::Direction; +using Pokemon::Pose; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + + +StoryStep r75_old_gate_exit(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "out_of_oreburgh_gate"; + step.legs = {{.direction = Direction::WEST, .tiles = 8}}; + step.variant = "to_map"; + step.pose_after = Pokemon::tile_pose("Route203", {TilePos{55, 9}}, Direction::WEST); + return step; +} +Pose r75_pond_pocket(){ + std::vector tiles; + for (int y = 6; y <= 13; y++){ + for (int x = 49; x <= 54; x++){ + tiles.push_back({x, y}); + } + } + return Pokemon::tile_pose("Route203", tiles); +} + +StoryStep r81_old_cave_exit(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "out_of_the_ravaged_path"; + step.legs = {{.direction = Direction::SOUTH, .tiles = 4}}; + step.variant = "to_wall"; + step.pose_after = Pokemon::tile_pose("Route204North", {TilePos{20, 26}}, Direction::SOUTH); + return step; +} +Pose r81_below_the_mouth(){ + return Pokemon::tile_pose("Route204North", {TilePos{20, 27}, TilePos{20, 28}, TilePos{20, 29}, TilePos{20, 30}}); +} + +StoryStep old_mine_hall_19(std::string name, Direction direction){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = std::move(name); + step.legs = {{.direction = direction, .tiles = 19}}; + return step; +} + +StoryStep old_coal_room_crate_cut(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "to_roarks_corner"; + step.legs = { + {.direction = Direction::EAST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 2}, + {.direction = Direction::WEST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 5}, + {.direction = Direction::EAST, .tiles = 14}, {.direction = Direction::SOUTH, .tiles = 10}, + {.direction = Direction::SOUTH, .tiles = 2}, {.direction = Direction::WEST, .tiles = 11}, + }; + return step; +} + +StoryStep old_tap_into_the_gate(){ + StoryStep step; + step.kind = StoryStepKind::STEP; + step.name = "into_oreburgh_gate"; + step.direction = Direction::WEST; + step.variant = "to_banner"; + step.pose_after = Pokemon::tile_pose("OreburghGate", {TilePos{27, 22}, TilePos{26, 22}}, Direction::WEST); + return step; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h new file mode 100644 index 0000000000..580eb84f32 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h @@ -0,0 +1,54 @@ +/* BDSP AutoStory - Old story steps + * + * From: https://github.com/PokemonAutomation/ + * + * Steps the story table had that went wrong on the console, as they were: + * the story simulation's regression tests run them in place of the + * table's step of the same name and check they still go wrong there. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OldStorySteps_H +#define PokemonAutomation_PokemonBDSP_AutoStory_OldStorySteps_H + +#include +#include "Pokemon/AutoStory/Pokemon_StorySteps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// r75: out of the Oreburgh Gate as a run west until Route 203's banner +// (the old event west_until_transition()). The banner reads a few tiles +// in: the run ends west of the Gate's warp tile (55, 9), in the pocket by +// the pond (Route 203's x 49 to 54, rows 6 to 13). +Pokemon::StoryStep r75_old_gate_exit(); +// Where r75's run west ended: the pocket by Route 203's pond. +Pokemon::Pose r75_pond_pocket(); + +// r81: out of the Ravaged Path as a timed walk south (the old event's +// 4 s walk_dir()), its fade missed: on past cave_exit (20, 26) to the +// cliff, column 20 down to row 30. +Pokemon::StoryStep r81_old_cave_exit(); +// Where r81's walk south ended: below the Ravaged Path's mouth. +Pokemon::Pose r81_below_the_mouth(); + +// Oreburgh Mine B1F: tapping 19 tiles leaves the player 1 tile short of the warp door. +Pokemon::StoryStep old_mine_hall_19(std::string name, Pokemon::Direction direction); + +// Oreburgh Mine: stepping south at col 29 without bypassing the crate +// hits the wooden crate at (29, 28) on the south leg, a tile down. +Pokemon::StoryStep old_coal_room_crate_cut(); + +// 01.05's old tap into the Oreburgh Gate, west to its banner, after an +// open walk to the tile beside its mouth (1, 13) that slid onto the warp: +// the tap step began inside the Gate (lab-B 2026-11-08 15:31 to 15:54). +Pokemon::StoryStep old_tap_into_the_gate(); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 85f4792206..5f6a1a86b7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -41,6 +41,7 @@ #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_OldStorySteps.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" @@ -70,13 +71,18 @@ using Pokemon::TilePos; // (run_until_map()) of the run goes unseen, though the player did go // through. The console missed both (r75, r81). The `dark`th door run reads // dark SIM_FALSE_DARK in, short of the door, as lab-B's did on 2026-11-08. -// The counts and flags below are the run's: how many fades and banners it -// looked for, whether a miss happened since the executor last looked, and -// whether a missed fade is still unseen. +// The `through`th tap step (tap_to_banner(), from 0) starts on its far side, +// its banner gone unless `through_banner`: the walk before it slid onto the +// warp (lab-B 2026-11-08). The counts and flags below are the run's: how +// many fades and banners it looked for, whether a miss happened since the +// executor last looked, and whether a missed fade is still unseen. struct SimMisses{ std::optional fade; std::optional banner; std::optional dark = {}; + std::optional through = {}; + bool through_banner = false; + size_t tap_steps = 0; size_t fades = 0; size_t banners = 0; size_t doors = 0; @@ -226,10 +232,17 @@ bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, cons } // D-pad taps, each looked at, until the fade and then the banner (the -// console's ConsoleStoryStepIO::tap_to_banner()). Each look stands still, -// so a banner on the far side reads at once. A fade seen ends the taps, +// console's ConsoleStoryStepIO::tap_to_banner()): none if the banner shows +// before the first. Each look stands still, so a banner on the far side +// reads at once. A fade seen ends the taps, // banner or not; with the fade missed the next look still sees the banner. std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ + if (m_misses.through == m_misses.tap_steps++){ + m_misses.missed = true; + if (m_far_side() && m_misses.through_banner){ + return 0; + } + } bool crossed = false; for (size_t tap = 1; tap <= max_taps; tap++){ const SimMove move = m_sim.tap(direction, 160ms, false); @@ -740,44 +753,6 @@ UnitTestResult run_exit_test(Logger& logger, const std::string& row_id, const St return true; } -// r75: out of the Oreburgh Gate as a run west until Route 203's banner -// (the old event west_until_transition()). The banner reads a few tiles -// in: the run ends west of the Gate's warp tile (55, 9), in the pocket by -// the pond (Route 203's x 49 to 54, rows 6 to 13). -StoryStep r75_old_gate_exit(){ - StoryStep step; - step.kind = StoryStepKind::LEGS; - step.name = "out_of_oreburgh_gate"; - step.legs = {{.direction = Direction::WEST, .tiles = 8}}; - step.variant = "to_map"; - step.pose_after = Pokemon::tile_pose("Route203", {TilePos{55, 9}}, Direction::WEST); - return step; -} -Pose r75_pond_pocket(){ - std::vector tiles; - for (int y = 6; y <= 13; y++){ - for (int x = 49; x <= 54; x++){ - tiles.push_back({x, y}); - } - } - return Pokemon::tile_pose("Route203", tiles); -} -// r81: out of the Ravaged Path as a timed walk south (the old event's -// 4 s walk_dir()), its fade missed: on past cave_exit (20, 26) to the -// cliff, column 20 down to row 30. -StoryStep r81_old_cave_exit(){ - StoryStep step; - step.kind = StoryStepKind::LEGS; - step.name = "out_of_the_ravaged_path"; - step.legs = {{.direction = Direction::SOUTH, .tiles = 4}}; - step.variant = "to_wall"; - step.pose_after = Pokemon::tile_pose("Route204North", {TilePos{20, 26}}, Direction::SOUTH); - return step; -} -Pose r81_below_the_mouth(){ - return Pokemon::tile_pose("Route204North", {TilePos{20, 27}, TilePos{20, 28}, TilePos{20, 29}, TilePos{20, 30}}); -} - UnitTestResult test_coord_events(Logger&){ for (const auto& [map, json] : bdsp_map_json()){ const StoryWorld* world = story_plan_world(map, map); @@ -860,28 +835,24 @@ UnitTestResult test_exit_ravaged_path(Logger& logger){ return run_exit_test(logger, "01.09", r81_old_cave_exit(), SimMisses{.fade = 0, .banner = std::nullopt}, r81_below_the_mouth()); } -// Oreburgh Mine B1F: tapping 19 tiles leaves the player 1 tile short of the warp door. -StoryStep old_mine_hall_19(std::string name, Direction direction){ - StoryStep step; - step.kind = StoryStepKind::LEGS; - step.name = std::move(name); - step.legs = {{.direction = direction, .tiles = 19}}; - return step; -} - -// Oreburgh Mine: stepping south at col 29 without bypassing the crate -// hits the wooden crate at (29, 28) on the south leg, a tile down. -StoryStep old_coal_room_crate_cut(){ - StoryStep step; - step.kind = StoryStepKind::LEGS; - step.name = "to_roarks_corner"; - step.legs = { - {.direction = Direction::EAST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 2}, - {.direction = Direction::WEST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 5}, - {.direction = Direction::EAST, .tiles = 14}, {.direction = Direction::SOUTH, .tiles = 10}, - {.direction = Direction::SOUTH, .tiles = 2}, {.direction = Direction::WEST, .tiles = 11}, - }; - return step; +// lab-B 2026-11-08 15:31 to 15:54: 01.05's walk to the tile beside the +// Oreburgh Gate's mouth slid onto the warp, and the tap step after it began +// inside the Gate. With its banner up, the step ends there with no tap and +// no fade (the clean run's fade into the Gate is not seen); with it gone, +// it fails a few taps on, not across the Gate. +UnitTestResult test_tap_through_already(Logger& logger, bool banner){ + const std::vector rows = table_with("01.05", old_tap_into_the_gate()); + SimExecutor clean(logger); + run_rows_on(clean, logger, {.from = "01.05", .to = "01.05"}, rows); + SimExecutor through(logger, {.fade = {}, .banner = {}, .through = 1, .through_banner = banner}); + run_rows_on(through, logger, {.from = "01.05", .to = "01.05"}, rows); + const SimRun& run = through.result(); + const std::optional at = run.world ? story_to_local(*run.world, "OreburghGate", run.end) : std::nullopt; + const bool passed = banner + ? run.error.empty() && through.misses().fades + 1 == clean.misses().fades + : run.failed_step == "01.05 into_oreburgh_gate" && at && at->y == 22 && at->x >= 21; + return passed ? UnitTestResult(true) : UnitTestResult(std::format("failed in '{}' on {} after {} fades (clean {}): {}", + run.failed_step, end_of(run), through.misses().fades, clean.misses().fades, run.error.empty() ? "no failure" : run.error)); } UnitTestResult test_story_sim_step_failure(Logger& logger, const std::string& row, const StoryStep& old_step, const std::string& expected_failed_step, const std::string& expected_error){ @@ -955,6 +926,12 @@ const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { }}, .expectation = {}}, {.input = {"r75, out of the Oreburgh Gate", test_exit_gate}, .expectation = {}}, {.input = {"r81, out of the Ravaged Path", test_exit_ravaged_path}, .expectation = {}}, + {.input = {"01.05, a tap step begun through the Gate's mouth, its banner up (lab-B, 2026-11-08)", [](Logger& logger){ + return test_tap_through_already(logger, true); + }}, .expectation = {}}, + {.input = {"01.05, a tap step begun through the Gate's mouth, its banner gone (lab-B, 2026-11-08)", [](Logger& logger){ + return test_tap_through_already(logger, false); + }}, .expectation = {}}, { .input = {"01.03, a dark frame 1.8 s down the mine's entrance hall is not its mouth (lab-B, 2026-11-08)", [](Logger& logger){ SimExecutor executor(logger, {.fade = {}, .banner = {}, .dark = 1}); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 579109c51f..ce5d08921a 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1710,6 +1710,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp From 71c3ed1498682ddcc46a334098de998aff48e3eb Mon Sep 17 00:00:00 2001 From: Di Fan <26423504+dayfine@users.noreply.github.com> Date: Sun, 8 Nov 2026 19:46:10 -0800 Subject: [PATCH 065/166] BDSP AutoStory: a wall leg that never moved waits, then plans from its start (#271) On lab-B (2026-11-08 16:50, 01.08 below_the_ravaged_path) the leg "west 2 (to wall)" from Route 204 (13, 2) stopped at once, 0 chunks moved: the youngster who wanders (12, 2) to (14, 2) stood a tile ahead. The wait for the way needed a stop three tiles short of the wall, so he was talked to at once, and the replan from both (12, 2) and (13, 2) found no plan: an uncertain start needs a wall both tiles reach, and no wall is anchored from a tile someone wanders on. A walk to the wall that never moved stopped where it began, so someone stands on the next tile: it now waits for the way on short legs too, and if they stay, the replan starts from the start tile alone with their tile marked. Two Planned route tests replay the run. Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss Co-authored-by: Claude Opus 5.5 --- ...kemonBDSP_AutoStory_PlannedRoute_Tests.cpp | 128 ++++++++++++++++++ .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 27 +++- 2 files changed, 152 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp index ca7f599636..bbd9056ff9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp @@ -17,8 +17,10 @@ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Data/PokemonBDSP_AutoStory_Maps.h" #include "Data/PokemonBDSP_AutoStory_StoryMaps.h" +#include "Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "Utils/PokemonBDSP_AutoStory_RouteIO.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_PlannedRoute_Tests.h" namespace PokemonAutomation{ @@ -352,6 +354,124 @@ UnitTestResult test_open_leg_known_trainer(Logger&){ } +// 01.08's walk below the Ravaged Path (lab-B 2026-11-08 16:50): the leg +// north up Route 204 South ended at (13, 2), and the leg "west 2 (to +// wall)" to (11, 2) stopped at once, 0 chunks moved: the wandering +// youngster (the map's youngster_3, wandering (12, 2) to (14, 2)) stood on +// (12, 2). The world joins Jubilife and Route 204 South, as the step's. +const StoryWorld& ravaged_path_world(){ + static const StoryWorld* const world = story_plan_world("JubilifeCity", "Route204South"); + return *world; +} +TilePos on_route204_south(TilePos local){ + return story_to_world(ravaged_path_world(), "Route204South", local); +} + +// The console's first walk west: blocked after 800 ms, no chunk moved. +ScriptStep west_never_moved(){ + return walk_step("wall: T: west 2 (to wall)", WalkStop::BLOCKED, 1050ms, 0); +} + +// A youngster who steps off the leg's next tile while we wait is waited +// out, on a leg of two tiles too: the walk west then reaches the wall at +// (11, 2). The wait used to need a stop at least three tiles short of the +// wall, so the person one tile ahead was talked to instead. +UnitTestResult test_short_leg_waits_for_the_way(Logger&){ + Script script{.steps = { + west_never_moved(), + press_step("wait 2500 ms x1"), + walk_step("wall: T: west 2 (to wall)", WalkStop::BLOCKED, 3000ms, 2), + answer_step("dialog within 500 ms", false), + }}; + ScriptedWalk walk; + try{ + walk = walk_script(ravaged_path_world(), on_route204_south({13, 2}), on_route204_south({11, 2}), {}, script); + }catch (const ScriptMismatch& e){ + return e.message; + } + if (!walk.failure.empty() || !walk.fights.empty()){ + return std::format("expected to wait and walk on; fought {}, failure \"{}\".", walk.fights.size(), walk.failure); + } + if (walk.at != std::vector{on_route204_south({11, 2})}){ + return "did not arrive at Route 204 South (11, 2)."; + } + const std::string left = script_left(script); + return left.empty() ? UnitTestResult(true) : UnitTestResult(left); +} + +// Whether the replan after the youngster's talk starts from (13, 2) alone, +// with (12, 2) marked, and plans a route. +std::string check_never_moved_replan(const Script& script){ + const std::string replan = check_replan_from(script, {"Route 204 (13, 2)"}); + if (!replan.empty()){ + return replan; + } + const auto replan_note = std::find_if(script.notes.begin(), script.notes.end(), [](const std::string& note){ + return note.find("planning again") != std::string::npos; + }); + if (replan_note->find("(12, 2)") != std::string::npos){ + return "the replan still starts from the youngster's tile: " + *replan_note; + } + const auto marked = std::find_if(script.notes.begin(), script.notes.end(), [](const std::string& note){ + return note.find("marked it") != std::string::npos; + }); + if (marked == script.notes.end() || marked->find("(12, 2)") == std::string::npos){ + return "the youngster's tile (12, 2) was not marked."; + } + const size_t plans = std::count_if(script.notes.begin(), script.notes.end(), [](const std::string& note){ + return note.find("legs planned") != std::string::npos; + }); + if (plans != 2){ + return std::format("{} plans made, expected the first and the replan.", plans); + } + return ""; +} + +// The youngster stays on (12, 2) through both waits and talks without a +// battle. The console then planned from {(12, 2), (13, 2)}, one tile per +// tile the walk may have moved, and found no plan: an uncertain start +// needs a wall both tiles reach (wall_recovery_candidates()), and no wall +// is anchored from a tile someone wanders on, which both are. A walk that +// never moved stopped where it began: the replan starts from (13, 2) +// alone, with the youngster's tile marked. +UnitTestResult test_never_moved_plans_from_the_start(Logger& logger){ + const StoryWorld& world = ravaged_path_world(); + const std::vector console_from{on_route204_south({12, 2}), on_route204_south({13, 2})}; + if (!wall_recovery_candidates(world, console_from).empty()){ + return "the console's two tiles have a wall to anchor on: the cause is not the wander box."; + } + logger.log("No wall anchors from Route 204 South (12, 2) and (13, 2): both are in youngster_3's wander box."); + Script script{.steps = { + west_never_moved(), + press_step("wait 2500 ms x1"), + west_never_moved(), + press_step("wait 2500 ms x1"), + west_never_moved(), + press_step("A 80 ms x1"), + answer_step("dialog within 2000 ms", true), + }}; + ScriptedWalk walk; + std::string stopped_at; + try{ + walk = walk_script(world, on_route204_south({13, 2}), on_route204_south({11, 2}), {}, script); + }catch (const ScriptMismatch& e){ + // The walk after the replan is not scripted. + stopped_at = e.message; + } + if (!walk.failure.empty()){ + return "failed: " + walk.failure; + } + if (script.next != script.steps.size()){ + return "stopped at: " + stopped_at; + } + for (const std::string& note : script.notes){ + logger.log(note); + } + const std::string replan = check_never_moved_replan(script); + return replan.empty() ? UnitTestResult(true) : UnitTestResult(replan); +} + + struct PlannedRouteInput{ std::string name; std::function body; @@ -399,6 +519,14 @@ const PlannedRouteCase PLANNED_ROUTE_CASES[] = { .input = {"a known trainer stops an open leg", test_open_leg_known_trainer}, .expectation = {}, }, + { + .input = {"a person a tile ahead on a short leg is waited out", test_short_leg_waits_for_the_way}, + .expectation = {}, + }, + { + .input = {"a wall leg that never moved plans from its start", test_never_moved_plans_from_the_start}, + .expectation = {}, + }, }; void add_tests_AutoStory_PlannedRoute(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index 014870b7b5..45add5572c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -165,6 +165,19 @@ size_t tiles_moved(const WalkResult& walk, Milliseconds per_tile){ return moving.count() <= 0 ? (size_t)0 : (size_t)(moving / per_tile); } +// Whether a walk to the wall never moved: no chunk changed and its time +// counts no tile. It stopped where it began, so whoever stopped it stands +// on the next tile, however short the leg. On lab-B (2026-11-08 16:50, +// 01.08) Route 204's youngster, who wanders (12, 2) to (14, 2), stood a +// tile ahead of the leg "west 2 (to wall)" from (13, 2). The wait for the +// way needed a stop three tiles short of the wall, so he was talked to at +// once, and the replan from both (12, 2) and (13, 2) found no plan: an +// uncertain start needs a wall both tiles reach, and no wall is anchored +// from a tile someone wanders on. +bool never_moved(const WalkResult& walk, size_t walked_tiles){ + return walk.stop == WalkStop::BLOCKED && walk.moved_chunks == 0 && walked_tiles == 0; +} + // Whether a leg's walk goes on to the next leg or the route plans again. enum class LegNext{ NEXT_LEG, @@ -454,8 +467,13 @@ size_t RouteWalker::unstick_wall_leg(LegWalk& walk, size_t walked_tiles, size_t walked_tiles += tiles_moved(walk.result, per_tile); } // Someone walking about may stand in the way for a moment: wait and - // walk to the wall again before calling it an obstacle. - for (size_t again = 0; again < 2 && walk.result.stop == WalkStop::BLOCKED && walked_tiles + 2 < nearest; again++){ + // walk to the wall again before calling it an obstacle. A walk that + // never moved waits on a short leg too (never_moved()). + const auto in_the_way = [&]{ + return walk.result.stop == WalkStop::BLOCKED && + (walked_tiles + 2 < nearest || (nearest > 0 && never_moved(walk.result, walked_tiles))); + }; + for (size_t again = 0; again < 2 && in_the_way(); again++){ m_io.note("[Route] " + walk.label + ": stopped after about " + std::to_string(walked_tiles) + " tiles, short of the wall; waiting for the way to clear.", RouteNote::WARNING); m_io.press(WAIT_FOR_THE_WAY); @@ -469,10 +487,13 @@ LegNext RouteWalker::stopped_short_of_wall(LegWalk& walk, size_t walked_tiles){ // Someone who stays put: talk to them. A trainer we walked up to from // the side starts the battle this way. talk_to_blocker(walk.label); + // A walk that never moved is where it began (never_moved()); any other + // stop may be a tile either side of the tiles its time counts. + const size_t last = never_moved(walk.result, walked_tiles) ? 0 : walked_tiles + 1; std::vector stopped; for (const TilePos& pos : m_from){ const std::vector path = leg_path(m_grid, pos, walk.planned.leg.direction, SIZE_MAX); - for (size_t k = walked_tiles == 0 ? 0 : walked_tiles - 1; k <= walked_tiles + 1 && k <= path.size(); k++){ + for (size_t k = walked_tiles == 0 ? 0 : walked_tiles - 1; k <= last && k <= path.size(); k++){ stopped.push_back(k == 0 ? pos : path[k - 1]); } } From 5493a9eb8c64451eebe7450bf95383721e4e411a Mon Sep 17 00:00:00 2001 From: Di Fan <26423504+dayfine@users.noreply.github.com> Date: Sun, 8 Nov 2026 19:55:38 -0800 Subject: [PATCH 066/166] BDSP AutoStory: routes never run along a wander zone; short wall legs walk every tile (#277) * BDSP AutoStory: a wall leg that never moved waits, then plans from its start On lab-B (2026-11-08 16:50, 01.08 below_the_ravaged_path) the leg "west 2 (to wall)" from Route 204 (13, 2) stopped at once, 0 chunks moved: the youngster who wanders (12, 2) to (14, 2) stood a tile ahead. The wait for the way needed a stop three tiles short of the wall, so he was talked to at once, and the replan from both (12, 2) and (13, 2) found no plan: an uncertain start needs a wall both tiles reach, and no wall is anchored from a tile someone wanders on. A walk to the wall that never moved stopped where it began, so someone stands on the next tile: it now waits for the way on short legs too, and if they stay, the replan starts from the start tile alone with their tile marked. Two Planned route tests replay the run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: red tests for routes along wander zones and short wall legs On lab-B (2026-11-08, 01.08 below_the_ravaged_path) the plan "north 35 (to wall) to (13, 2), west 2 (to wall) to (11, 2)" walked along the row Route 204 South's youngster wanders, (12..14, 2). He stopped the leg west after 1 of 2 tiles; the check at the wall allowed a tile short on legs of two or three tiles, so the route logged arriving at (11, 2) from (13, 2). New tests, red on this commit: - Route planner: a leg may cross a row zone (one tile of it) but not run along it (two tiles, the start among them); no plan when the row is the only way. - Story table: every ROUTE step plans and none runs along a wander zone; 01.08's plan walks at most one tile of (12..14, 2). - Planned route: a 2-tile leg to a wall that ran out of time after 1 tile is a stop short of the wall, not the wall. The two #271 tests that replayed the console's leg along the youngster's row now replay it on a plain room: the planner will no longer plan it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: no route runs along a wander zone; short wall legs walk every tile plan_robust_route() no longer uses a leg that walks two tiles in a row of a zone where someone wanders (the leg's start among them): along a row zone, or through a 2-D one. Crossing a row zone through one tile is still planned at per_wander_tile, with #271's wait if he stands there. With no other way there is no plan; nothing falls back. A leg to a wall of 3 tiles or fewer that runs out of time short of its tiles is now a stop short of the wall (talk, then plan again), and the check at the wall needs every tile on such legs. Plans that change: 01.08 below_the_ravaged_path goes up column 14, then 12, and crosses the youngster's row at (12, 2) only; 00.05b below_the_tv_clown and 01.03 above_the_mine go round their wanderers. The story sim now plans ROUTE steps as walk_route() does (from a wall for a few start tiles, then default costs): from 01.03's two start tiles the search over both ran out of budget on the longer way. The grid sim's wait test crosses a row zone on a plain room, and Segment00Lines' reference line for 00.03 goes along Route 201's row 13, above the Breeder. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --------- Co-authored-by: Claude Opus 5.5 --- .../PokemonBDSP_AutoStory_RoutePlanner.cpp | 14 +- .../Data/PokemonBDSP_AutoStory_RoutePlanner.h | 9 +- .../PokemonBDSP_AutoStory_Segment00Lines.cpp | 4 +- ...kemonBDSP_AutoStory_PlannedRoute_Tests.cpp | 69 ++++++-- ...kemonBDSP_AutoStory_RoutePlanner_Tests.cpp | 48 +++++- ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 163 ++++++++++++++++-- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 34 ++-- ...onBDSP_AutoStory_StorySimulation_Tests.cpp | 10 +- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 20 ++- 9 files changed, 319 insertions(+), 52 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp index 184549ce82..0c2303cf3f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp @@ -222,10 +222,14 @@ struct Stepped{ TilePos end; int grass = 0; int wander = 0; + // Two tiles in a row where someone wanders, the start among them: the + // walk runs along their zone, and plan_robust_route() does not use it. + bool along_wander = false; }; std::optional step_tiles(const StoryWorld& world, TilePos from, Direction direction, int tiles){ Stepped stepped; int travelled = 0; + bool in_wander = wandering_hazard(world, from); while (travelled < tiles){ const std::optional next = step(world, from, direction); if (!next){ @@ -238,9 +242,12 @@ std::optional step_tiles(const StoryWorld& world, TilePos from, Directi if (tall_grass(world, *next)){ stepped.grass++; } - if (wandering_hazard(world, *next)){ + const bool next_wander = wandering_hazard(world, *next); + if (next_wander){ stepped.wander++; + stepped.along_wander |= in_wander; } + in_wander = next_wander; from = *next; } stepped.end = from; @@ -282,6 +289,9 @@ std::optional to_wall_leg(const StoryWorld& world, const Spread& spre return std::nullopt; } if (const std::optional stepped = step_tiles(world, pos, direction, (int)hit.tiles)){ + if (stepped->along_wander){ + return std::nullopt; + } grass = std::max(grass, stepped->grass); wander = std::max(wander, stepped->wander); } @@ -307,7 +317,7 @@ std::optional open_leg(const StoryWorld& world, const Spread& spread, for (const TilePos& pos : spread){ for (int n = std::max(1, tiles - error); n <= tiles + error; n++){ const std::optional stepped = step_tiles(world, pos, direction, n); - if (!stepped){ + if (!stepped || stepped->along_wander){ return std::nullopt; } grass = std::max(grass, stepped->grass); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h index 2376e8e59b..8e22ac6c33 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h @@ -129,8 +129,13 @@ struct RobustPlanCosts : TilePlanCosts{ // Cheapest legs that take the player from any of the tiles in `from` to tiles // that are all `goal`, even if every open leg ends up to `open_error` tiles // off: the walls of later legs must bring the possible positions together. -// Legs that would leave the maps or enter a door are not used. Nothing if no -// such plan exists, or none is found within `costs.max_searched` sets. +// Legs that would leave the maps or enter a door are not used, nor legs that +// run along a zone where someone wanders: two tiles of it in a row, the +// leg's start among them. Crossing a zone (one tile of it) costs +// `per_wander_tile`. On lab-B (2026-11-08, 01.08) Route 204's youngster, +// who wanders (12, 2) to (14, 2), stopped the leg "west 2 (to wall)" from +// (13, 2) twice. Nothing if no such plan exists, or none is found within +// `costs.max_searched` sets. std::optional> plan_robust_route( const StoryWorld& world, const std::vector& from, const std::function& goal, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp index c247bc3a35..c32ae18be4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp @@ -131,8 +131,10 @@ const std::vector& lines(){ walked("00.03", "the lake's entrance back to Rowan", { lakefront_point("lake_entrance"), lakefront({17, 21}), lakefront({29, 21}), route201_point("rowan_stop"), }, "Rowan and Dawn on the way back", {"Rowan and Dawn on the way back"}), + // Row 13, a row above the Breeder, who wanders (26..28, 14..16): no + // route runs along a wander zone (plan_robust_route()). walked("00.03", "Rowan to Dawn at Sandgem's entrance", { - route201_point("rowan_stop"), route201({17, 14}), route201({29, 14}), route201({41, 14}), + route201_point("rowan_stop"), route201({17, 14}), route201({17, 13}), route201({29, 13}), route201({41, 13}), route201({41, 7}), route201({42, 7}), route201({42, 5}), route201({52, 5}), route201_point("route_201_east_end"), sandgem_point("dawn_stop"), }, "Dawn at Sandgem's entrance", {"Dawn at Sandgem's entrance"}), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp index bbd9056ff9..a6368eccd3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp @@ -367,6 +367,14 @@ TilePos on_route204_south(TilePos local){ return story_to_world(ravaged_path_world(), "Route204South", local); } +// Routes no longer run along a wander zone, so that leg is no longer +// planned on Route 204 South: the walks below replay it on a plain room, +// from (3, 1) "west 2 (to wall)" to (1, 1), the person on (2, 1), with a +// row below to plan round them. +StoryWorld youngster_room(){ + return make_world({"#####", "#...#", "#...#", "#####"}); +} + // The console's first walk west: blocked after 800 ms, no chunk moved. ScriptStep west_never_moved(){ return walk_step("wall: T: west 2 (to wall)", WalkStop::BLOCKED, 1050ms, 0); @@ -385,38 +393,38 @@ UnitTestResult test_short_leg_waits_for_the_way(Logger&){ }}; ScriptedWalk walk; try{ - walk = walk_script(ravaged_path_world(), on_route204_south({13, 2}), on_route204_south({11, 2}), {}, script); + walk = walk_script(youngster_room(), {3, 1}, {1, 1}, {}, script); }catch (const ScriptMismatch& e){ return e.message; } if (!walk.failure.empty() || !walk.fights.empty()){ return std::format("expected to wait and walk on; fought {}, failure \"{}\".", walk.fights.size(), walk.failure); } - if (walk.at != std::vector{on_route204_south({11, 2})}){ - return "did not arrive at Route 204 South (11, 2)."; + if (walk.at != std::vector{{1, 1}}){ + return "did not arrive at (1, 1)."; } const std::string left = script_left(script); return left.empty() ? UnitTestResult(true) : UnitTestResult(left); } -// Whether the replan after the youngster's talk starts from (13, 2) alone, -// with (12, 2) marked, and plans a route. +// Whether the replan after the youngster's talk starts from (3, 1) alone, +// with (2, 1) marked, and plans a route. std::string check_never_moved_replan(const Script& script){ - const std::string replan = check_replan_from(script, {"Route 204 (13, 2)"}); + const std::string replan = check_replan_from(script, {"(3, 1)"}); if (!replan.empty()){ return replan; } const auto replan_note = std::find_if(script.notes.begin(), script.notes.end(), [](const std::string& note){ return note.find("planning again") != std::string::npos; }); - if (replan_note->find("(12, 2)") != std::string::npos){ + if (replan_note->find("(2, 1)") != std::string::npos){ return "the replan still starts from the youngster's tile: " + *replan_note; } const auto marked = std::find_if(script.notes.begin(), script.notes.end(), [](const std::string& note){ return note.find("marked it") != std::string::npos; }); - if (marked == script.notes.end() || marked->find("(12, 2)") == std::string::npos){ - return "the youngster's tile (12, 2) was not marked."; + if (marked == script.notes.end() || marked->find("(2, 1)") == std::string::npos){ + return "the youngster's tile (2, 1) was not marked."; } const size_t plans = std::count_if(script.notes.begin(), script.notes.end(), [](const std::string& note){ return note.find("legs planned") != std::string::npos; @@ -432,8 +440,8 @@ std::string check_never_moved_replan(const Script& script){ // tile the walk may have moved, and found no plan: an uncertain start // needs a wall both tiles reach (wall_recovery_candidates()), and no wall // is anchored from a tile someone wanders on, which both are. A walk that -// never moved stopped where it began: the replan starts from (13, 2) -// alone, with the youngster's tile marked. +// never moved stopped where it began: the replan starts from the start +// alone, with the youngster's tile marked (on youngster_room()). UnitTestResult test_never_moved_plans_from_the_start(Logger& logger){ const StoryWorld& world = ravaged_path_world(); const std::vector console_from{on_route204_south({12, 2}), on_route204_south({13, 2})}; @@ -453,7 +461,7 @@ UnitTestResult test_never_moved_plans_from_the_start(Logger& logger){ ScriptedWalk walk; std::string stopped_at; try{ - walk = walk_script(world, on_route204_south({13, 2}), on_route204_south({11, 2}), {}, script); + walk = walk_script(youngster_room(), {3, 1}, {1, 1}, {}, script); }catch (const ScriptMismatch& e){ // The walk after the replan is not scripted. stopped_at = e.message; @@ -471,6 +479,39 @@ UnitTestResult test_never_moved_plans_from_the_start(Logger& logger){ return replan.empty() ? UnitTestResult(true) : UnitTestResult(replan); } +// A leg to the wall two tiles away that runs out of time after one tile +// (one chunk moved): someone stands in it, as Route 204's youngster did on +// 01.08's "west 2 (to wall)" (lab-B 2026-11-08). The check at the wall +// allowed a tile short on legs of two or three tiles, so the stop against +// him passed as the wall and the route went on a tile off. Now it is a +// stop short of the wall: talk to whoever is there, then plan again. +UnitTestResult test_short_leg_a_tile_short_is_not_arrived(Logger&){ + const StoryWorld room = make_world({"####", "#..#", "#..#", "#..#", "####"}); + Script script{.steps = { + walk_step("wall: T: north 2 (to wall)", WalkStop::LIMIT, 1850ms, 1), + press_step("A 80 ms x1"), + answer_step("dialog within 2000 ms", false), + }}; + ScriptedWalk walk; + std::string stopped_at; + try{ + walk = walk_script(room, {1, 3}, {1, 1}, {}, script); + }catch (const ScriptMismatch& e){ + // The walk after the replan is not scripted. + stopped_at = e.message; + } + if (!walk.failure.empty()){ + return "failed: " + walk.failure; + } + if (script.next != script.steps.size()){ + return "went on as at the wall: " + stopped_at; + } + const bool replanned = std::any_of(script.notes.begin(), script.notes.end(), [](const std::string& note){ + return note.find("stopped early after about 1 tiles") != std::string::npos && note.find("planning again") != std::string::npos; + }); + return replanned ? UnitTestResult(true) : UnitTestResult("no replan after the stop a tile short."); +} + struct PlannedRouteInput{ std::string name; @@ -523,6 +564,10 @@ const PlannedRouteCase PLANNED_ROUTE_CASES[] = { .input = {"a person a tile ahead on a short leg is waited out", test_short_leg_waits_for_the_way}, .expectation = {}, }, + { + .input = {"a short leg to a wall a tile short is a stop, not the wall", test_short_leg_a_tile_short_is_not_arrived}, + .expectation = {}, + }, { .input = {"a wall leg that never moved plans from its start", test_never_moved_plans_from_the_start}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp index 5696886887..13029be081 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp @@ -30,7 +30,8 @@ namespace{ using Pokemon::Direction; using Pokemon::TilePos; -StoryWorld make_world(const std::vector& rows){ +// A map of `rows`, with someone wandering `wander` if given. +StoryWorld make_world(const std::vector& rows, const std::optional& wander = std::nullopt){ Pokemon::MapData map; map.name = "Test"; map.tiles = Pokemon::Grid{(int)rows[0].size(), (int)rows.size(), {}}; @@ -39,6 +40,10 @@ StoryWorld make_world(const std::vector& rows){ map.tiles.cells.push_back(*Pokemon::tile_from_glyph(glyph)); } } + if (wander){ + map.objects.push_back({.name = "wanderer", .x = wander->x0, .y = wander->y0, .facing = std::nullopt, + .wander = wander, .trainer = std::nullopt, .hide_flag = std::nullopt}); + } StoryWorld world; world.add("Test", map, {0, 0}); return world; @@ -137,6 +142,43 @@ UnitTestResult test_plan_robust_route(Logger&){ return true; } +// Someone wanders a row, (2..4, 2): a leg may cross the row through one of +// their tiles, but not run along it through two, the leg's start among +// them. On lab-B (2026-11-08, 01.08) Route 204's youngster stopped a leg +// west along his row twice. With no other way there is no plan. +UnitTestResult test_plan_robust_route_wander_zone(Logger&){ + const Pokemon::TileBox row_zone{.x0 = 2, .y0 = 2, .x1 = 4, .y1 = 2}; + const StoryWorld room = make_world({"#######", "#.....#", "#.....#", "#.....#", "#######"}, row_zone); + const StoryWorld corridor = make_world({"#######", "#.....#", "#######"}, Pokemon::TileBox{.x0 = 2, .y0 = 1, .x1 = 4, .y1 = 1}); + RobustPlanCosts exact; + exact.exact_open_tiles = exact.max_open_tiles; + struct ZoneCase{ + std::string name; + const StoryWorld& world; + TilePos from; + TilePos goal; + std::string legs; + }; + const std::vector cases{ + {.name = "south across the row", .world = room, .from = {3, 1}, .goal = {3, 3}, .legs = "south 2 (to wall) to (3, 3)"}, + {.name = "north across the row", .world = room, .from = {3, 3}, .goal = {3, 1}, .legs = "north 2 (to wall) to (3, 1)"}, + {.name = "east into the row's first tile", .world = room, .from = {1, 2}, .goal = {2, 2}, .legs = "east 1 (open) to (2, 2)"}, + {.name = "east along the row goes round it", .world = room, .from = {1, 2}, .goal = {5, 2}, + .legs = "north 1 (to wall) to (1, 1); east 4 (to wall) to (5, 1); south 1 (open) to (5, 2)"}, + {.name = "west along the row from inside it goes round", .world = room, .from = {3, 2}, .goal = {1, 2}, + .legs = "north 1 (to wall) to (3, 1); west 2 (to wall) to (1, 1); south 1 (open) to (1, 2)"}, + {.name = "no plan when the row is the only way", .world = corridor, .from = {1, 1}, .goal = {5, 1}, .legs = ""}, + }; + for (const ZoneCase& item : cases){ + const auto legs = plan_robust_route(item.world, {item.from}, [&](const TilePos& pos){ return pos == item.goal; }, exact); + const std::string read = legs ? describe(*legs) : ""; + if (read != item.legs){ + return std::format("{}: planned \"{}\", expected \"{}\".", item.name, read, item.legs); + } + } + return true; +} + // November 5 mine report: credited taps need not establish physical pose. // The two phases are explicit diagnostics, not inferred console timing. @@ -347,6 +389,10 @@ const RoutePlannerCase ROUTE_PLANNER_CASES[] = { .input = {"robust plans", test_plan_robust_route}, .expectation = {}, }, + { + .input = {"robust plans cross a wander zone, never along it", test_plan_robust_route_wander_zone}, + .expectation = {}, + }, { .input = {"trainers' sight lines", test_trainer_sight}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index a6797a9190..9bbbe47c36 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -5,11 +5,14 @@ */ #include +#include #include +#include #include #include #include #include +#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" @@ -257,14 +260,21 @@ std::string slides_into_door(const StoryWorld& world, const PlannedLeg& planned) return ""; } -// No ROUTE step of the table plans an open leg that ends before a door it -// walks toward: a door is gone through by a step that runs or taps into it -// from where the route ends on a wall or off its line. Where a row's steps -// leave the player is followed from its start through each step's target -// or pose_after; a route from an unknown place is not checked. -UnitTestResult test_story_routes_stop_short_of_doors(Logger& logger){ - std::vector found; - size_t checked = 0; +// A ROUTE step of the table from a known place: the world it plans on and +// its plan, or nothing if it finds none. +struct PlannedStoryRoute{ + std::string name; // " " + const StoryWorld* world; + std::vector from; + std::optional> legs; +}; + +// Every ROUTE step of the table that starts from a known place, planned as +// walk_route() plans it. Where a row's steps leave the player is followed +// from its start through each step's target or pose_after; a route from an +// unknown place is logged, not planned. +std::vector plan_story_routes(Logger& logger){ + std::vector routes; for (const StoryCheckpoint& row : story_checkpoints()){ std::optional at = row.start; for (const Pokemon::StoryStep& step : row.steps){ @@ -274,19 +284,36 @@ UnitTestResult test_story_routes_stop_short_of_doors(Logger& logger){ if (step.kind == StoryStepKind::ROUTE && world == nullptr){ logger.log(std::format("{} {}: not checked, from {}.", row.id, step.name, at ? Pokemon::to_string(*at) : "nowhere known")); } - const std::optional> legs = world ? route_step_plan(*world, *at, step) : std::nullopt; - checked += legs ? 1 : 0; - for (const PlannedLeg& planned : legs ? *legs : std::vector{}){ - const std::string why = slides_into_door(*world, planned); - if (!why.empty()){ - found.push_back(std::format("{} {}: {}.", row.id, step.name, why)); + if (world != nullptr){ + std::vector from; + for (const TilePos& pos : Pokemon::tiles_of(*at)){ + from.push_back(story_to_world(*world, at->map, pos)); } + routes.push_back({row.id + " " + step.name, world, std::move(from), route_step_plan(*world, *at, step)}); } at = step.kind == StoryStepKind::ROUTE ? step.target : step.pose_after ? step.pose_after : step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP ? std::nullopt : at; } } + return routes; +} + +// No ROUTE step of the table plans an open leg that ends before a door it +// walks toward: a door is gone through by a step that runs or taps into it +// from where the route ends on a wall or off its line. +UnitTestResult test_story_routes_stop_short_of_doors(Logger& logger){ + std::vector found; + size_t checked = 0; + for (const PlannedStoryRoute& route : plan_story_routes(logger)){ + checked += route.legs ? 1 : 0; + for (const PlannedLeg& planned : route.legs ? *route.legs : std::vector{}){ + const std::string why = slides_into_door(*route.world, planned); + if (!why.empty()){ + found.push_back(std::format("{}: {}.", route.name, why)); + } + } + } logger.log(std::format("{} routes planned.", checked)); std::string out; for (const std::string& line : found){ @@ -295,6 +322,106 @@ UnitTestResult test_story_routes_stop_short_of_doors(Logger& logger){ return found.empty() ? UnitTestResult(true) : UnitTestResult("Open legs that end before a door they walk toward:" + out); } +// The tiles a planned leg walks over from `from`, `from` first: to the wall, +// or its tiles' worth of steps. +std::vector walked_tiles(const StoryWorld& world, const TilePos& from, const TileLeg& leg){ + std::vector tiles{from}; + size_t walked = 0; + while (leg.ends_at_wall || walked < leg.tiles){ + const std::optional next = step(world, tiles.back(), leg.direction); + if (!next){ + break; + } + walked += (size_t)(std::abs(next->x - tiles.back().x) + std::abs(next->y - tiles.back().y)); + tiles.push_back(*next); + } + return tiles; +} + +// The most tiles of `zone` one leg of `legs` walks over, from any tile the +// player may be on, and that leg. +std::pair most_zone_tiles( + const StoryWorld& world, std::vector from, const std::vector& legs, + const std::function& zone +){ + std::pair most{0, ""}; + for (const PlannedLeg& planned : legs){ + for (const TilePos& pos : from){ + const std::vector tiles = walked_tiles(world, pos, planned.leg); + const size_t in_zone = (size_t)std::count_if(tiles.begin(), tiles.end(), zone); + if (in_zone > most.first){ + most = {in_zone, to_string(planned.leg) + " from " + describe(world, pos)}; + } + } + from = planned.after; + } + return most; +} + +// Where a planned leg from `from` runs along a zone where someone wanders, +// or "": two zone tiles in a row on a straight leg are tiles of one zone. +std::string along_wander_zone(const StoryWorld& world, const TilePos& from, const TileLeg& leg){ + const std::vector tiles = walked_tiles(world, from, leg); + for (size_t i = 1; i < tiles.size(); i++){ + if (wandering_hazard(world, tiles[i - 1]) && wandering_hazard(world, tiles[i])){ + return std::format("{} from {} runs along a wander zone at {}", to_string(leg), describe(world, from), describe(world, tiles[i])); + } + } + return ""; +} + +// Every ROUTE step of the table from a known place has a plan, and no leg +// of it runs along a zone where someone wanders: plan_robust_route() never +// plans one, so a step with no other way finds no plan here. +UnitTestResult test_story_routes_keep_off_wander_zones(Logger& logger){ + std::string out; + for (const PlannedStoryRoute& route : plan_story_routes(logger)){ + if (!route.legs){ + out += "\n " + route.name + ": no plan."; + continue; + } + std::vector from = route.from; + for (const PlannedLeg& planned : *route.legs){ + for (const TilePos& pos : from){ + const std::string along = along_wander_zone(*route.world, pos, planned.leg); + out += along.empty() ? "" : "\n " + route.name + ": " + along + "."; + } + from = planned.after; + } + } + return out.empty() ? UnitTestResult(true) : UnitTestResult("ROUTE steps:" + out); +} + +// 01.08's walk below the Ravaged Path keeps off the row Route 204 South's +// youngster_3 wanders, (12, 2) to (14, 2): on lab-B (2026-11-08) the plan +// "north 35 (to wall) to (13, 2), west 2 (to wall) to (11, 2)" walked along +// it, and he stopped the leg west twice. A leg may cross his row through +// one of his tiles, not walk two of them. +UnitTestResult test_ravaged_path_keeps_off_the_youngster(Logger& logger){ + for (const PlannedStoryRoute& route : plan_story_routes(logger)){ + if (route.name != "01.08 below_the_ravaged_path"){ + continue; + } + if (!route.legs){ + return "01.08 below_the_ravaged_path: no plan."; + } + const StoryWorld& world = *route.world; + for (const PlannedLeg& planned : *route.legs){ + logger.log("01.08 below_the_ravaged_path: " + to_string(planned)); + } + const auto youngster_row = [&](const TilePos& pos){ + const std::optional local = story_to_local(world, "Route204South", pos); + return local && local->y == 2 && local->x >= 12 && local->x <= 14; + }; + const auto [most, leg] = most_zone_tiles(world, route.from, *route.legs, youngster_row); + if (most >= 2){ + return std::format("the leg {} walks {} tiles of the youngster's row (12..14, 2).", leg, most); + } + return true; + } + return "01.08 below_the_ravaged_path is not a ROUTE step from a known place."; +} + struct AutoStoryStoryTableInput{ std::string name; @@ -351,6 +478,14 @@ const AutoStoryStoryTableCase AUTO_STORY_STORY_TABLE_CASES[] = { .input = {"Story table: no open leg ends before a door it walks toward (lab-B, 2026-11-08)", test_story_routes_stop_short_of_doors}, .expectation = {}, }, + { + .input = {"Story table: every route plans, and none runs along a wander zone", test_story_routes_keep_off_wander_zones}, + .expectation = {}, + }, + { + .input = {"01.08: the walk below the Ravaged Path keeps off the youngster's row (lab-B, 2026-11-08)", test_ravaged_path_keeps_off_the_youngster}, + .expectation = {}, + }, }; void add_tests_AutoStory_StoryTable(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 11ccb344d4..b87c43da62 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -46,7 +46,8 @@ using Pokemon::TileBox; using Pokemon::TilePos; -StoryWorld make_world(const std::vector& rows){ +// A map of `rows`, with someone wandering `wander` if given. +StoryWorld make_world(const std::vector& rows, const std::optional& wander = std::nullopt){ Pokemon::MapData map; map.name = "Test"; map.tiles = Pokemon::Grid{(int)rows[0].size(), (int)rows.size(), {}}; @@ -55,6 +56,10 @@ StoryWorld make_world(const std::vector& rows){ map.tiles.cells.push_back(*Pokemon::tile_from_glyph(glyph)); } } + if (wander){ + map.objects.push_back({.name = "wanderer", .x = wander->x0, .y = wander->y0, .facing = std::nullopt, + .wander = wander, .trainer = std::nullopt, .hide_flag = std::nullopt}); + } StoryWorld world; world.add("Test", map, {0, 0}); return world; @@ -684,30 +689,25 @@ UnitTestResult test_wandering_npc_routes_multi_seed(Logger& logger){ return true; } +// Routes never run along a wander zone, but cross one: a row someone +// wanders, (2..4, 2), crossed south at (3, 2) while they stand there. UnitTestResult test_wandering_npc_wait_clearance(Logger& logger){ - const StoryWorld* world = story_plan_world("OreburghCity", "OreburghCity"); - if (world == nullptr){ - return "OreburghCity world not found"; - } - const TilePos start = story_to_world(*world, "OreburghCity", {48, 22}); - const TilePos target = story_to_world(*world, "OreburghCity", {48, 30}); - const TileBox hiker_box{ - story_to_world(*world, "OreburghCity", {46, 25}).x, - story_to_world(*world, "OreburghCity", {46, 25}).y, - story_to_world(*world, "OreburghCity", {48, 27}).x, - story_to_world(*world, "OreburghCity", {48, 27}).y - }; + const TileBox row_zone{.x0 = 2, .y0 = 2, .x1 = 4, .y1 = 2}; + const StoryWorld room = make_world({"#######", "#.....#", "#.....#", "#.....#", "#.....#", "#######"}, row_zone); + const StoryWorld* world = &room; + const TilePos start{3, 1}; + const TilePos target{3, 4}; SimWanderer hiker{ .name = "hiker_0", - .box = hiker_box, - .pos = story_to_world(*world, "OreburghCity", {48, 26}), + .box = row_zone, + .pos = {3, 2}, .seed = 2, .step_interval = 2000ms, }; - GridSim sim({.world = world, .trainers = story_trainers(*world), .wanderers = {hiker}}, start, Direction::NORTH, true); + GridSim sim({.world = world, .trainers = {}, .wanderers = {hiker}}, start, Direction::NORTH, true); std::vector notes; GridSimRouteIO sim_io(sim, notes); - RouteTrainers trainers{story_trainers(*world), [&sim](const std::string&){ sim.end_dialogue(); }}; + RouteTrainers trainers{{}, [&sim](const std::string&){ sim.end_dialogue(); }}; const auto result = walk_route(sim_io, *world, {start}, trainers, { .goal = [&](const TilePos& pos){ return pos == target; }, .label = "walk_through_hiker", diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index 27c100db13..80f9c9f358 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -26,6 +26,7 @@ #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_StorySimulation_Tests.h" @@ -113,7 +114,14 @@ Walked plan_route(const Pose& from, const StoryStep& step){ targets.push_back(story_to_world(*world, goal.map, pos)); } const std::function at_goal = [&](const TilePos& pos){ return contains(targets, pos); }; - const auto plan = plan_robust_route(*world, start, at_goal, *costs); + // As walk_route() plans: from a wall when the start is one of a few + // tiles, then with the default costs if the step's find nothing. From + // 01.03's two start tiles a search over both found no plan within its + // budget once routes kept off the hiker's zone. + std::optional> plan = plan_recovered_route(*world, start, at_goal, *costs); + if (!plan){ + plan = plan_recovered_route(*world, start, at_goal, RobustPlanCosts()); + } if (!plan){ return {std::nullopt, step.name + ": no plan from" + describe(from.map, Pokemon::tiles_of(from)) + ".", ""}; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index 45add5572c..b2f2d0354f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -178,6 +178,19 @@ bool never_moved(const WalkResult& walk, size_t walked_tiles){ return walk.stop == WalkStop::BLOCKED && walk.moved_chunks == 0 && walked_tiles == 0; } +// Legs to a wall this many tiles or shorter must walk every tile: a tile +// short is someone in the way, not the time count's slack. On lab-B +// (2026-11-08, 01.08) Route 204's youngster stopped "west 2 (to wall)" +// after 1 tile; a tile short passed as at the wall, the route logged +// arriving at (11, 2) from (13, 2), and the taps north hit the cliff. +constexpr size_t EXACT_WALL_LEG_TILES = 3; + +// The fewest tiles a leg to a wall `expected_tiles` away must have walked +// to count as at its wall. +size_t min_tiles_at_wall(size_t expected_tiles){ + return expected_tiles > EXACT_WALL_LEG_TILES ? expected_tiles * 7 / 10 : expected_tiles; +} + // Whether a leg's walk goes on to the next leg or the route plans again. enum class LegNext{ NEXT_LEG, @@ -421,6 +434,10 @@ LegNext RouteWalker::wall_leg(LegWalk& walk){ // into the lab). Out of tall grass a stop reads, so walk on: a player // still moving is not where the plan has him. if (walk.result.stop == WalkStop::LIMIT && route_wall_readable(m_grid, walk.planned.after)){ + // A short leg a tile short stopped against someone in the way. + if (nearest <= EXACT_WALL_LEG_TILES && walked_tiles < nearest){ + return stopped_short_of_wall(walk, walked_tiles); + } check_at_wall(walk, walked_tiles, nearest); } return LegNext::NEXT_LEG; @@ -507,8 +524,7 @@ LegNext RouteWalker::stopped_short_of_wall(LegWalk& walk, size_t walked_tiles){ void RouteWalker::check_at_wall(LegWalk& walk, size_t walked_tiles, size_t expected_tiles){ if (expected_tiles != SIZE_MAX && expected_tiles > 0 && walked_tiles != SIZE_MAX){ - const size_t min_tiles = expected_tiles > 3 ? (expected_tiles * 7 / 10) : (expected_tiles > 1 ? expected_tiles - 1 : 1); - if (walked_tiles < min_tiles){ + if (walked_tiles < min_tiles_at_wall(expected_tiles)){ fail(m_io, walk.label + ": ran out of time well short of the wall (" + std::to_string(walked_tiles) + " of " + std::to_string(expected_tiles) + " tiles): not where the plan has us."); } From 8eece719702253de20a7f579794ab7b2c337d39f Mon Sep 17 00:00:00 2001 From: Di Fan <26423504+dayfine@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:07:13 -0800 Subject: [PATCH 067/166] BDSP AutoStory: recovery picks the cheapest whole walk; 01.10 runs into Floaroma (#278) * BDSP AutoStory: a wall leg that never moved waits, then plans from its start On lab-B (2026-11-08 16:50, 01.08 below_the_ravaged_path) the leg "west 2 (to wall)" from Route 204 (13, 2) stopped at once, 0 chunks moved: the youngster who wanders (12, 2) to (14, 2) stood a tile ahead. The wait for the way needed a stop three tiles short of the wall, so he was talked to at once, and the replan from both (12, 2) and (13, 2) found no plan: an uncertain start needs a wall both tiles reach, and no wall is anchored from a tile someone wanders on. A walk to the wall that never moved stopped where it began, so someone stands on the next tile: it now waits for the way on short legs too, and if they stay, the replan starts from the start tile alone with their tile marked. Two Planned route tests replay the run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: red tests for routes along wander zones and short wall legs On lab-B (2026-11-08, 01.08 below_the_ravaged_path) the plan "north 35 (to wall) to (13, 2), west 2 (to wall) to (11, 2)" walked along the row Route 204 South's youngster wanders, (12..14, 2). He stopped the leg west after 1 of 2 tiles; the check at the wall allowed a tile short on legs of two or three tiles, so the route logged arriving at (11, 2) from (13, 2). New tests, red on this commit: - Route planner: a leg may cross a row zone (one tile of it) but not run along it (two tiles, the start among them); no plan when the row is the only way. - Story table: every ROUTE step plans and none runs along a wander zone; 01.08's plan walks at most one tile of (12..14, 2). - Planned route: a 2-tile leg to a wall that ran out of time after 1 tile is a stop short of the wall, not the wall. The two #271 tests that replayed the console's leg along the youngster's row now replay it on a plain room: the planner will no longer plan it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: no route runs along a wander zone; short wall legs walk every tile plan_robust_route() no longer uses a leg that walks two tiles in a row of a zone where someone wanders (the leg's start among them): along a row zone, or through a 2-D one. Crossing a row zone through one tile is still planned at per_wander_tile, with #271's wait if he stands there. With no other way there is no plan; nothing falls back. A leg to a wall of 3 tiles or fewer that runs out of time short of its tiles is now a stop short of the wall (talk, then plan again), and the check at the wall needs every tile on such legs. Plans that change: 01.08 below_the_ravaged_path goes up column 14, then 12, and crosses the youngster's row at (12, 2) only; 00.05b below_the_tv_clown and 01.03 above_the_mine go round their wanderers. The story sim now plans ROUTE steps as walk_route() does (from a wall for a few start tiles, then default costs): from 01.03's two start tiles the search over both ran out of budget on the longer way. The grid sim's wait test crosses a row zone on a plain room, and Segment00Lines' reference line for 00.03 goes along Route 201's row 13, above the Breeder. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: red tests for 01.10's line-5 recovery wall and a battle on line 7 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: recovery takes the cheapest whole walk; 01.10 runs into Floaroma Recovery from a few possible tiles pinned the wall with the fewest held tiles and ignored the way on to the goal: after Taylor's battle on line 5 it held south 12 and walked 12 back where north 13 and 5 south would do. It now plans the way on from every anchor and keeps the cheapest whole walk. 01.10's last line ran an open leg up column 11, which has no wall north; a wild battle on it left no plan. The row now runs north until Floaroma's banner, which ends the same from any tile of the column, and 01.11 starts from the rows the run may stop on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: keep the story table under the length limit; line-7 cases as a table Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --------- Co-authored-by: Claude Opus 5.5 --- .../PokemonBDSP_AutoStory_RoutePlanner.cpp | 32 ++++ .../Data/PokemonBDSP_AutoStory_RoutePlanner.h | 10 ++ .../PokemonBDSP_AutoStory_WallRecovery.cpp | 27 +-- .../Data/PokemonBDSP_AutoStory_WallRecovery.h | 2 + ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 160 ++++++++++++++++++ .../PokemonBDSP_AutoStory_StoryTable.cpp | 21 +-- ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 32 ++++ ...onBDSP_AutoStory_StorySimulation_Tests.cpp | 4 + 8 files changed, 268 insertions(+), 20 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp index 0c2303cf3f..78e68ef048 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp @@ -469,6 +469,38 @@ std::optional> plan_robust_route( return RobustSearch(world, costs).run(from, goal); } +long long robust_route_cost( + const StoryWorld& world, + const std::vector& from, const std::vector& legs, + const RobustPlanCosts& costs +){ + long long total = 0; + Spread spread = from; + normalize(spread); + const TileLeg* previous = nullptr; + for (const PlannedLeg& planned : legs){ + const TileLeg& leg = planned.leg; + const std::optional expansion = leg.ends_at_wall + ? to_wall_leg(world, spread, leg.direction, costs) + : open_leg(world, spread, leg.direction, (int)leg.tiles, costs); + long long cost = (long long)costs.per_leg + (long long)costs.per_tile * (long long)leg.tiles; + if (!leg.ends_at_wall){ + cost += costs.leg_not_at_wall + (long long)costs.per_open_tile * (long long)leg.tiles; + } + if (expansion){ + cost = expansion->cost; + } + if (previous != nullptr && previous->direction == leg.direction && !previous->ends_at_wall){ + cost -= costs.per_leg; + } + total += cost; + spread = planned.after; + normalize(spread); + previous = ⋚ + } + return total; +} + } // namespace PokemonBDSP diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h index 8e22ac6c33..718d4bf513 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h @@ -148,6 +148,16 @@ std::optional> plan_robust_route( const RobustPlanCosts& costs = RobustPlanCosts() ); +// What plan_robust_route() charges for walking `legs` from any of `from`, +// each leg from the tiles the one before may end on. A leg it would not +// plan (along a wander zone, or off the maps) costs its tiles and legs +// without grass or wander tiles. +long long robust_route_cost( + const StoryWorld& world, + const std::vector& from, const std::vector& legs, + const RobustPlanCosts& costs +); + } // namespace PokemonBDSP diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp index 7ccc8549c5..3d73a54243 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp @@ -135,19 +135,26 @@ std::optional> plan_recovered_route( if (from.size() == 1){ return plan_robust_route(world, from, goal, costs); } - auto anchors = wall_recovery_candidates(world, from); - std::stable_sort(anchors.begin(), anchors.end(), [&](const auto& a, const auto& b){ - return goal(a.at) && !goal(b.at); - }); - for (const auto& anchor : anchors){ + // The cheapest whole walk, holds and the way on from the wall: the + // fewest held tiles alone chose "south 12 (to wall), north 12 (open)" + // over "north 13 (to wall), south 5 (open)" for 01.10's line 5 (lab-B + // 2026-11-08 18:15:47). Ties keep find_wall_anchors()' order. + std::optional> best; + long long best_cost = 0; + for (const auto& anchor : wall_recovery_candidates(world, from)){ const auto back = plan_robust_route(world, std::vector{anchor.at}, goal, costs); - if (back){ - auto route = recovery_legs(world, from, anchor.holds); - route.insert(route.end(), back->begin(), back->end()); - return route; + if (!back){ + continue; + } + auto route = recovery_legs(world, from, anchor.holds); + route.insert(route.end(), back->begin(), back->end()); + const long long cost = robust_route_cost(world, from, route, costs); + if (!best || cost < best_cost){ + best = std::move(route); + best_cost = cost; } } - return std::nullopt; + return best; } } // namespace PokemonBDSP diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h index 862e2a2f14..954f02c4ae 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h @@ -32,6 +32,8 @@ std::vector interrupted_leg_positions( // Establish a common wall anchor before continuing from an uncertain pose. // Single positions retain the existing planner. Ambiguous positions without // a safe anchor fail instead of choosing one. Goals already held need no walk. +// Of the anchors, the one whose whole walk, holds and the way on to the +// goal, costs least (robust_route_cost()). std::optional> plan_recovered_route( const StoryWorld& world, const std::vector& from, const std::function& goal, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index 794a08bc30..d448d579f4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -8,6 +8,7 @@ * physical cause. Run the real story step and route walker on GridSim. */ #include +#include #include #include #include @@ -643,6 +644,162 @@ const MineExitCase MINE_EXIT_CASES[] = { .expectation = {.below_the_door = false, .west_of_column_46 = std::nullopt}}, }; +// A wild battle after `tiles` tiles of the first walk north longer than +// that, tapped or run until a banner (none if 0); the walk goes on after +// it, as walk_tiles_dpad() and walk_until_dpad() go on after running. +class ColumnBattle{ +public: + ColumnBattle(std::vector& notes, size_t tiles) : m_notes(notes), m_tiles(tiles){} + size_t tiles() const{ return m_tiles; } + // Whether the battle comes after `tile` tiles of a walk of `tiles` `direction`. + bool after(Direction direction, size_t tiles, size_t tile){ + if (m_taken || m_tiles == 0 || direction != Direction::NORTH || tiles <= m_tiles || tile != m_tiles){ + return false; + } + m_taken = true; + m_notes.push_back(std::format("[Sim] a wild battle after {} tiles north.", tile)); + return true; + } +private: + std::vector& m_notes; + size_t m_tiles; + bool m_taken = false; +}; + +class ColumnBattleRouteIO : public GridSimRouteIO{ +public: + ColumnBattleRouteIO(GridSim& sim, std::vector& notes, ColumnBattle& battle) + : GridSimRouteIO(sim, notes), m_battle(battle) + {} + virtual WalkResult walk_taps(Direction direction, size_t tiles, const std::string& label) override{ + if (!m_battle.after(direction, tiles, m_battle.tiles())){ + return GridSimRouteIO::walk_taps(direction, tiles, label); + } + WalkResult result = GridSimRouteIO::walk_taps(direction, m_battle.tiles(), label); + const WalkResult rest = GridSimRouteIO::walk_taps(direction, tiles - m_battle.tiles(), label); + result.stop = rest.stop; + result.walked += rest.walked; + result.moved_chunks += rest.moved_chunks; + result.wild_battles++; + return result; + } +private: + ColumnBattle& m_battle; +}; + +// RecoveryStepIO that also runs until a map's banner: it reads +// SIM_BANNER_TILES into the map, as the story simulation's does, or where +// something stops the run on it. +class BannerStepIO : public RecoveryStepIO{ +public: + static constexpr size_t SIM_BANNER_TILES = 3; + BannerStepIO(RouteIO& route, GridSim& sim, ColumnBattle& battle) : RecoveryStepIO(route), m_sim(sim), m_battle(battle){} + virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override{ + size_t on = 0; + size_t tiles = 0; + for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ + m_battle.after(direction, SIZE_MAX, tiles); + const SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + tiles++; + const bool stopped = move.distance == 0 || move.stop != SimStop::DONE; + on = story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)) ? on + 1 : 0; + if (on > 0 && (on >= SIM_BANNER_TILES || stopped)){ + return true; + } + if (stopped){ + return false; + } + } + return false; + } +private: + GridSim& m_sim; + ColumnBattle& m_battle; +}; + +// 01.10's last stretch, north up column 11 from (11, 12) through the grass +// on (11, 5..11) into Floaroma (lab-B 2026-11-08 18:17:53): a wild battle +// on "north 7 (open)" to (11, 5) left (11, 5..12), and no plan came, for +// column 11 has no wall to the north and no other wall brings those tiles +// together. The table's steps after line 6, with a wild battle the input's +// tiles up, must end in Floaroma where the row's last walk says. +struct LineSevenInput{ + std::string name; + size_t battle_after_tiles = 0; +}; +struct LineSevenExpectation{ +}; +struct LineSevenCase{ + LineSevenInput input; + LineSevenExpectation expectation; +}; + +UnitTestResult test_line_7_battle_reaches_floaroma(Logger& logger, const LineSevenInput& input){ + const StoryWorld& world = *story_plan_world("Route204North", "FloaromaTown"); + GridSim sim({.world = &world}, story_to_world(world, "Route204North", {11, 12}), Direction::WEST, true); + std::vector notes; + ColumnBattle battle(notes, input.battle_after_tiles); + ColumnBattleRouteIO route(sim, notes, battle); + BannerStepIO io(route, sim, battle); + StoryWalkSteps walks(io); + walks.begin_attempt("01.10"); + Pokemon::RunState state{.pose = Pokemon::tile_pose("Route204North", {{11, 12}}, Direction::WEST), .flags = {}}; + std::string failure; + std::optional last; + try{ + bool after_line_6 = false; + for (const Pokemon::StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const Pokemon::StoryStep& step : checkpoint.id == "01.10" ? checkpoint.steps : std::vector{}){ + const bool walks_here = after_line_6 && (step.kind == Pokemon::StoryStepKind::ROUTE || step.kind == Pokemon::StoryStepKind::LEGS); + after_line_6 |= step.name == "line_6"; + if (!walks_here || !failure.empty()){ + continue; + } + const Pokemon::Outcome outcome = step.kind == Pokemon::StoryStepKind::ROUTE ? walks.route(state, step) : walks.legs(state, step); + failure = outcome.failure; + last = step.pose_after ? step.pose_after : step.target; + state.pose = outcome.pose ? *outcome.pose : *last; + logger.log(std::format("01.10 {} ended at {}.", step.name, to_string(sim.player().pos))); + } + } + }catch (const GridSimFailure& error){ + failure = error.message; + } + for (const std::string& note : notes){ + logger.log(note); + } + if (!failure.empty() || !last){ + return "01.10 after line 6: " + (failure.empty() ? std::string("no walk") : failure); + } + const std::vector tiles = Pokemon::tiles_of(*last); + const auto end = story_to_local(world, last->map, nearest_tile(sim.player().pos)); + if (!end || std::find(tiles.begin(), tiles.end(), *end) == tiles.end()){ + return std::format("01.10 ended at {}, not on {}.", to_string(sim.player().pos), Pokemon::to_string(*last)); + } + if (last->map != "FloaromaTown"){ + return "01.10 ends on " + last->map + ", not in Floaroma."; + } + return true; +} + +class Test_LineSevenBattle : public UnitTest{ +public: + explicit Test_LineSevenBattle(LineSevenCase data) + : UnitTest("PokemonBDSP::AutoStory - Recovery walk: 01.10 into Floaroma, " + data.input.name), m_case(std::move(data)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + return test_line_7_battle_reaches_floaroma(logger, m_case.input); + } +private: + LineSevenCase m_case; +}; + +const LineSevenCase LINE_SEVEN_CASES[] = { + {.input = {.name = "no battle", .battle_after_tiles = 0}, .expectation = {}}, + {.input = {.name = "a wild battle 3 tiles up (lab-B, 2026-11-08)", .battle_after_tiles = 3}, .expectation = {}}, + {.input = {.name = "a wild battle 6 tiles up", .battle_after_tiles = 6}, .expectation = {}}, +}; + } // namespace void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ @@ -672,6 +829,9 @@ void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ for (const MineExitCase& scenario : MINE_EXIT_CASES){ database.add(scenario); } + for (const LineSevenCase& scenario : LINE_SEVEN_CASES){ + database.add(scenario); + } } } // namespace PokemonBDSP } // namespace NintendoSwitch diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 2f7cb7123d..650259e1e5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -848,19 +848,20 @@ StoryCheckpoint through_the_ravaged_path(){ } // 01.10: the line a human walked up Route 204's north half (2026-10-31, -// r246a to r251a), corner to corner (Test_Route204NorthLine checks each -// stretch is one straight leg), then north between the flower beds into -// Floaroma. Its trainers who see us are fought: Taylor on the line, the -// Twins as a pair. +// r246a to r251a; Test_Route204NorthLine), then north up column 11 until +// Floaroma's banner, which reads on (11, 27..29): the column has no wall +// north, so a wild battle on an open leg to the line's last corner (11, 5) +// found no plan back (lab-B 2026-11-08 18:17:53). Taylor and the Twins fight. +Pose into_floaroma(){ return Pokemon::tile_pose(FLOAROMA, {TilePos{11, 27}, TilePos{11, 28}, TilePos{11, 29}}, NORTH); } StoryCheckpoint route_204_to_floaroma(){ std::vector steps; const std::vector line = map_region(ROUTE_204_NORTH, "floaroma_waypoints"); - for (size_t i = 0; i < line.size(); i++){ + for (size_t i = 0; i + 1 < line.size(); i++){ steps.push_back(route(std::format("line_{}", i + 1), Pokemon::tile_pose(ROUTE_204_NORTH, {line[i]}), "a corner of the human's line", "line")); } - // 01.11 walks on from here: west 8 along row 29, north to the old woman. - steps.push_back(route("into_floaroma", at(FLOAROMA, "route_204_arrival", NORTH), "north up column 11 into Floaroma", "line")); + steps.push_back(anchored(legs("into_floaroma", {{.direction = NORTH, .tiles = 17}}, + "run north until Floaroma's banner; on after a wild battle", "to_map"), into_floaroma())); steps.push_back(save()); return row("01.10", "Route 204 to Floaroma", at(ROUTE_204_NORTH, "cave_exit", SOUTH), std::move(steps)); } @@ -890,12 +891,12 @@ std::vector to_oreburgh(){ // 01.11 on Floaroma's map: the old woman (3, 25) and the old man (2, 25) // west of her stand still above the flower field's bottom row (r251a). // The walk to her is the one that ran on the console: 8 taps west along -// row 29, then north until she stops us (r250a: 3 steps, then bumps). +// row 29 (or 27, 28), then north until she stops us (r250a: 3 steps, bumps). StoryCheckpoint floaromas_old_couple(){ const Pose below_the_old_woman = next_to(FLOAROMA, "old_woman", SOUTH, NORTH); const Pose below_the_old_man = next_to(FLOAROMA, "old_man", SOUTH, NORTH); - return row("01.11", "Floaroma's old couple", at(FLOAROMA, "route_204_arrival", NORTH), { - legs("west_along_the_field", {{.direction = WEST, .tiles = 8}}, "8 taps west along row 29"), + return row("01.11", "Floaroma's old couple", into_floaroma(), { + legs("west_along_the_field", {{.direction = WEST, .tiles = 8}}, "8 taps west along the row we stopped on"), anchored(to_walls("up_to_the_old_woman", {{.direction = NORTH, .tiles = 5}}, "north until she stops us"), below_the_old_woman), talk("old_woman", "she gives Mew when a Let's Go save is on the console"), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index 9bbbe47c36..a11e09f379 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -224,6 +224,34 @@ UnitTestResult test_route204_north_line(Logger& logger){ return true; } +// 01.10's line 5, "north 10 (open)" to (19, 12), after Aroma Lady Taylor's +// battle (lab-B 2026-11-08 18:15:47): we may stand anywhere on (19, 12..20). +// Column 19 is open floor from row 7 to 13 below the wall on row 6, so north +// to that wall and 5 south reach the goal; the console's plan, "south 12 (to +// wall) to (19, 24), north 12 (open) to (19, 12)", pinned the wall with the +// fewest held tiles and walked back twice as far. +UnitTestResult test_line_5_recovery_pins_the_wall_nearest_the_goal(Logger& logger){ + const StoryWorld& world = *story_plan_world("Route204North", "Route204North"); + std::vector from; + for (int y = 12; y <= 20; y++){ + from.push_back(story_to_world(world, "Route204North", {19, y})); + } + const TilePos goal = story_to_world(world, "Route204North", {19, 12}); + const auto legs = plan_recovered_route(world, from, [&](const TilePos& pos){ return pos == goal; }, *story_route_costs("line")); + if (!legs || legs->empty()){ + return "no plan from (19, 12..20)."; + } + for (const PlannedLeg& planned : *legs){ + logger.log("01.10 line 5 recovery: " + to_string(planned)); + } + const PlannedLeg& first = legs->front(); + const TilePos wall = story_to_world(world, "Route204North", {19, 7}); + if (first.leg.direction != Direction::NORTH || !first.leg.ends_at_wall || first.after != std::vector{wall}){ + return "the recovery starts " + to_string(first) + ", not north to the wall at (19, 7)."; + } + return true; +} + // The legs a ROUTE step from `from` plans, as walk_route() plans them (the // step's costs, then the default ones), on `world`; nothing if none. std::optional> route_step_plan(const StoryWorld& world, const Pokemon::Pose& from, const Pokemon::StoryStep& step){ @@ -474,6 +502,10 @@ const AutoStoryStoryTableCase AUTO_STORY_STORY_TABLE_CASES[] = { .input = {"Route 204 North: the line into Floaroma", test_route204_north_line}, .expectation = {}, }, + { + .input = {"01.10: line 5's recovery pins the wall nearest its goal (lab-B, 2026-11-08)", test_line_5_recovery_pins_the_wall_nearest_the_goal}, + .expectation = {}, + }, { .input = {"Story table: no open leg ends before a door it walks toward (lab-B, 2026-11-08)", test_story_routes_stop_short_of_doors}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index 80f9c9f358..e2eda64d12 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -171,6 +171,10 @@ Walked walk_legs(const Pose& from, const StoryStep& step){ if (step.variant == "to_wall"){ return {std::nullopt, "", ""}; } + // A run until a map's banner ends where the banner reads. + if (step.variant == "to_map"){ + return {step.pose_after, "", ""}; + } const StoryWorld* world = story_plan_world(from.map, from.map); if (world == nullptr){ return {std::nullopt, step.name + ": no world holds " + from.map + ".", ""}; From e686375116d7bb78c3efc50e60e04a32745615bd Mon Sep 17 00:00:00 2001 From: Di Fan <26423504+dayfine@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:16:03 -0800 Subject: [PATCH 068/166] BDSP: test portability fix + #263 (01.03 authored JSON) into the BDSP line (#264) * Make existing BDSP recovery tests compile across GCC and Clang-cl * BDSP: load mine/Roark checkpoint from shared authored JSON (#263) * Load BDSP mine checkpoint from shared JSON without changing its executor * Pin the BDSP replay schema correction for paired CI * Compare normalized checkpoint semantics instead of optional JSON defaults * Share authored checkpoint envelopes and embedded resource loading * Use shared authored checkpoint loading for BDSP * Make the native mine plan authoritative and address data review * Space BDSP data declarations and test mutation helpers * Resolve simulator staging root across Python versions * Keep existing Git normalization rules for authored story data * Report actual BDSP story data values in test failures * BDSP AutoStory: the mine doc's above_the_mine stops two short of the warps #269 moved the route's target to (46, 57); the authored plan follows it in the merge, and its doc now says so too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --------- Co-authored-by: Claude Opus 5.5 --- .../workflows/cpp-ci-serial-programs-base.yml | 40 ++++ SerialPrograms/CMakeLists.txt | 14 ++ .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 2 + ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 5 +- .../PokemonBDSP_AutoStory_StoryData.cpp | 56 +++++ .../PokemonBDSP_AutoStory_StoryData.h | 34 +++ .../PokemonBDSP_AutoStory_StoryData_Tests.cpp | 195 +++++++++++++++++ .../PokemonBDSP_AutoStory_StoryData_Tests.h | 22 ++ .../PokemonBDSP_AutoStory_StoryTable.cpp | 108 +--------- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 2 +- ...onBDSP_AutoStory_StorySimulation_Tests.cpp | 25 +++ .../Programs/AutoStory/StoryData/README.md | 16 ++ .../AutoStory/StoryData/bdsp-mine-01.03.md | 41 ++++ .../StoryData/bdsp-mine-01.03.plan.json | 197 ++++++++++++++++++ SerialPrograms/cmake/SourceFiles.cmake | 4 + 15 files changed, 653 insertions(+), 108 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/README.md create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-mine-01.03.md create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-mine-01.03.plan.json diff --git a/.github/workflows/cpp-ci-serial-programs-base.yml b/.github/workflows/cpp-ci-serial-programs-base.yml index a87f526da4..40452d1067 100644 --- a/.github/workflows/cpp-ci-serial-programs-base.yml +++ b/.github/workflows/cpp-ci-serial-programs-base.yml @@ -96,6 +96,46 @@ jobs: operation: prepare consumer-directory: Arduino-Source + - name: Checkout authored BDSP story simulator + if: startsWith(inputs.os, 'ubuntu') && inputs.run-tests + uses: actions/checkout@v7 + with: + repository: dayfine/PokemonSimulation + ref: cf365e1722dea03fcf40c322b910332fcc864ea4 + path: AuthoredStorySource + + - name: Replay the authoritative Arduino mine plan + if: startsWith(inputs.os, 'ubuntu') && inputs.run-tests + env: + PYTHONPATH: AuthoredStorySource/src + run: | + python3 - <<'PYTHON' + from pathlib import Path + import hashlib, json, tempfile + from pokesim.story.replay_binding import load_binding + from pokesim.story.replay_cases import read_cases, check_case + from pokesim.story.checkpoint_replay import run + source = Path('AuthoredStorySource').resolve() + folder = source / 'data/story/bdsp-mine-pilot' + native = Path('Arduino-Source/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData') + # The Arduino plan is authoritative; bind these exact bytes explicitly. + # The simulator's checked-in plan is only a frozen regression snapshot. + with tempfile.TemporaryDirectory(prefix='.native-story-', dir=source) as temporary: + stage = Path(temporary) + raw = (native / 'bdsp-mine-01.03.plan.json').read_bytes() + (stage / 'plan.json').write_bytes(raw) + profile = json.loads((folder / 'binding.json').read_text()) + profile['plan'] = {'file': str((stage / 'plan.json').relative_to(source)), + 'sha256': hashlib.sha256(raw).hexdigest()} + (stage / 'binding.json').write_text(json.dumps(profile)) + binding = load_binding(stage / 'binding.json', source) + cases = read_cases(folder / 'cases.json') + for case in cases: + check_case(case, run(binding, case['input'])) + print(case['id'] + ': current Arduino plan replay passed') + assert len(cases) == 9 + PYTHON + - name: Install Qt uses: jurplel/install-qt-action@v4 with: diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index 0fe561e736..bc51b4daf2 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -240,6 +240,20 @@ pa_pokesim_map_directory(BDSP_MAP_DIRECTORY bdsp "${POKESIM_CONSUMER}" "${POKESI file(RELATIVE_PATH BDSP_MAP_RESOURCES "${CMAKE_CURRENT_SOURCE_DIR}" "${BDSP_MAP_DIRECTORY}") pa_embed_text_files(SerialProgramsLib "${BDSP_MAP_RESOURCES}" PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h PokemonAutomation::NintendoSwitch::PokemonBDSP bdsp_map_json) +# TODO: Move JSON syntax preflight into pa_embed_text_files so map and story +# resources share it. Keep game/schema/semantic checks in their native tests. +# Catch JSON syntax errors during a lab build, before static table initialization. +# Native tests still validate the schema, game policy and execution semantics. +file(GLOB BDSP_STORY_FILES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/Source/PokemonBDSP/Programs/AutoStory/StoryData/*.json") +foreach(BDSP_STORY_FILE IN LISTS BDSP_STORY_FILES) + file(READ "${BDSP_STORY_FILE}" BDSP_STORY_TEXT) + string(JSON BDSP_STORY_TYPE ERROR_VARIABLE BDSP_STORY_ERROR TYPE "${BDSP_STORY_TEXT}") + if(BDSP_STORY_ERROR OR NOT BDSP_STORY_TYPE STREQUAL "OBJECT") + message(FATAL_ERROR "Invalid authored checkpoint ${BDSP_STORY_FILE}: ${BDSP_STORY_ERROR}") + endif() +endforeach() +pa_embed_text_files(SerialProgramsLib Source/PokemonBDSP/Programs/AutoStory/StoryData + PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.h PokemonAutomation::NintendoSwitch::PokemonBDSP bdsp_checkpoint_json) # Create binary target diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index 72c29a2fa1..40be88c76f 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -16,6 +16,7 @@ #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h" #include "PokemonBDSP_Tests.h" @@ -34,6 +35,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_StoryMaps(database); add_tests_AutoStory_Segment00(database); add_tests_AutoStory_StorySimulation(database); + add_tests_AutoStory_StoryData(database); add_tests_AutoStory_StoryTable(database); add_tests_AutoStory_Walk(database); add_tests_AutoStory_PlannedRoute(database); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index d448d579f4..5af1245470 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" @@ -218,7 +219,7 @@ class WallStepIO : public RecoveryStepIO{ GridSim& m_sim; }; -const Pokemon::StoryStep& story_step(const std::string& row, const std::string& name){ +const Pokemon::StoryStep& story_step(std::string_view row, std::string_view name){ for (const Pokemon::StoryCheckpoint& checkpoint : story_checkpoints()){ for (const Pokemon::StoryStep& step : checkpoint.steps){ if (checkpoint.id == row && step.name == name){ @@ -226,7 +227,7 @@ const Pokemon::StoryStep& story_step(const std::string& row, const std::string& } } } - throw GridSimFailure{"no step " + name + " in " + row}; + throw GridSimFailure{std::format("no step {} in {}", name, row)}; } // lab-B 2026-11-08 11:55: a wild battle on 01.03's counted taps across diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.cpp new file mode 100644 index 0000000000..8fecf57098 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.cpp @@ -0,0 +1,56 @@ +/* BDSP Authored Checkpoint Data + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.h" +#include "PokemonBDSP_AutoStory_StoryData.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +StoryFailure read_failure(std::string_view value){ + if (value == "reload_and_retry"){ + return StoryFailure::RELOAD_AND_RETRY; + } + if (value == "stop"){ + return StoryFailure::STOP; + } + throw ParseException("Unsupported BDSP failure policy: " + std::string(value)); +} + +StoryCheckpoint apply_execution(Pokemon::AuthoredCheckpoint parsed, std::string_view source){ + const JsonObject& execution = parsed.execution; + Pokemon::require_story_json_fields(execution, {"on_failure", "saves_in"}, source); + StoryCheckpoint result; + static_cast(result) = std::move(parsed.checkpoint); + result.on_failure = read_failure(execution.get_string_throw("on_failure")); + result.saves_in = execution.get_string_throw("saves_in"); + if ((result.on_failure == StoryFailure::RELOAD_AND_RETRY) == result.saves_in.empty()){ + throw ParseException("BDSP save-card location is required exactly when the checkpoint saves/retries."); + } + return result; +} + +} // namespace + +StoryCheckpoint read_authored_checkpoint(const JsonValue& value, std::string_view source){ + return apply_execution(Pokemon::read_authored_checkpoint(value, "bdsp", source), source); +} + +StoryCheckpoint load_authored_checkpoint(std::string_view file){ + return apply_execution(Pokemon::load_authored_checkpoint(bdsp_checkpoint_json(), file, "bdsp"), file); +} + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.h new file mode 100644 index 0000000000..ef56b77bca --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.h @@ -0,0 +1,34 @@ +/* BDSP Authored Checkpoint Data + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryData_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryData_H + +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "PokemonBDSP_AutoStory_StoryExecutor.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Strict authored envelope and BDSP save/failure configuration; no controller IO. +// Unknown fields/values or inconsistent save policy throw ParseException. +StoryCheckpoint read_authored_checkpoint(const JsonValue& value, std::string_view source); + +// The embedded authored JSON files, keyed by filename without .json. +const std::vector>& bdsp_checkpoint_json(); + +// Load an embedded authored checkpoint; a missing file throws InternalProgramError. +StoryCheckpoint load_authored_checkpoint(std::string_view file); +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.cpp new file mode 100644 index 0000000000..98c70e6f7a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.cpp @@ -0,0 +1,195 @@ +/* BDSP Authored Checkpoint Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepJson.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP_AutoStory_StoryData.h" +#include "PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP_AutoStory_StoryData_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +struct Input{ + std::string_view name; + void (*mutate)(JsonObject&) = nullptr; +}; + +struct Expectation{ + bool rejected = false; +}; +struct Case{ + Input input; + Expectation expectation; +}; +void extra(JsonObject& root){ + root["unknown"] = true; +} + +void wrong_game(JsonObject& root){ + root["game"] = "frlg"; +} + +void wrong_policy(JsonObject& root){ + root.get_object_throw("execution")["on_failure"] = "guess"; +} + +void missing_card(JsonObject& root){ + root.get_object_throw("execution")["saves_in"] = ""; +} + +void stop_with_save(JsonObject& root){ + root.get_object_throw("execution")["on_failure"] = "stop"; +} + +const Case CASES[] = { + {.input = {.name = "mine resource is registered with ordered events and save policy"}, .expectation = {}}, + {.input = {.name = "extra envelope field", .mutate = extra}, .expectation = {.rejected = true}}, + {.input = {.name = "wrong game", .mutate = wrong_game}, .expectation = {.rejected = true}}, + {.input = {.name = "unknown failure policy", .mutate = wrong_policy}, .expectation = {.rejected = true}}, + {.input = {.name = "missing save-card location", .mutate = missing_card}, .expectation = {.rejected = true}}, + {.input = {.name = "stop policy must not claim a start save", .mutate = stop_with_save}, .expectation = {.rejected = true}}, +}; + +std::string string_list(const std::vector& values){ + JsonArray result; + for (const std::string& value : values){ + result.push_back(value); + } + return result.dump(-1); +} + +std::string tile_list(const std::vector& tiles){ + std::vector values; + for (const auto& tile : tiles){ + values.push_back(Pokemon::to_string(tile)); + } + return string_list(values); +} + +std::string policy(const StoryCheckpoint& row){ + return std::format("{}; saves_in=\"{}\"", + row.on_failure == StoryFailure::RELOAD_AND_RETRY ? "reload_and_retry" : "stop", row.saves_in); +} + +JsonValue plan(){ + std::vector names; + for (const auto& [name, text] : bdsp_checkpoint_json()){ + names.push_back(name); + if (name == "bdsp-mine-01.03.plan"){ + return parse_json(text); + } + } + throw ParseException("Expected embedded bdsp-mine-01.03.plan.json; read resource names " + string_list(names)); +} + +// Literal authored poses must stay aligned with the map-derived anchors +// used by adjacent checkpoints; a map correction must trigger plan review. +std::string check_map_anchors(const StoryCheckpoint& loaded){ + const std::vector doorstep{ + {47, 21}, map_point("OreburghCity", "pokemon_center_doorstep") + }; + if (!loaded.start || Pokemon::tiles_of(*loaded.start) != doorstep){ + return "Expected Center exit tiles " + tile_list(doorstep) + "; read " + + (loaded.start ? Pokemon::story_pose_json(*loaded.start).dump(-1) : "absent start"); + } + const std::vector below_roark{ + map_point("OreburghMine", "roark").next(Pokemon::Direction::SOUTH) + }; + for (const auto& step : loaded.steps){ + const bool roark = step.name == "below_roark" || step.name == "roark_smashes_the_rock"; + if (roark || step.name == "heal_oreburgh"){ + const auto& expected = roark ? below_roark : doorstep; + if (!step.pose_after || Pokemon::tiles_of(*step.pose_after) != expected){ + return "Expected " + step.name + " arrival tiles " + tile_list(expected) + "; read " + + (step.pose_after ? Pokemon::story_pose_json(*step.pose_after).dump(-1) : "absent arrival"); + } + } + } + return ""; +} + +std::string check_registration(const StoryCheckpoint& loaded){ + const auto& rows = story_checkpoints(); + const auto row = std::find_if(rows.begin(), rows.end(), [](const StoryCheckpoint& x){ return x.id == "01.03"; }); + // Wiring check only: both values originate in the authored resource. + // Route correctness is covered by separate scenario expectations. + if (row == rows.end()){ + std::vector ids; + for (const auto& entry : rows){ + ids.push_back(entry.id); + } + return "Expected registered checkpoint 01.03; read checkpoint IDs " + string_list(ids); + } + if (Pokemon::story_checkpoint_json(*row) != Pokemon::story_checkpoint_json(loaded)){ + return "Expected registered resource " + Pokemon::story_checkpoint_json(loaded).dump(-1) + + "; read table record " + Pokemon::story_checkpoint_json(*row).dump(-1); + } + if (loaded.on_failure != StoryFailure::RELOAD_AND_RETRY || loaded.saves_in != "Oreburgh City" + || row->on_failure != loaded.on_failure || row->saves_in != loaded.saves_in){ + return "Expected reload_and_retry; saves_in=\"Oreburgh City\" for resource and table; read resource " + + policy(loaded) + "; table " + policy(*row); + } + const std::vector expected{ + "above_the_mine", "into_the_mine", "into_the_coal_room", "south_to_the_rock", + "to_roarks_corner", "beside_roarks_rock", "below_roark", "roark", "roark_smashes_the_rock", + "below_the_coal_rooms_warp", "up_to_the_hall", "out_of_the_mine", + "north_to_the_centers_wall", "east_below_the_centers_door", "heal_oreburgh" + }; + std::vector actual; + for (const auto& step : loaded.steps){ + actual.push_back(step.name); + } + if (actual != expected){ + return "Expected event IDs " + string_list(expected) + "; read " + string_list(actual); + } + return check_map_anchors(loaded); +} + +class DataTest : public UnitTest{ +public: + explicit DataTest(Case test) : UnitTest("PokemonBDSP::StoryData - " + std::string(test.input.name)), m_test(test){} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + JsonValue input = plan(); + if (m_test.input.mutate){ + m_test.input.mutate(input.to_object_throw()); + } + try{ + const StoryCheckpoint loaded = read_authored_checkpoint(input, m_test.input.name); + if (m_test.expectation.rejected){ + return "Expected authored data rejection; read accepted record " + Pokemon::story_checkpoint_json(loaded).dump(-1); + } + const std::string error = check_registration(loaded); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + }catch (const Exception& error){ + return m_test.expectation.rejected ? UnitTestResult(true) : UnitTestResult(error.to_str()); + } + } +private: + Case m_test; +}; + +} // namespace + +void add_tests_AutoStory_StoryData(UnitTestDatabase& database){ + for (const Case& test : CASES){ + database.add(test); + } +} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.h new file mode 100644 index 0000000000..2b81e594e7 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.h @@ -0,0 +1,22 @@ +/* BDSP Authored Checkpoint Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryData_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryData_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Register strict authored-data validation and table-wiring cases. +void add_tests_AutoStory_StoryData(UnitTestDatabase& database); +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 650259e1e5..2a697170b9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -23,6 +23,7 @@ #include #include #include "Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP_AutoStory_StoryData.h" #include "PokemonBDSP_AutoStory_StoryTable.h" namespace PokemonAutomation{ @@ -59,10 +60,6 @@ const char* const JUBILIFE = "JubilifeCity"; const char* const TRAINERS_SCHOOL = "TrainersSchool"; const char* const OREBURGH = "OreburghCity"; const char* const GYM = "OreburghGym"; -// The mine's entrance hall (Diamond's MAP_OREBURGH_MINE_B1F) and the coal -// room below it, Roark's. -const char* const MINE_HALL = "OreburghMineB1F"; -const char* const MINE = "OreburghMine"; const char* const GATE = "OreburghGate"; const char* const ROUTE_203 = "Route203"; const char* const ROUTE_204_SOUTH = "Route204South"; @@ -688,68 +685,6 @@ StoryCheckpoint route_203_to_oreburgh(){ }); } -// 01.03, planned on Oreburgh's map and the coal room's (Diamond's zone -// events narc_0044 and narc_0197): Barry in the Center's door says Roark -// went to the mine (Roark ignored A until then, r101 and r104); down the -// door's column to the mine's warp tiles (44..48, 59); straight down the -// entrance hall to its warps (11..13, 21); in the coal room down to -// Roark, whose scene ends with him gone (Platinum's -// scripts_oreburgh_mine_b2f.s: he smashes the rock east of him and walks -// off east); back up and out; and the Center's nurse, so 01.04 starts on -// the doorstep. The Center's door is the decomp's (47, 20): out of -// Sandgem's and Jubilife's Centers the console stood in their doors' -// columns. The map's doorstep (46, 21) is the Gym's door column plus the -// 20 taps of 01.04 (r217d, r218d), which do not say where the taps began; -// the heal lines up on the lit doorway if north from (47, 21) misses. -// -// The hall is walked on counted taps, not held: it is a cave, and a wild -// battle on a hold toward a fade would read as the fade. Its warp tiles -// are only entered on the step after, which meets no wild Pokemon. The -// warps are Platinum's (pret/pokeplatinum res/field/maps/*/events.json; -// BDSP keeps DP's layout): the city's (44..48, 59) lead to the hall's -// (11, 1), (11, 1), (12, 1), (13, 1), (13, 1), and the hall's (11..13, 1) -// back to the city's (45..47, 59), a column each. Down, from the city's -// (46, 59) we land on the hall's (12, 1); up, the coal room's warp (15, 1) -// lands us on the hall's (12, 21), not (11, 21), so the walk north up -// column 12 comes out on the city's (46, 59), east of the mine's sign -// (45, 56): the walk north to it never stopped there (lab-B 2026-11-08, -// 09:46, 10:39 and 12:03). -// -// Across the coal room to Roark's east corner (20, 28): the north wall above -// it, his rock (19, 28) to its west. A wild battle on a counted tap re-plans -// to the end of the step, and a step that ends in a corner ends that re-plan -// on wall clips. Lab-B 2026-11-08 11:55: the re-plan went only to the end of -// the interrupted leg, the open tile (15, 16); its last leg, south 5 across -// the open room, overshot a row, and the taps after ran under Roark's rocks. -std::vector legs_to_roarks_corner(){ - return { - {.direction = EAST, .tiles = 1}, - {.direction = SOUTH, .tiles = 2}, - {.direction = WEST, .tiles = 1}, - {.direction = SOUTH, .tiles = 5}, - {.direction = EAST, .tiles = 14}, - {.direction = SOUTH, .tiles = 10}, - {.direction = WEST, .tiles = 2}, - {.direction = SOUTH, .tiles = 2}, - {.direction = WEST, .tiles = 7}, - }; -} - -std::vector legs_out_of_coal_room(){ - return { - {.direction = EAST, .tiles = 9}, - {.direction = NORTH, .tiles = 3}, - {.direction = EAST, .tiles = 2}, - {.direction = NORTH, .tiles = 10}, - {.direction = WEST, .tiles = 14}, - {.direction = NORTH, .tiles = 5}, - {.direction = EAST, .tiles = 1}, - {.direction = NORTH, .tiles = 2}, - {.direction = WEST, .tiles = 1}, - {.direction = NORTH, .tiles = 7}, - }; -} - // 01.02b: the welcome leaves the party as Route 203 left it (2026-11-07 runs: // the lead paralysed, its water move out of PP, and every reload of 01.03 // replayed that). Barry's lines first, as before the split (he blocks the @@ -766,45 +701,9 @@ StoryCheckpoint oreburgh_center_heal(){ }); } +// The authored file carries the mine route and its save-card/failure policy. StoryCheckpoint oreburgh_mine_to_roark(){ - const Pose below_roark = next_to(MINE, "roark", SOUTH, NORTH); - return row("01.03", "Oreburgh Mine to Roark", out_of_oreburgh_center(), { - route("above_the_mine", at(OREBURGH, 46, 57, SOUTH), "down the door's column to two above the mine's warp tiles (44..48, 59)", "town"), - step_into("into_the_mine", SOUTH, "the warp tile (46, 59)", at(MINE_HALL, 12, 1, SOUTH)), - step_into("into_the_coal_room", SOUTH, "down the entrance hall through the cave mouth", at(MINE, 15, 2, SOUTH)), - anchored(to_walls("south_to_the_rock", {{.direction = SOUTH, .tiles = 8}}, "south against the corridor rock (15, 11)"), - at(MINE, 15, 9, SOUTH)), - anchored(legs("to_roarks_corner", legs_to_roarks_corner(), "east around the rock, across the room, down column 29, west to Roark's rock"), - at(MINE, 20, 28, WEST)), - // Counted taps along the open row 29 drifted (lab-B 2026-11-07: south 3 - // moved 2): south stops at the wall under row 29, two tiles from below him. - anchored(to_walls("beside_roarks_rock", {{.direction = SOUTH, .tiles = 1}}, "south against the room's wall"), - at(MINE, 20, 29, SOUTH)), - anchored(legs("below_roark", {{.direction = WEST, .tiles = 2}}, "west 2 to below Roark"), below_roark), - talk("roark", "Roark, north of us between his rocks"), - scene("roark_smashes_the_rock", below_roark, "his lines, Rock Smash on the rock east of him, and he walks off"), - anchored(legs("below_the_coal_rooms_warp", legs_out_of_coal_room(), "east around crate, up column 29, west across row 17, and up corridor to warp doorstep"), - at(MINE, 15, 2, NORTH)), - step_into("up_to_the_hall", NORTH, "the warp tile (15, 1)", at(MINE_HALL, 12, 21, NORTH)), - // Out on the city's (46, 59), the warp tile of the hall's column 12 - // (the decomp's warp: the hall's (12, 1) to the city's (46, 59)), or - // a tile north should the walk go on past the fade. On the console - // (lab-B 2026-11-08 13:50) a tap north and a hold east to the wall - // matched the map only from column 46. - step_into("out_of_the_mine", NORTH, "up the entrance hall and out to the city", - Pokemon::tile_pose(OREBURGH, {TilePos{46, 59}, TilePos{46, 58}}, NORTH)), - // Straight north up column 46 to the wall west of the Center's door, - // (46, 20): 37 tiles from (46, 58), 38 from (46, 59). Oreburgh's - // Hiker wanders (46..48, 25..27) across it, and the walk waits for - // him. The column was the one the console stopped on at 10:39, and - // it keeps off the street east of the mine, where at 13:50 a hold - // east from (48, 57) moved 0 though the map has (49, 57) open, and - // the walk after went astray. - anchored(legs("north_to_the_centers_wall", {{.direction = NORTH, .tiles = 37}}, - "north up column 46 to the wall west of the Center's door", "counted_wall"), at(OREBURGH, 46, 21, NORTH)), - anchored(legs("east_below_the_centers_door", {{.direction = EAST, .tiles = 1}}, "a tap east below the door"), below_oreburghs_center()), - heal("heal_oreburgh", "the nurse; out onto the doorstep, where 01.04 starts", out_of_oreburgh_center()), - }); + return load_authored_checkpoint("bdsp-mine-01.03.plan"); } // Below Rowan's trigger in Jubilife: (47, 8), the east tile under the @@ -956,7 +855,6 @@ const std::map& start_save_cards(){ {"01.01", "Jubilife City"}, {"01.02", "Route 203"}, {"01.02b", "Oreburgh City"}, - {"01.03", "Oreburgh City"}, {"01.04", "Oreburgh City"}, {"01.05", "Oreburgh City"}, {"01.06", "Route 203"}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index b87c43da62..b53a1f0476 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -489,7 +489,7 @@ StepsWalk walk_steps(GridSim& sim, const TableSteps& table){ WalkStepsIO io(sim, route_io); StoryWalkSteps walk(io); walk.begin_attempt("01.03"); - Pokemon::RunState state{.pose = table.start}; + Pokemon::RunState state{.pose = table.start, .flags = {}}; try{ for (const StoryStep& step : table.steps){ const Pokemon::Outcome outcome = step.kind == StoryStepKind::ROUTE ? walk.route(state, step) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index e2eda64d12..af4d5862bb 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -522,7 +522,32 @@ class Test_StorySimulation : public UnitTest{ } // namespace +// Execute the authored mine resource through the actual table and shared engine. +UnitTestResult test_authored_mine(Logger&){ + Simulation sim; + const auto report = sim.run({.from = "01.03", .to = "01.03"}); + if (!report.completed || sim.begun() != std::vector{"01.03"} + || sim.count("save in 01.03") != 1 || sim.count("card for 01.03: Oreburgh City") != 1 + || sim.count("01.03/heal_oreburgh") != 1 || sim.count("01.03/roark") != 1){ + return "Expected the JSON-authored mine checkpoint to save once, talk to Roark, heal and finish:" + joined(sim.trace) + joined(sim.lines); + } + return true; +} + +UnitTestResult test_authored_mine_stops(Logger&){ + Simulation sim; + sim.game.failures["01.03/out_of_the_mine"] = {.failure = "unconfirmed_transition", .times = 3}; + const auto report = sim.run({.from = "01.03", .to = "01.03"}); + if (report.completed || report.reloads != 2 || report.failed_event != "out_of_the_mine" + || sim.count("01.03/heal_oreburgh") != 0){ + return "Expected failed mine transition to exhaust retries before healing:" + joined(sim.trace) + joined(sim.lines); + } + return true; +} + const AutoStoryStorySimulationCase AUTO_STORY_STORY_SIMULATION_CASES[] = { + {.input = {.name = "01.03 authored mine executes through the real table", .body = test_authored_mine}, .expectation = {}}, + {.input = {.name = "01.03 unconfirmed mine exit stops before healing", .body = test_authored_mine_stops}, .expectation = {}}, { .input = {"00.00 to Floaroma, in order, each row saved first, English and Japanese", test_whole_table}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/README.md b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/README.md new file mode 100644 index 0000000000..cf77edffe0 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/README.md @@ -0,0 +1,16 @@ +# BDSP authored checkpoint pilot + +`bdsp-mine-01.03.plan.json` is the authoritative definition of the mine/Roark checkpoint. `oreburgh_mine_to_roark()` loads it into the existing story table. Edit this file here when changing the route; PokemonSimulation consumes an explicitly pinned Arduino revision for independent analysis. Its checked-in pilot plan is a frozen regression snapshot, not a second authoring source. + +The shared `pokesim-authored-checkpoint/1` envelope contains `checkpoint.id`, `title`, `start`, `events` in that order. BDSP validates `execution.on_failure` and `execution.saves_in`. The common envelope and resource lookup live in `Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.*`. Bookkeeping defaults and game executors are unchanged. + +## Validation and iteration + +1. Native registered tests run the actual JSON-backed table through the existing engine/fake game, including retry exhaustion before healing. Data tests check parsing, table wiring, event IDs/order, policy/card values, and map-derived Center/Roark anchors. The table-wiring comparison is not an independent check against the removed C++ authoring list. +2. Linux CI pins a simulator revision reachable from its main branch and replays **this checkout's JSON** against nine independent scenario expectations. There is no byte-equality requirement against a second plan. A route change may still require revising a scenario expectation when its expected behavior intentionally changes; such failures are meaningful regression feedback, not a requirement to mirror JSON or repin simulator code for every edit. + +A lab route edit therefore touches the Arduino plan and applicable tests/evidence. The next build re-embeds it automatically. CMake rejects malformed JSON syntax before launching the app; native tests perform full reader/policy validation. Run tests before deploying: CMake's syntax preflight alone cannot validate all semantics. The shared formatter writes authored JSON; Git normalization rules are unchanged. Whitespace and line-ending changes do not affect replay results. C++ retains the repository CRLF convention. + +Coordinates remain literal data tied to the pinned map. The map-anchor test catches drift in the Center exit and Roark approach; it does not validate every tile or replace map review. See [the checkpoint evidence](bdsp-mine-01.03.md) for the warp columns, counted hall movement, wall choices and unresolved observations. + +The native fake uses declared scene/door fallbacks and is not a detector/timing oracle. Python uses scripted transition/dialogue/scene/heal evidence and NPC-clearance windows. Missing warp links, native planner-cost parity, queued movement and live recovery remain gaps. Python's diagnostic policy is stop/no-save; the native program retains its start-save/reload policy. No map correction, console, profile or save is part of this authoring migration. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-mine-01.03.md b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-mine-01.03.md new file mode 100644 index 0000000000..9237f7a965 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-mine-01.03.md @@ -0,0 +1,41 @@ +# Mine/Roark checkpoint: route evidence + +This sidecar preserves the reasoning that previously accompanied the C++ row. The JSON defines current actions; these observations explain why they were chosen. They are historical evidence, not new console verification. Entry assumes the preceding Barry conversation and Center heal have completed. + +## Entry and Center alignment + +The Center door is `(47,20)`, so its approach is `(47,21)` facing north. The published `pokemon_center_doorstep` is `(46,21)`: a route there hit the wall west of the door and healing found no door (lab-B, 2026-11-07 20:18). Both `(47,21)` and `(46,21)` facing south remain exit alternatives. Earlier Gym alignment runs r217d/r218d inferred column 46 from twenty west taps; they did not independently establish where those taps began. + +`above_the_mine` goes to `(46,57)` facing south, two tiles short of the warp row so an open walk cannot slide onto it (01.05, lab-B 2026-11-08). The city's five warp tiles `(44..48,59)` map into the hall at `(11,1),(11,1),(12,1),(13,1),(13,1)`. Thus column 46 enters B1F at `(12,1)`. The mine hall is Diamond's B1F; the coal room below is the room with Roark. Diamond zone-event sources were narc_0044/narc_0197; Platinum's event files provide the corresponding warp layout, used as evidence for BDSP's retained DP layout. + +## Into the coal room + +`into_the_mine` and `into_the_coal_room` cross the cave mouths. Hall movement uses counted taps rather than an open hold toward a fade: a wild battle on a hold can be mistaken for the transition. Warp entry itself is expected on the subsequent step. These are executor assumptions that still need detector/interruption coverage. + +The hall's coal-room mouth is `(11..13,21)`; column 12 enters the coal room at `(15,2)`. `south_to_the_rock` clips the corridor rock before the grouped inbound legs. The script's anchor is `(15,9)` facing south; the rock was described at `(15,11)`. + +## Roark approach and talk + +`to_roarks_corner` groups all nine inbound legs through `(20,28)` facing west, rather than ending recovery at an open intermediate tile. Lab-B, 2026-11-08 11:55: recovery replanned only to `(15,16)`, a subsequent south-five leg overshot a row, and later taps ran under Roark's rocks. Grouping through a corner allows a replanned path to finish with wall clips. The offline interrupted-leg case deliberately stops with uncertainty; it does not prove live recovery/rejoin. + +`beside_roarks_rock` clips the room's south wall to `(20,29)`, then `below_roark` moves west two to `(18,29)` facing north. Lab-B, 2026-11-07: an open counted south-three leg moved only two, motivating the wall anchor. Roark's map point is `(18,28)`; native tests check the authored below-Roark pose against that map point. + +`roark` initiates the conversation. Barry's earlier message that Roark went to the mine is a prerequisite: Roark ignored A without it in r101/r104. `roark_smashes_the_rock` represents the lines, Rock Smash east of him, and his departure east, consistent with Platinum's mine B2F script. The declared return pose is an executor fallback, not an observed receipt proving the scene completed. + +## Back through the hall + +`below_the_coal_rooms_warp` contains the ten outbound legs: east around the crate, north along column 29, west across row 17, then up the corridor to `(15,2)` facing north. Entering `(15,1)` returns to the hall at `(12,21)`, not `(11,21)`. + +`up_to_the_hall` and `out_of_the_mine` continue up column 12. The hall's `(12,1)` exit leads to city `(46,59)`. The city belief also permits `(46,58)` if movement continued past the fade. Lab-B, 2026-11-08 09:46, 10:39 and 12:03: the exit was east of the sign `(45,56)` and northward movement did not stop there. At 13:50, a north tap and east wall hold matched the map only from column 46. + +## Return to the nurse + +`north_to_the_centers_wall` clips the wall at `(46,20)` from either exit tile: 37 tiles from row 58 or 38 from row 59. The Hiker wanders through columns 46..48 and rows 25..27; the live walker must wait or recover safely, and the offline model uses an explicit synthetic clearance window. + +This column avoids the street east of the mine. At 13:50, an east hold from `(48,57)` moved zero although the map showed `(49,57)` open; later movement went astray. That discrepancy remains unresolved and is not grounds to change terrain silently. + +`east_below_the_centers_door` moves one tile east to `(47,21)` facing north. `heal_oreburgh` enters, heals and exits to the two-tile doorstep belief. The next Gym checkpoint starts there. The checkpoint keeps save-at-start/reload-and-retry guarded by the Oreburgh City save card. + +## Updating this route + +Edit the authoritative JSON, update relevant native/scenario expectations, and preserve new run evidence here. A changed map pin requires anchor review. A claimed transition or recovery fix needs an independent observation/regression case; do not turn `declared_after` into proof of success. The initial migration was checked against the pre-migration row and the reported successful lab-B sequence of 2026-11-08 14:17–14:23; later changes must record their own evidence. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-mine-01.03.plan.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-mine-01.03.plan.json new file mode 100644 index 0000000000..1a5afa9d9b --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-mine-01.03.plan.json @@ -0,0 +1,197 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "bdsp", + "checkpoint": { + "id": "01.03", + "title": "Oreburgh Mine to Roark", + "start": { + "map": "OreburghCity", + "certainty": "set", + "where": {"kind": "tiles", "tiles": [[47, 21], [46, 21]], "facing": "south"} + }, + "events": [ + { + "id": "above_the_mine", + "kind": "route", + "target": { + "map": "OreburghCity", + "certainty": "tile", + "where": {"kind": "tiles", "tiles": [[46, 57]], "facing": "south"} + }, + "variant": "town", + "why": "down the door's column to two above the mine's warp tiles (44..48, 59)" + }, + { + "id": "into_the_mine", + "kind": "step", + "direction": "south", + "declared_after": { + "map": "OreburghMineB1F", + "certainty": "tile", + "where": {"kind": "tiles", "tiles": [[12, 1]], "facing": "south"} + }, + "why": "the warp tile (46, 59)" + }, + { + "id": "into_the_coal_room", + "kind": "step", + "direction": "south", + "declared_after": { + "map": "OreburghMine", + "certainty": "tile", + "where": {"kind": "tiles", "tiles": [[15, 2]], "facing": "south"} + }, + "why": "down the entrance hall through the cave mouth" + }, + { + "id": "south_to_the_rock", + "kind": "legs", + "legs": [{"direction": "south", "tiles": 8}], + "declared_after": { + "map": "OreburghMine", + "certainty": "tile", + "where": {"kind": "tiles", "tiles": [[15, 9]], "facing": "south"} + }, + "why": "south against the corridor rock (15, 11)", + "variant": "to_wall" + }, + { + "id": "to_roarks_corner", + "kind": "legs", + "legs": [ + {"direction": "east", "tiles": 1}, + {"direction": "south", "tiles": 2}, + {"direction": "west", "tiles": 1}, + {"direction": "south", "tiles": 5}, + {"direction": "east", "tiles": 14}, + {"direction": "south", "tiles": 10}, + {"direction": "west", "tiles": 2}, + {"direction": "south", "tiles": 2}, + {"direction": "west", "tiles": 7} + ], + "declared_after": { + "map": "OreburghMine", + "certainty": "tile", + "where": {"kind": "tiles", "tiles": [[20, 28]], "facing": "west"} + }, + "why": "east around the rock, across the room, down column 29, west to Roark's rock" + }, + { + "id": "beside_roarks_rock", + "kind": "legs", + "legs": [{"direction": "south", "tiles": 1}], + "declared_after": { + "map": "OreburghMine", + "certainty": "tile", + "where": {"kind": "tiles", "tiles": [[20, 29]], "facing": "south"} + }, + "why": "south against the room's wall", + "variant": "to_wall" + }, + { + "id": "below_roark", + "kind": "legs", + "legs": [{"direction": "west", "tiles": 2}], + "declared_after": { + "map": "OreburghMine", + "certainty": "tile", + "where": {"kind": "tiles", "tiles": [[18, 29]], "facing": "north"} + }, + "why": "west 2 to below Roark" + }, + { + "id": "roark", + "kind": "talk", + "why": "Roark, north of us between his rocks" + }, + { + "id": "roark_smashes_the_rock", + "kind": "scene", + "declared_after": { + "map": "OreburghMine", + "certainty": "tile", + "where": {"kind": "tiles", "tiles": [[18, 29]], "facing": "north"} + }, + "why": "his lines, Rock Smash on the rock east of him, and he walks off" + }, + { + "id": "below_the_coal_rooms_warp", + "kind": "legs", + "legs": [ + {"direction": "east", "tiles": 9}, + {"direction": "north", "tiles": 3}, + {"direction": "east", "tiles": 2}, + {"direction": "north", "tiles": 10}, + {"direction": "west", "tiles": 14}, + {"direction": "north", "tiles": 5}, + {"direction": "east", "tiles": 1}, + {"direction": "north", "tiles": 2}, + {"direction": "west", "tiles": 1}, + {"direction": "north", "tiles": 7} + ], + "declared_after": { + "map": "OreburghMine", + "certainty": "tile", + "where": {"kind": "tiles", "tiles": [[15, 2]], "facing": "north"} + }, + "why": "east around crate, up column 29, west across row 17, and up corridor to warp doorstep" + }, + { + "id": "up_to_the_hall", + "kind": "step", + "direction": "north", + "declared_after": { + "map": "OreburghMineB1F", + "certainty": "tile", + "where": {"kind": "tiles", "tiles": [[12, 21]], "facing": "north"} + }, + "why": "the warp tile (15, 1)" + }, + { + "id": "out_of_the_mine", + "kind": "step", + "direction": "north", + "declared_after": { + "map": "OreburghCity", + "certainty": "set", + "where": {"kind": "tiles", "tiles": [[46, 59], [46, 58]], "facing": "north"} + }, + "why": "up the entrance hall and out to the city" + }, + { + "id": "north_to_the_centers_wall", + "kind": "legs", + "legs": [{"direction": "north", "tiles": 37}], + "declared_after": { + "map": "OreburghCity", + "certainty": "tile", + "where": {"kind": "tiles", "tiles": [[46, 21]], "facing": "north"} + }, + "why": "north up column 46 to the wall west of the Center's door", + "variant": "counted_wall" + }, + { + "id": "east_below_the_centers_door", + "kind": "legs", + "legs": [{"direction": "east", "tiles": 1}], + "declared_after": { + "map": "OreburghCity", + "certainty": "tile", + "where": {"kind": "tiles", "tiles": [[47, 21]], "facing": "north"} + }, + "why": "a tap east below the door" + }, + { + "id": "heal_oreburgh", + "kind": "heal", + "declared_after": { + "map": "OreburghCity", + "certainty": "set", + "where": {"kind": "tiles", "tiles": [[47, 21], [46, 21]], "facing": "south"} + }, + "why": "the nurse; out onto the doorstep, where 01.04 starts" + } + ] + }, + "execution": {"on_failure": "reload_and_retry", "saves_in": "Oreburgh City"} +} diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index ce5d08921a..a98758405c 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1575,6 +1575,10 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp From 779ec115345f453370d0b46529a8d266f19a78af Mon Sep 17 00:00:00 2001 From: Di Fan <26423504+dayfine@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:25:37 -0800 Subject: [PATCH 069/166] BDSP AutoStory: 01.11 walks to the field's edge before the old woman (#279) * BDSP AutoStory: a wall leg that never moved waits, then plans from its start On lab-B (2026-11-08 16:50, 01.08 below_the_ravaged_path) the leg "west 2 (to wall)" from Route 204 (13, 2) stopped at once, 0 chunks moved: the youngster who wanders (12, 2) to (14, 2) stood a tile ahead. The wait for the way needed a stop three tiles short of the wall, so he was talked to at once, and the replan from both (12, 2) and (13, 2) found no plan: an uncertain start needs a wall both tiles reach, and no wall is anchored from a tile someone wanders on. A walk to the wall that never moved stopped where it began, so someone stands on the next tile: it now waits for the way on short legs too, and if they stay, the replan starts from the start tile alone with their tile marked. Two Planned route tests replay the run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: red tests for routes along wander zones and short wall legs On lab-B (2026-11-08, 01.08 below_the_ravaged_path) the plan "north 35 (to wall) to (13, 2), west 2 (to wall) to (11, 2)" walked along the row Route 204 South's youngster wanders, (12..14, 2). He stopped the leg west after 1 of 2 tiles; the check at the wall allowed a tile short on legs of two or three tiles, so the route logged arriving at (11, 2) from (13, 2). New tests, red on this commit: - Route planner: a leg may cross a row zone (one tile of it) but not run along it (two tiles, the start among them); no plan when the row is the only way. - Story table: every ROUTE step plans and none runs along a wander zone; 01.08's plan walks at most one tile of (12..14, 2). - Planned route: a 2-tile leg to a wall that ran out of time after 1 tile is a stop short of the wall, not the wall. The two #271 tests that replayed the console's leg along the youngster's row now replay it on a plain room: the planner will no longer plan it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: no route runs along a wander zone; short wall legs walk every tile plan_robust_route() no longer uses a leg that walks two tiles in a row of a zone where someone wanders (the leg's start among them): along a row zone, or through a 2-D one. Crossing a row zone through one tile is still planned at per_wander_tile, with #271's wait if he stands there. With no other way there is no plan; nothing falls back. A leg to a wall of 3 tiles or fewer that runs out of time short of its tiles is now a stop short of the wall (talk, then plan again), and the check at the wall needs every tile on such legs. Plans that change: 01.08 below_the_ravaged_path goes up column 14, then 12, and crosses the youngster's row at (12, 2) only; 00.05b below_the_tv_clown and 01.03 above_the_mine go round their wanderers. The story sim now plans ROUTE steps as walk_route() does (from a wall for a few start tiles, then default costs): from 01.03's two start tiles the search over both ran out of budget on the longer way. The grid sim's wait test crosses a row zone on a plain room, and Segment00Lines' reference line for 00.03 goes along Route 201's row 13, above the Breeder. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: red tests for 01.10's line-5 recovery wall and a battle on line 7 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: recovery takes the cheapest whole walk; 01.10 runs into Floaroma Recovery from a few possible tiles pinned the wall with the fewest held tiles and ignored the way on to the goal: after Taylor's battle on line 5 it held south 12 and walked 12 back where north 13 and 5 south would do. It now plans the way on from every anchor and keeps the cheapest whole walk. 01.10's last line ran an open leg up column 11, which has no wall north; a wild battle on it left no plan. The row now runs north until Floaroma's banner, which ends the same from any tile of the column, and 01.11 starts from the rows the run may stop on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: keep the story table under the length limit; line-7 cases as a table Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: red sim test for 01.11's walk to the old woman lab-B 2026-11-08 18:41: 01.11's 8 taps west, then north, ended below the old man and no one answered the old woman's talk. A grid sim test walks 01.11 to her from each of the nine tiles Floaroma's banner stops us on: the old taps (OldStorySteps) must miss her from x 10 and 12, and the table's walk must end below her from all nine. The westedge batch found the field's edge 3 taps west of the old man, a column west of Floaroma's map. SimGround adds that column beside the map, for this test and for the story sim's 01.11 from now on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: 01.11 walks west to the field's edge, then 4 taps east 8 taps west from where Floaroma's banner stops us (any of x 10..12) did not end below the old woman: on lab-B (2026-11-08 18:41) they ended below the old man. A walk west until the field's edge stops us ends on one column from every arrival; from below the old man the edge is 3 taps west (westedge batch 2026-11-08), so her column is 4 taps east of it. That edge is x = -1, a column west of Floaroma's map. The map is left as it is (a TODO in the table): the field may go on past it, or the old couple may stand a tile east of their map points. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: pin PokemonSimulation's Floaroma couple fix; drop the sim ground (#285) Bump the BDSP map pin to PokemonSimulation 7209388 (#76), which moves Floaroma's old couple a column east: old man (3, 25), old woman (4, 25). 01.11's walk west now stops at the field's edge on the map (x 0), and 4 taps east land on her column, so the sim-only extra column west of the map goes. Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss Co-authored-by: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../PokemonBDSP_AutoStory_StoryTable.cpp | 14 ++++---- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 34 +++++++++++++++++++ .../PokemonBDSP_AutoStory_OldStorySteps.cpp | 8 +++++ .../PokemonBDSP_AutoStory_OldStorySteps.h | 5 +++ devtools/maps/map-resources.lock.json | 4 +-- 5 files changed, 56 insertions(+), 9 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 2a697170b9..2bcc88cb0c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -787,17 +787,17 @@ std::vector to_oreburgh(){ }; } -// 01.11 on Floaroma's map: the old woman (3, 25) and the old man (2, 25) -// west of her stand still above the flower field's bottom row (r251a). -// The walk to her is the one that ran on the console: 8 taps west along -// row 29 (or 27, 28), then north until she stops us (r250a: 3 steps, bumps). +// 01.11: the old woman (4, 25), the old man (3, 25) west of her (r251a; columns from the westedge batch 2026-11-08, +// PokemonSimulation#76). 8 taps west from the banner's x 10..12 ended below him (lab-B 2026-11-08 18:41), so the walk +// clips to the field's west edge (x 0) and taps east to her column. StoryCheckpoint floaromas_old_couple(){ const Pose below_the_old_woman = next_to(FLOAROMA, "old_woman", SOUTH, NORTH); const Pose below_the_old_man = next_to(FLOAROMA, "old_man", SOUTH, NORTH); + const Pose at_the_field_edge = Pokemon::tile_pose(FLOAROMA, {TilePos{0, 27}, TilePos{0, 28}, TilePos{0, 29}}, WEST); return row("01.11", "Floaroma's old couple", into_floaroma(), { - legs("west_along_the_field", {{.direction = WEST, .tiles = 8}}, "8 taps west along the row we stopped on"), - anchored(to_walls("up_to_the_old_woman", {{.direction = NORTH, .tiles = 5}}, "north until she stops us"), - below_the_old_woman), + anchored(to_walls("west_to_the_field_edge", {{.direction = WEST, .tiles = 13}}, "until the field's edge stops us"), at_the_field_edge), + legs("below_her_column", {{.direction = EAST, .tiles = 4}}, "4 taps east to her column (westedge batch 2026-11-08)"), + anchored(to_walls("up_to_the_old_woman", {{.direction = NORTH, .tiles = 5}}, "north until she stops us"), below_the_old_woman), talk("old_woman", "she gives Mew when a Let's Go save is on the console"), scene("old_woman_talks", below_the_old_woman, "her lines"), // He stands above that tile, so talk() turning north only turns. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index b53a1f0476..6901c3c2e5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -22,6 +22,7 @@ #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" #include "PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_OldStorySteps.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" @@ -591,6 +592,35 @@ UnitTestResult test_gate_walk_part_tile_off(Logger&){ return true; } +// lab-B 2026-11-08 18:41: 01.11's 8 taps west, then north, ended below the +// old man, and no one answered the old woman's talk. Floaroma's banner +// stops us on any of (10..12, 27..29): the old taps miss her from x 10 and +// 11; the table's walk west to the field's edge and 4 taps east end below +// her from all nine. +UnitTestResult test_old_couple_from_each_arrival(Logger& logger){ + const std::optional table = table_steps("01.11", "west_to_the_field_edge", "old_woman"); + const StoryWorld* world = story_plan_world("FloaromaTown", "FloaromaTown"); + if (!table || table->steps.empty() || world == nullptr){ + return "01.11 has no walk west to the field's edge, or Floaroma no map."; + } + const TableSteps old_taps{table->start, {old_west_along_the_field(), table->steps.back()}}; + const TilePos below_her = story_to_world(*world, "FloaromaTown", map_point("FloaromaTown", "old_woman").next(Direction::SOUTH)); + for (int x = 10; x <= 12; x++){ + for (int y = 27; y <= 29; y++){ + const TilePos start = story_to_world(*world, "FloaromaTown", {x, y}); + const std::string old_miss = walk_misses(*world, old_taps, start, {{"up_to_the_old_woman", below_her}}, logger); + if (old_miss.empty() != (x == 12)){ + return std::format("The old taps from ({}, {}): {}", x, y, old_miss.empty() ? "ended below her." : old_miss); + } + const std::string miss = walk_misses(*world, *table, start, {{"up_to_the_old_woman", below_her}}, logger); + if (!miss.empty()){ + return "The table's walk " + miss; + } + } + } + return true; +} + UnitTestResult test_wandering_npc_mechanics(Logger& logger){ StoryWorld world = make_world({ "#######", @@ -937,6 +967,10 @@ const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { .input = {"01.05, a part of a tile off, the old open walk west takes the Gate's warp (lab-B, 2026-11-08)", test_gate_walk_part_tile_off}, .expectation = {}, }, + { + .input = {"01.11, the old woman from each tile Floaroma's banner stops us on (lab-B, 2026-11-08)", test_old_couple_from_each_arrival}, + .expectation = {}, + }, }; void add_tests_AutoStory_GridSim(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp index 657513f382..a508c54be5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp @@ -83,6 +83,14 @@ StoryStep old_tap_into_the_gate(){ return step; } +StoryStep old_west_along_the_field(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "west_along_the_field"; + step.legs = {{.direction = Direction::WEST, .tiles = 8}}; + return step; +} + } // namespace PokemonBDSP diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h index 580eb84f32..7c4608e445 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h @@ -46,6 +46,11 @@ Pokemon::StoryStep old_coal_room_crate_cut(); // the tap step began inside the Gate (lab-B 2026-11-08 15:31 to 15:54). Pokemon::StoryStep old_tap_into_the_gate(); +// 01.11's old walk toward the old woman: 8 taps west along the row +// Floaroma's banner stopped us on, from x 10 to 12, so north of it ended +// below the old man (lab-B 2026-11-08 18:41). +Pokemon::StoryStep old_west_along_the_field(); + } // namespace PokemonBDSP diff --git a/devtools/maps/map-resources.lock.json b/devtools/maps/map-resources.lock.json index 08e0421209..1efcb689ef 100644 --- a/devtools/maps/map-resources.lock.json +++ b/devtools/maps/map-resources.lock.json @@ -3,9 +3,9 @@ "repository": "dayfine/PokemonSimulation", "games": { "bdsp": { - "revision": "4de7742a764d27293b4525d6ad2a6fc8a95f3e3a", + "revision": "72093886bc7bc80497aff770d803a753e7e4bca7", "manifest_path": "data/maps/runtime-manifest.json", - "manifest_sha256": "db6894b6e6c49a6ac7b7661d117a3514ebac2241c8c9311d9c101208abab35ad" + "manifest_sha256": "0ce25ea46dc00d91d5d8587c6f00f322490ca35b8d0ad9778588133a9f55d00f" } } } From 352b050b94a534ebcc95dc2a6086df106e55c9da Mon Sep 17 00:00:00 2001 From: Di Fan <26423504+dayfine@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:27:30 -0800 Subject: [PATCH 070/166] BDSP AutoStory: fight a wild battle the game will not let the walker leave (#255) * BDSP AutoStory: escape policy seam and a red test for a trapped wild battle escape_wild_battle() only pressed Run until a timeout; in Oreburgh Mine an Onix's Bind refused nine Runs in 60 s and the walk failed (console B, 2026-11-07). Its decisions now run over a small WildBattleEscapeActions seam (WildBattlePolicy.h) with a console binding and a GridSim fake, so the simulation can script a battle that refuses the escape. The new GridSim case "bound: every Run refused" fails: the policy still only runs. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: fight a wild battle the game will not let the walker leave On console B (2026-11-07) an Onix's Bind in Oreburgh Mine refused nine Runs in a row and escape_wild_battle() gave up with "Exit transition and late main-menu fallback could not confirm escape." The escape policy now counts refused Runs (the battle menu back after Run) and, after `run_refusals` of them (default 3), fights the battle to its end through the existing fight_wild_battle() path instead of pressing Run until the attempts run out. Both the count and the fallback are policy data, so GridSim runs the same decisions with a scripted battle; the wall-leg GridSim test and the policy tests cover escape, fight, and fight turned off. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: wall-leg wild battle sim tests in their own file GridSim_Tests went over the 1000-line limit once the base's new grid tests met this PR's. This PR's wall-leg battle cases move, unchanged, to Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests, one UnitTest per case, and GridSim_Tests is back to the base's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --------- Co-authored-by: Claude Fable 5.1 --- .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 4 + .../PokemonBDSP_AutoStory_WildBattle.cpp | 118 +++++++++----- .../PokemonBDSP_AutoStory_WildBattle.h | 11 +- .../PokemonBDSP_AutoStory_GridSim.cpp | 56 ++++++- .../PokemonBDSP_AutoStory_GridSim.h | 26 ++- ...emonBDSP_AutoStory_WallBattleSim_Tests.cpp | 146 +++++++++++++++++ ...okemonBDSP_AutoStory_WallBattleSim_Tests.h | 27 ++++ ...PokemonBDSP_AutoStory_WildBattlePolicy.cpp | 42 +++++ .../PokemonBDSP_AutoStory_WildBattlePolicy.h | 81 ++++++++++ ...nBDSP_AutoStory_WildBattlePolicy_Tests.cpp | 150 ++++++++++++++++++ ...monBDSP_AutoStory_WildBattlePolicy_Tests.h | 28 ++++ SerialPrograms/cmake/SourceFiles.cmake | 6 + 12 files changed, 653 insertions(+), 42 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy_Tests.h diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index 40be88c76f..ad6bf441b7 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -19,6 +19,8 @@ #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h" +#include "Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy_Tests.h" +#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h" #include "PokemonBDSP_Tests.h" namespace PokemonAutomation{ @@ -38,8 +40,10 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_StoryData(database); add_tests_AutoStory_StoryTable(database); add_tests_AutoStory_Walk(database); + add_tests_AutoStory_WildBattlePolicy(database); add_tests_AutoStory_PlannedRoute(database); add_tests_AutoStory_GridSim(database); + add_tests_AutoStory_WallBattleSim(database); add_tests_AutoStory_RecoveryWalk(database); add_tests_AutoStory_StorySim(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.cpp index 9f8dbf52c2..5994605164 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.cpp @@ -208,39 +208,81 @@ bool mine_select_run(VideoStream& stream, ProControllerContext& context, BattleT return false; } -// Run on the battle menu, until the battle's exit shows or `timeout` -// runs out. Whether the exit was seen. -bool run_until_escaped( - VideoStream& stream, ProControllerContext& context, BattleType battle_type, - std::chrono::seconds timeout, EndBattleWatcher& battle_end -){ - const auto deadline = std::chrono::steady_clock::now() + timeout; - while (std::chrono::steady_clock::now() < deadline){ - pbf_press_button(context, BUTTON_B, 40ms, 200ms); - context.wait_for_all_requests(); - BattleMenuWatcher menu_ready(battle_type, COLOR_YELLOW); - const int ready = wait_until(stream, context, 3s, {{battle_end}, {menu_ready}}); - if (ready == 0){ - return true; - } - if (ready != 1 || !mine_select_run(stream, context, battle_type)){ - continue; +// The escape policy's game steps on the console. The exit watcher lives +// across the attempts: EndBattleWatcher needs black followed by a visible +// screen, which one attempt's waits may split. +class ConsoleWildBattleEscape : public WildBattleEscapeActions{ +public: + ConsoleWildBattleEscape(VideoStream& stream, ProControllerContext& context, BattleType battle_type) + : m_stream(stream) + , m_context(context) + , m_battle_type(battle_type) + {} + + virtual WildRunOutcome run() override; + virtual void fight() override{ + fight_wild_battle(m_stream, m_context, "Mine escape"); + } + virtual void note(const std::string& text) override{ + m_stream.log("[Mine escape] " + text); + } + + // After the policy gave up: whether the exit still shows within `wait`. + bool exit_within(Milliseconds wait){ + return wait_until(m_stream, m_context, wait, {{m_battle_end}}) == 0; + } + +private: + // B, then the exit (0) or the battle menu (1) within three seconds; -1 for neither. + int exit_or_menu(); + + VideoStream& m_stream; + ProControllerContext& m_context; + BattleType m_battle_type; + EndBattleWatcher m_battle_end; +}; + +int ConsoleWildBattleEscape::exit_or_menu(){ + pbf_press_button(m_context, BUTTON_B, 40ms, 200ms); + m_context.wait_for_all_requests(); + BattleMenuWatcher menu_ready(m_battle_type, COLOR_YELLOW); + return wait_until(m_stream, m_context, 3s, {{m_battle_end}, {menu_ready}}); +} + +WildRunOutcome ConsoleWildBattleEscape::run(){ + const int ready = exit_or_menu(); + if (ready == 0){ + return WildRunOutcome::ESCAPED; + } + if (ready != 1 || !mine_select_run(m_stream, m_context, m_battle_type)){ + return WildRunOutcome::UNCERTAIN; + } + m_stream.log("[Mine escape] Run input sent; watching for black-screen exit."); + const int result = run_until(m_stream, + m_context, + [](ProControllerContext& controller){ + pbf_mash_button(controller, BUTTON_ZL, 1000ms); + pbf_mash_button(controller, BUTTON_A, 1000ms); + pbf_mash_button(controller, BUTTON_B, 3000ms); + controller.wait_for_all_requests(); + }, + {m_battle_end}); + if (result == 0){ + return WildRunOutcome::ESCAPED; + } + // No exit after Run: the menu back means the game refused it ("Can't + // escape!": Onix's Bind in Oreburgh Mine, console B 2026-11-07). Its + // text and the foe's turn take a few seconds. + for (size_t look = 0; look < 2; look++){ + const int seen = exit_or_menu(); + if (seen == 0){ + return WildRunOutcome::ESCAPED; } - stream.log("[Mine escape] Run input sent; watching for black-screen exit."); - const int result = run_until(stream, - context, - [](ProControllerContext& controller){ - pbf_mash_button(controller, BUTTON_ZL, 1000ms); - pbf_mash_button(controller, BUTTON_A, 1000ms); - pbf_mash_button(controller, BUTTON_B, 3000ms); - controller.wait_for_all_requests(); - }, - {battle_end}); - if (result == 0){ - return true; + if (seen == 1){ + return WildRunOutcome::TRAPPED; } } - return false; + return WildRunOutcome::UNCERTAIN; } // B until the overworld shows; fails with `failure` after two minutes. @@ -390,13 +432,17 @@ void catch_1_pokemon( void escape_wild_battle(VideoStream& stream, ProControllerContext& context, BattleType battle_type, - std::chrono::seconds timeout){ - EndBattleWatcher battle_end; - bool exit_transition = run_until_escaped(stream, context, battle_type, timeout, battle_end); - if (!exit_transition && wait_until(stream, context, 10s, {{battle_end}}) == 0){ - exit_transition = true; + const WildBattleEscapePolicy& policy){ + ConsoleWildBattleEscape actions(stream, context, battle_type); + WildEscapeResult result = escape_wild_battle(actions, policy); + if (result == WildEscapeResult::FOUGHT){ + // fight_wild_battle() ended on the overworld. + return; + } + if (result == WildEscapeResult::UNCONFIRMED && actions.exit_within(10s)){ + result = WildEscapeResult::ESCAPED; } - if (exit_transition){ + if (result == WildEscapeResult::ESCAPED){ // EndBattleWatcher requires black followed by a visible screen. stream.log("[Mine escape] Black-screen exit transition confirmed.", COLOR_GREEN); pbf_wait(context, 800ms); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.h index 7ca96f2bb7..98a93ffb9b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.h @@ -13,10 +13,10 @@ #ifndef PokemonAutomation_PokemonBDSP_AutoStory_WildBattle_H #define PokemonAutomation_PokemonBDSP_AutoStory_WildBattle_H -#include #include "CommonFramework/Tools/VideoStream.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" #include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -34,13 +34,16 @@ void battle_1_pokemon(VideoStream& stream, ProControllerContext& context); // in the Bag, up to ten throws; ends on the overworld. void catch_1_pokemon(VideoStream& stream, ProControllerContext& context); -// Runs from the wild battle on screen: Run on the battle menu until the -// exit's black screen shows. Fails with a screenshot after `timeout`. +// Leaves the wild battle on screen as `policy` says: Run on the battle menu +// until the exit's black screen shows, or, once the game has refused the +// escape `policy.run_refusals` times (a trapping move), fights it to its end +// with the best move. Fails with a screenshot once the policy gives up and +// the main menu does not prove the overworld either. void escape_wild_battle( VideoStream& stream, ProControllerContext& context, BattleType battle_type = BattleType::STANDARD, - std::chrono::seconds timeout = std::chrono::seconds(60) + const WildBattleEscapePolicy& policy = WildBattleEscapePolicy() ); // escape_wild_battle() for a standard wild battle, as the walker takes it diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp index 909766eb48..38630ad729 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -7,6 +7,7 @@ #include #include #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy.h" #include "PokemonBDSP_AutoStory_GridSim.h" namespace PokemonAutomation{ @@ -380,14 +381,67 @@ WalkStop walk_stop(SimStop stop){ return WalkStop::LIMIT; } +// The escape policy's game steps on a scripted battle. +class SimWildBattleEscape : public WildBattleEscapeActions{ +public: + SimWildBattleEscape(const SimWildBattle& battle, std::vector& notes) + : m_refusals_left(battle.run_refusals) + , m_notes(notes) + {} + virtual WildRunOutcome run() override{ + if (m_refusals_left == 0){ + return WildRunOutcome::ESCAPED; + } + m_refusals_left--; + return WildRunOutcome::TRAPPED; + } + virtual void fight() override{ + m_notes.push_back("[Sim escape] Fought with the best move until the battle ended."); + } + virtual void note(const std::string& text) override{ + m_notes.push_back("[Sim escape] " + text); + } + +private: + size_t m_refusals_left; + std::vector& m_notes; +}; + } // namespace +std::optional GridSimRouteIO::take_wall_encounter(const RouteWallWalk& walk){ + const auto found = std::find_if(m_wall_encounters.begin(), m_wall_encounters.end(), [&](const SimWallEncounter& encounter){ + return encounter.direction == walk.direction && encounter.label == walk.label; + }); + if (found == m_wall_encounters.end()){ + return std::nullopt; + } + SimWallEncounter encounter = *found; + m_wall_encounters.erase(found); + return encounter; +} + +void GridSimRouteIO::escape_scripted_battle(const SimWildBattle& battle, const std::string& label){ + SimWildBattleEscape actions(battle, m_notes); + const WildEscapeResult result = escape_wild_battle(actions, WildBattleEscapePolicy()); + if (result == WildEscapeResult::UNCONFIRMED){ + note(std::format("escape_wild_battle: {}: the Run attempts ran out without the exit.", label), RouteNote::FAILURE); + } + const char* ended = result == WildEscapeResult::FOUGHT ? "fought to its end" : "run from"; + m_notes.push_back(std::format("[Sim] {}: wild battle {}.", label, ended)); +} + WalkResult GridSimRouteIO::walk_to_wall(const RouteWallWalk& walk){ + size_t wild_battles = 0; + if (const auto encounter = take_wall_encounter(walk)){ + escape_scripted_battle(encounter->battle, walk.label); + wild_battles = 1; + } const SimPace pace = walk.options.pace == DpadPace::RUN ? SimPace::RUN : SimPace::WALK; const SimMove move = m_sim.hold(walk.direction, walk.limit, pace); m_notes.push_back(std::format("[Sim] {}: held {} to {} at {}.", walk.label, direction_name(walk.direction), sim_stop_name(move.stop), to_string(m_sim.player().pos))); - return {.stop = walk_stop(move.stop), .walked = move.time, .wild_battles = 0, .moved_chunks = (size_t)(move.distance / SIM_TILE)}; + return {.stop = walk_stop(move.stop), .walked = move.time, .wild_battles = wild_battles, .moved_chunks = (size_t)(move.distance / SIM_TILE)}; } std::optional GridSimRouteIO::take_encounter(Direction direction, size_t tiles, size_t tap, const std::string& label){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h index 0535e3f043..68db3ed247 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h @@ -195,14 +195,33 @@ struct SimWildTap{ WalkOrigin origin = WalkOrigin::CURRENT_LEG; }; +// A scripted wild battle, as the escape policy's game steps see it: how +// many Run presses the game refuses ("Can't escape!": Bind, Wrap) before +// one works. Not a model of the battle itself. +struct SimWildBattle{ + size_t run_refusals = 0; +}; +// A wild battle that interrupts the walk to a wall (walk_to_wall()) with +// this label toward this direction, once; the hold goes on to the wall +// after it, as the console's does. +struct SimWallEncounter{ + std::string label; + Pokemon::Direction direction = Pokemon::Direction::NORTH; + SimWildBattle battle; +}; + // The walker's RouteIO on a GridSim. A failure throws GridSimFailure. class GridSimRouteIO : public RouteIO{ public: // Every line noted goes to `notes`, which must outlive this. - GridSimRouteIO(GridSim& sim, std::vector& notes, std::vector encounters = {}) + GridSimRouteIO( + GridSim& sim, std::vector& notes, + std::vector encounters = {}, std::vector wall_encounters = {} + ) : m_sim(sim) , m_notes(notes) , m_encounters(std::move(encounters)) + , m_wall_encounters(std::move(wall_encounters)) {} virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override; @@ -215,10 +234,15 @@ class GridSimRouteIO : public RouteIO{ private: std::optional take_encounter(Pokemon::Direction direction, size_t tiles, size_t tap, const std::string& label); + std::optional take_wall_encounter(const RouteWallWalk& walk); + // The escape policy on `battle`; notes a FAILURE where the console + // would fail the program. + void escape_scripted_battle(const SimWildBattle& battle, const std::string& label); GridSim& m_sim; std::vector& m_notes; std::vector m_encounters; + std::vector m_wall_encounters; }; // What GridSimRouteIO throws for RouteNote::FAILURE. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp new file mode 100644 index 0000000000..d4bd12f569 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp @@ -0,0 +1,146 @@ +/* BDSP AutoStory Grid Simulation - Wild Battles on Wall Legs Tests + * + * From: https://github.com/PokemonAutomation/ + * + * A wild battle on a leg to a wall, walked by the route walker on the grid + * simulation: however the escape ends the battle, the leg must still end at + * the wall with the battle counted. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_WallBattleSim_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using Pokemon::Direction; +using Pokemon::TilePos; + + +struct WallBattleInput{ + std::string name; + SimWildBattle battle; +}; +struct WallBattleExpectation{ + // How the simulation notes the battle ended. + std::string ended; +}; +struct WallBattleCase{ + WallBattleInput input; + WallBattleExpectation expectation; +}; + +StoryWorld make_world(const std::vector& rows){ + Pokemon::MapData map; + map.name = "Test"; + map.tiles = Pokemon::Grid{(int)rows[0].size(), (int)rows.size(), {}}; + for (const std::string& row : rows){ + for (char glyph : row){ + map.tiles.cells.push_back(*Pokemon::tile_from_glyph(glyph)); + } + } + StoryWorld world; + world.add("Test", map, {0, 0}); + return world; +} + +// The corridor's one leg, east to its end wall, walked with `battle` on +// the way; the walk's notes, or why it did not end at the wall. +struct WallBattleWalk{ + std::vector notes; + std::string error; +}; +WallBattleWalk walk_wall_battle(const std::string& leg, const SimWildBattle& battle){ + StoryWorld world = make_world({ + "########################", + "#......................#", + "########################", + }); + const TilePos start{1, 1}; + const TilePos target{22, 1}; + GridSim sim({.world = &world}, start, Direction::EAST, true); + WallBattleWalk walk; + GridSimRouteIO sim_io(sim, walk.notes, {}, {{.label = leg, .direction = Direction::EAST, .battle = battle}}); + RouteTrainers trainers{{}, [](const std::string&){}}; + try{ + walk_route(sim_io, world, {start}, trainers, { + .goal = [&](const TilePos& pos){ return pos == target; }, + .label = "wall leg battle", + .avoid = {}, + .costs = *story_route_costs("town"), + .speed = MoveSpeed::RUN, + }); + }catch (const GridSimFailure& f){ + walk.error = "failed: " + f.message; + return walk; + } + if (nearest_tile(sim.player().pos) != target){ + walk.error = "ended at " + to_string(sim.player().pos) + ", not at the wall."; + } + return walk; +} + +class Test_WallBattleSim : public UnitTest{ +public: + explicit Test_WallBattleSim(WallBattleCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Grid sim: a wild battle on a wall leg: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string leg = "wall leg battle: " + to_string(TileLeg{.direction = Direction::EAST, .tiles = 21, .ends_at_wall = true}); + const WallBattleWalk walk = walk_wall_battle(leg, m_case.input.battle); + if (!walk.error.empty()){ + return walk.error; + } + const std::string ended = std::format("[Sim] {}: wild battle {}.", leg, m_case.expectation.ended); + if (std::find(walk.notes.begin(), walk.notes.end(), ended) == walk.notes.end()){ + std::string notes; + for (const std::string& line : walk.notes){ + notes += "\n " + line; + } + return std::format("expected the note \"{}\"; the walk noted:{}", ended, notes); + } + return true; + } + +private: + WallBattleCase m_case; +}; + +const WallBattleCase WALL_BATTLE_SIM_CASES[] = { + {.input = {.name = "the first Run works", .battle = {.run_refusals = 0}}, .expectation = {.ended = "run from"}}, + {.input = {.name = "two refusals, then the third Run works", .battle = {.run_refusals = 2}}, .expectation = {.ended = "run from"}}, + // console B, BDSP 01.03 run 2026-11-07: Onix's Bind in Oreburgh Mine + // refused nine Runs in 60 s and escape_wild_battle() gave up. + {.input = {.name = "bound: every Run refused", .battle = {.run_refusals = 20}}, .expectation = {.ended = "fought to its end"}}, +}; + +} // namespace + + +void add_tests_AutoStory_WallBattleSim(UnitTestDatabase& database){ + for (const WallBattleCase& item : WALL_BATTLE_SIM_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h new file mode 100644 index 0000000000..0833c3040a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h @@ -0,0 +1,27 @@ +/* BDSP AutoStory Grid Simulation - Wild Battles on Wall Legs Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_WallBattleSim_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_WallBattleSim_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// A wild battle on a leg to a wall, on the grid simulation: run from, or +// fought when the game refuses the escape, the leg still ends at the wall. +void add_tests_AutoStory_WallBattleSim(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy.cpp new file mode 100644 index 0000000000..26a20e6fd4 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy.cpp @@ -0,0 +1,42 @@ +/* BDSP AutoStory - Wild battle escape policy + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonBDSP_AutoStory_WildBattlePolicy.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +WildEscapeResult escape_wild_battle(WildBattleEscapeActions& actions, const WildBattleEscapePolicy& policy){ + size_t refusals = 0; + for (size_t attempt = 1; attempt <= policy.attempts; attempt++){ + actions.note(std::format("Run attempt {}/{}.", attempt, policy.attempts)); + switch (actions.run()){ + case WildRunOutcome::ESCAPED: + return WildEscapeResult::ESCAPED; + case WildRunOutcome::TRAPPED: + refusals++; + actions.note(std::format("The game refused the escape ({} so far).", refusals)); + if (refusals >= policy.run_refusals && policy.fallback == TrappedFallback::FIGHT){ + actions.note("Trapped: fighting the battle to its end instead."); + actions.fight(); + return WildEscapeResult::FOUGHT; + } + break; + case WildRunOutcome::UNCERTAIN: + break; + } + } + return WildEscapeResult::UNCONFIRMED; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy.h new file mode 100644 index 0000000000..9c0fb3ff12 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy.h @@ -0,0 +1,81 @@ +/* BDSP AutoStory - Wild battle escape policy + * + * From: https://github.com/PokemonAutomation/ + * + * How a wild battle that interrupts a walk is left, as decisions over the + * game steps the console or the simulation supplies, so the same policy + * runs on the Switch and in GridSim tests. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_WildBattlePolicy_H +#define PokemonAutomation_PokemonBDSP_AutoStory_WildBattlePolicy_H + +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// What one Run on the battle menu came to. +enum class WildRunOutcome{ + ESCAPED, // the battle's exit transition showed + TRAPPED, // the battle menu came back: the game refused the escape + UNCERTAIN, // neither showed within the wait: text still scrolling, cursor unread +}; + +// The game steps escape_wild_battle() takes, injected so its decisions run +// in tests without a Switch: the console presses the buttons and watches +// the screen; the simulation scripts the outcomes. +class WildBattleEscapeActions{ +public: + virtual ~WildBattleEscapeActions() = default; + + // On the battle menu: Run, then watch for the exit or the menu again. + virtual WildRunOutcome run() = 0; + + // On the battle menu after a refused Run: fight with the best move until + // the battle ends, on the overworld when it returns. + virtual void fight() = 0; + + // A line of the escape's log. + virtual void note(const std::string& text) = 0; +}; + +// What to do once the game has refused the escape `run_refusals` times. +enum class TrappedFallback{ + GIVE_UP, // keep pressing Run until the attempts run out + FIGHT, // fight the battle to its end instead +}; + +// How a wild battle is left: data, so the simulation runs the console's +// policy, and a later shared policy can carry it. +struct WildBattleEscapePolicy{ + // run() calls in all before the escape is given up as unconfirmed. + size_t attempts = 12; + // Refused Runs (the menu back each time) before `fallback` applies: a + // trapping move such as Bind refuses every one of them. + size_t run_refusals = 3; + TrappedFallback fallback = TrappedFallback::FIGHT; +}; + +// How escape_wild_battle() ended. +enum class WildEscapeResult{ + ESCAPED, + FOUGHT, // the game kept refusing the escape; the battle was fought to its end + UNCONFIRMED, // the attempts ran out without the exit +}; + +// The decisions of escape_wild_battle(): Run on the battle menu until the +// exit shows, within `policy.attempts` tries; after `policy.run_refusals` +// refused Runs, `policy.fallback`. +WildEscapeResult escape_wild_battle(WildBattleEscapeActions& actions, const WildBattleEscapePolicy& policy); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy_Tests.cpp new file mode 100644 index 0000000000..1dc864e70b --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy_Tests.cpp @@ -0,0 +1,150 @@ +/* BDSP AutoStory - Wild battle escape policy tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonBDSP_AutoStory_WildBattlePolicy.h" +#include "PokemonBDSP_AutoStory_WildBattlePolicy_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +// Scripted game steps: each run() returns the next outcome, and the last +// one again once they run out. +class ScriptedEscapeActions : public WildBattleEscapeActions{ +public: + explicit ScriptedEscapeActions(std::vector outcomes) + : m_outcomes(std::move(outcomes)) + {} + virtual WildRunOutcome run() override{ + const WildRunOutcome outcome = m_outcomes[std::min(m_runs, m_outcomes.size() - 1)]; + m_runs++; + return outcome; + } + virtual void fight() override{ + m_fights++; + } + virtual void note(const std::string&) override{} + + size_t runs() const{ + return m_runs; + } + size_t fights() const{ + return m_fights; + } + +private: + std::vector m_outcomes; + size_t m_runs = 0; + size_t m_fights = 0; +}; + +const char* result_name(WildEscapeResult result){ + switch (result){ + case WildEscapeResult::ESCAPED: + return "ESCAPED"; + case WildEscapeResult::FOUGHT: + return "FOUGHT"; + case WildEscapeResult::UNCONFIRMED: + return "UNCONFIRMED"; + } + return "?"; +} + +struct EscapePolicyInput{ + std::string name; + std::vector outcomes; + WildBattleEscapePolicy policy = {}; +}; +struct EscapePolicyExpectation{ + WildEscapeResult result = WildEscapeResult::ESCAPED; + size_t runs = 0; + size_t fights = 0; +}; +struct EscapePolicyCase{ + EscapePolicyInput input; + EscapePolicyExpectation expectation; +}; + +class Test_WildBattlePolicy : public UnitTest{ +public: + explicit Test_WildBattlePolicy(EscapePolicyCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Wild battle escape policy: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + ScriptedEscapeActions actions(m_case.input.outcomes); + const WildEscapeResult result = escape_wild_battle(actions, m_case.input.policy); + const EscapePolicyExpectation& expected = m_case.expectation; + if (result != expected.result || actions.runs() != expected.runs || actions.fights() != expected.fights){ + return std::format("expected {} after {} Run presses and {} fights, got {} after {} and {}.", + result_name(expected.result), expected.runs, expected.fights, + result_name(result), actions.runs(), actions.fights()); + } + return true; + } + +private: + EscapePolicyCase m_case; +}; + +constexpr WildRunOutcome ESCAPED = WildRunOutcome::ESCAPED; +constexpr WildRunOutcome TRAPPED = WildRunOutcome::TRAPPED; +constexpr WildRunOutcome UNCERTAIN = WildRunOutcome::UNCERTAIN; + +const EscapePolicyCase WILD_BATTLE_POLICY_CASES[] = { + { + .input = {.name = "the first Run works", .outcomes = {ESCAPED}}, + .expectation = {.result = WildEscapeResult::ESCAPED, .runs = 1}, + }, + { + .input = {.name = "text still scrolling twice, then away", .outcomes = {UNCERTAIN, UNCERTAIN, ESCAPED}}, + .expectation = {.result = WildEscapeResult::ESCAPED, .runs = 3}, + }, + { + .input = {.name = "two refusals, then the third Run works", .outcomes = {TRAPPED, TRAPPED, ESCAPED}}, + .expectation = {.result = WildEscapeResult::ESCAPED, .runs = 3}, + }, + { + .input = {.name = "never a menu or an exit: the attempts run out", .outcomes = {UNCERTAIN}, .policy = {.attempts = 5}}, + .expectation = {.result = WildEscapeResult::UNCONFIRMED, .runs = 5}, + }, + // Onix's Bind in Oreburgh Mine, console B 2026-11-07: nine Runs refused. + { + .input = {.name = "bound: every Run refused, so the battle is fought", .outcomes = {TRAPPED}}, + .expectation = {.result = WildEscapeResult::FOUGHT, .runs = 3, .fights = 1}, + }, + { + .input = {.name = "refusals between scrolling text count up to the fight", .outcomes = {TRAPPED, UNCERTAIN, TRAPPED, UNCERTAIN, TRAPPED}}, + .expectation = {.result = WildEscapeResult::FOUGHT, .runs = 5, .fights = 1}, + }, + { + .input = {.name = "bound with the fight turned off: the attempts run out", .outcomes = {TRAPPED}, .policy = {.attempts = 6, .fallback = TrappedFallback::GIVE_UP}}, + .expectation = {.result = WildEscapeResult::UNCONFIRMED, .runs = 6}, + }, +}; + +} // namespace + + +void add_tests_AutoStory_WildBattlePolicy(UnitTestDatabase& database){ + for (const EscapePolicyCase& item : WILD_BATTLE_POLICY_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy_Tests.h new file mode 100644 index 0000000000..3082f5343d --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy_Tests.h @@ -0,0 +1,28 @@ +/* BDSP AutoStory - Wild battle escape policy tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_WildBattlePolicy_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_WildBattlePolicy_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// The escape policy's decisions (PokemonBDSP_AutoStory_WildBattlePolicy.h) +// on scripted Run outcomes: when it escapes, when it fights a battle the +// game will not let it leave, and when it gives up. +void add_tests_AutoStory_WildBattlePolicy(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index a98758405c..1e5e2686ad 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1583,6 +1583,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp @@ -1597,6 +1599,10 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy.cpp + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy.h + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy_Tests.h Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.cpp Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.h Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.cpp From 6dc9f89ffeee7f45ca6473a4f3822fcecf7f26bc Mon Sep 17 00:00:00 2001 From: Di Fan <26423504+dayfine@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:36:34 -0800 Subject: [PATCH 071/166] BDSP AutoStory: route-plan golden + console-failure sim cases (#281) (#270) * BDSP AutoStory: no route ends beside a warp walking toward it 01.05's open walk west to (2, 13), beside the Oreburgh Gate's mouth, slid onto the warp (lab-B 2026-11-08, four runs). A table test plans every ROUTE step as the walker does and fails on an open leg that may end on the tile before a door it walks toward. It flagged 01.05's old by_the_gate and four more: 00.03 above_the_door_again (now counted legs from the west), 01.02 by_the_east_mouth and 01.05 through_the_gate (two tiles short of the Gate's mouths, the taps go the rest), and 01.03 above_the_mine (two rows above the warp row, the door run goes on). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: the story sim's old steps in their own file Moved unchanged out of StorySim_Tests.cpp, which is at the 1000-line limit: r75's and r81's old cave exits and the old mine steps. The next commit adds 01.05's old tap into the Oreburgh Gate beside them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: a dim cave floor is not a tap step's fade On lab-B (2026-11-08 15:31 to 15:54) 01.05's walk slid into the Oreburgh Gate, and its tap step read the Gate's floor (about 46) as the fade and waited 8 s for a banner already gone. A look after a tap is the fade only when black (< 25) or a drop to dark from the look before the tap (tap_faded()). A banner before the first tap means the walk before took us through: the step ends with no tap. A tap step taps at most two past the door its map has ahead, so one begun through the warp with its banner gone fails a few tiles in, not across the Gate. Tests: tap_faded() on the Gate's floor and real fades; the story sim's 01.05 tap step begun through the Gate's mouth, banner up and gone (red before: 24 taps across the Gate); GridSim's part-tile offset taking the warp on the old open walk west. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: mark the tap step's fade and through-already checks as stopgaps Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: dump every story ROUTE step's planned legs to a golden file Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: the story's route plans golden file Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: a wall leg that never moved waits, then plans from its start On lab-B (2026-11-08 16:50, 01.08 below_the_ravaged_path) the leg "west 2 (to wall)" from Route 204 (13, 2) stopped at once, 0 chunks moved: the youngster who wanders (12, 2) to (14, 2) stood a tile ahead. The wait for the way needed a stop three tiles short of the wall, so he was talked to at once, and the replan from both (12, 2) and (13, 2) found no plan: an uncertain start needs a wall both tiles reach, and no wall is anchored from a tile someone wanders on. A walk to the wall that never moved stopped where it began, so someone stands on the next tile: it now waits for the way on short legs too, and if they stay, the replan starts from the start tile alone with their tile marked. Two Planned route tests replay the run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: red tests for routes along wander zones and short wall legs On lab-B (2026-11-08, 01.08 below_the_ravaged_path) the plan "north 35 (to wall) to (13, 2), west 2 (to wall) to (11, 2)" walked along the row Route 204 South's youngster wanders, (12..14, 2). He stopped the leg west after 1 of 2 tiles; the check at the wall allowed a tile short on legs of two or three tiles, so the route logged arriving at (11, 2) from (13, 2). New tests, red on this commit: - Route planner: a leg may cross a row zone (one tile of it) but not run along it (two tiles, the start among them); no plan when the row is the only way. - Story table: every ROUTE step plans and none runs along a wander zone; 01.08's plan walks at most one tile of (12..14, 2). - Planned route: a 2-tile leg to a wall that ran out of time after 1 tile is a stop short of the wall, not the wall. The two #271 tests that replayed the console's leg along the youngster's row now replay it on a plain room: the planner will no longer plan it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: no route runs along a wander zone; short wall legs walk every tile plan_robust_route() no longer uses a leg that walks two tiles in a row of a zone where someone wanders (the leg's start among them): along a row zone, or through a 2-D one. Crossing a row zone through one tile is still planned at per_wander_tile, with #271's wait if he stands there. With no other way there is no plan; nothing falls back. A leg to a wall of 3 tiles or fewer that runs out of time short of its tiles is now a stop short of the wall (talk, then plan again), and the check at the wall needs every tile on such legs. Plans that change: 01.08 below_the_ravaged_path goes up column 14, then 12, and crosses the youngster's row at (12, 2) only; 00.05b below_the_tv_clown and 01.03 above_the_mine go round their wanderers. The story sim now plans ROUTE steps as walk_route() does (from a wall for a few start tiles, then default costs): from 01.03's two start tiles the search over both ran out of budget on the longer way. The grid sim's wait test crosses a row zone on a plain room, and Segment00Lines' reference line for 00.03 goes along Route 201's row 13, above the Breeder. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: red tests for 01.10's line-5 recovery wall and a battle on line 7 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: recovery takes the cheapest whole walk; 01.10 runs into Floaroma Recovery from a few possible tiles pinned the wall with the fewest held tiles and ignored the way on to the goal: after Taylor's battle on line 5 it held south 12 and walked 12 back where north 13 and 5 south would do. It now plans the way on from every anchor and keeps the cheapest whole walk. 01.10's last line ran an open leg up column 11, which has no wall north; a wild battle on it left no plan. The row now runs north until Floaroma's banner, which ends the same from any tile of the column, and 01.11 starts from the rows the run may stop on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: keep the story table under the length limit; line-7 cases as a table Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: red sim test for 01.11's walk to the old woman lab-B 2026-11-08 18:41: 01.11's 8 taps west, then north, ended below the old man and no one answered the old woman's talk. A grid sim test walks 01.11 to her from each of the nine tiles Floaroma's banner stops us on: the old taps (OldStorySteps) must miss her from x 10 and 12, and the table's walk must end below her from all nine. The westedge batch found the field's edge 3 taps west of the old man, a column west of Floaroma's map. SimGround adds that column beside the map, for this test and for the story sim's 01.11 from now on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: 01.11 walks west to the field's edge, then 4 taps east 8 taps west from where Floaroma's banner stops us (any of x 10..12) did not end below the old woman: on lab-B (2026-11-08 18:41) they ended below the old man. A walk west until the field's edge stops us ends on one column from every arrival; from below the old man the edge is 3 taps west (westedge batch 2026-11-08), so her column is 4 taps east of it. That edge is x = -1, a column west of Floaroma's map. The map is left as it is (a TODO in the table): the field may go on past it, or the old couple may stand a tile east of their map points. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: regenerate the route plans golden after #277, #278 and #279 Rewritten with PA_UPDATE_ROUTE_PLANS=1 on the merged tree: the recovery goal (#278) shortens several localizations, the wander-zone costs (#277) reroute 00.05b and 01.08, and 01.10's line 7 and into_floaroma are no longer ROUTE steps (#279). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: console failure cases on the story sim (known failing until fixed) (#281) * BDSP AutoStory: move the story sim's executor out of its tests SimStoryStepIO, SimExecutor and the run helpers move unchanged from StorySim_Tests.cpp to Simulation/PokemonBDSP_AutoStory_StorySim.{h,cpp}, so other test files can run rows on the same simulation. The header qualifies Pokemon:: names; the helpers that were file-local stay in an anonymous namespace. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: console failure cases on the story sim, known failing until fixed Sim knobs (SimWorldKnobs, all off unless a case sets them): - slides: an open leg's taps run on; onto a warp the walk sees the fade as it looks to its watchers (black: TRANSITION, dim: nothing, white: a wild battle), and the far map's banner is up or gone for the next step; - floor and fade brightness per map, judged by the program's tap_faded(); - wanderers: everyone with a wander box on the maps walks it, seeded; - late first lines for a talk. SimFailureCases_Tests runs one case per console failure. Those the program fails today are on KNOWN_FAILING with the change that is to fix them; their tests pass while they still fail and fail once they pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --------- Co-authored-by: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 2 + .../AutoStory/Data/route_plans.golden.txt | 447 ++++++++++++ ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 272 +++++++- ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 275 ++++++++ ...emonBDSP_AutoStory_SimFailureCases_Tests.h | 27 + .../PokemonBDSP_AutoStory_StorySim.cpp | 591 ++++++++++++++++ .../PokemonBDSP_AutoStory_StorySim.h | 393 +++++++++++ .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 656 +----------------- SerialPrograms/cmake/SourceFiles.cmake | 4 + 9 files changed, 1982 insertions(+), 685 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index ad6bf441b7..f51fe909fb 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -7,6 +7,7 @@ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h" +#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h" @@ -46,6 +47,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_WallBattleSim(database); add_tests_AutoStory_RecoveryWalk(database); add_tests_AutoStory_StorySim(database); + add_tests_AutoStory_SimFailureCases(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt new file mode 100644 index 0000000000..41d46a087a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt @@ -0,0 +1,447 @@ +BDSP AutoStory: the legs each ROUTE step of the story table plans. +Planned as the console's RouteWalker plans them: plan_recovered_route() on +story_plan_world(), from the tiles the row's steps before it leave the +player on, with the step's costs, then the default costs if those find none. +Written by the StoryTable test "every ROUTE step plans as +Data/route_plans.golden.txt says". After a planner or table change, run +that test with PA_UPDATE_ROUTE_PLANS=1 to rewrite this file +(PA_ROUTE_PLANS_GOLDEN= reads or writes another copy), and review +its diff. +turns: direction changes between legs. open: legs that stop in the open +(tapped, not held to a wall). localization: the wall holds at the start +that only bring several start tiles to one (plan_recovered_route()'s +anchor); 0 from one start tile. + +== 00.01 below_the_flute (costs: route) + from: PlayerHouse2F (4, 6) facing north (tile) + target: PlayerHouse2F (7, 5) facing north (tile) + start candidates: PlayerHouse2F (4, 6) + 1. north 1 (to wall) -> PlayerHouse2F (4, 5) + 2. east 3 (open) -> PlayerHouse2F (7, 5) + totals: 2 legs, 1 turns, 1 open, 0 localization + +== 00.01 above_the_door (costs: route) + from: PlayerHouse1F (10, 3) (10, 4) (set) + target: PlayerHouse1F (6, 9) facing south (tile) + start candidates: PlayerHouse1F (10, 3), PlayerHouse1F (10, 4) + 1. south 7 (to wall) -> PlayerHouse1F (10, 10) + 2. north 1 (open) -> PlayerHouse1F (10, 9) + 3. west 4 (open) -> PlayerHouse1F (6, 9) + totals: 3 legs, 2 turns, 2 open, 1 localization + +== 00.01 short_of_barrys_door (costs: route) + from: TwinleafTown (20, 22) facing south (tile) + target: TwinleafTown (10, 12) facing west (tile) + start candidates: Twinleaf Town (20, 22) + 1. west 7 (open) -> Twinleaf Town (13, 22) + 2. north 10 (to wall) -> Twinleaf Town (13, 12) + 3. west 3 (open) -> Twinleaf Town (10, 12) + totals: 3 legs, 2 turns, 2 open, 0 localization + +== 00.01 below_barrys_stairs (costs: route) + from: unknown + target: RivalHouse1F (2, 3) facing east (tile) + not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends) + +== 00.01 above_barrys_stairs (costs: route) + from: RivalHouse2F (3, 5) facing north (tile) + target: RivalHouse2F (3, 4) facing west (tile) + start candidates: RivalHouse2F (3, 5) + 1. north 1 (to wall) -> RivalHouse2F (3, 4) + totals: 1 legs, 0 turns, 0 open, 0 localization + +== 00.01 above_barrys_door (costs: route) + from: RivalHouse1F (2, 3) (tile) + target: RivalHouse1F (6, 9) facing south (tile) + start candidates: RivalHouse1F (2, 3) + 1. south 6 (open) -> RivalHouse1F (2, 9) + 2. east 4 (open) -> RivalHouse1F (6, 9) + totals: 2 legs, 1 turns, 2 open, 0 localization + +== 00.01 below_the_lake_entrance (costs: route) + from: unknown + target: VerityLakefront (17, 14) facing north (tile) + not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends) + +== 00.03 short_of_rowan (costs: route) + from: VerityLakefront (17, 14) (17, 15) (set) + target: Route201 (4, 14) facing east (tile) + start candidates: Verity Lakefront (17, 14), Verity Lakefront (17, 15) + 1. south 7 (to wall) -> Verity Lakefront (17, 21) + 2. east 19 (open) -> Route 201 (4, 14) + totals: 2 legs, 1 turns, 1 open, 1 localization + +== 00.03 by_the_counter (costs: route) + from: PlayerHouse1F (5, 8) (6, 8) facing east (set) + target: PlayerHouse1F (4, 8) facing west (tile) + start candidates: PlayerHouse1F (5, 8), PlayerHouse1F (6, 8) + 1. west 2 (to wall) -> PlayerHouse1F (4, 8) + totals: 1 legs, 0 turns, 0 open, 1 localization + +== 00.03 short_of_dawn (costs: route) + from: TwinleafTown (20, 22) facing south (tile) + target: Route201 (63, 5) facing east (tile) + start candidates: Twinleaf Town (20, 22) + 1. west 3 (open) -> Twinleaf Town (17, 22) + 2. north 34 (to wall) -> Route 201 (17, 13) + 3. east 40 (to wall) -> Route 201 (57, 13) + 4. west 7 (open) -> Route 201 (50, 13) + 5. north 10 (to wall) -> Route 201 (50, 3) + 6. east 13 (to wall) -> Route 201 (63, 3) + 7. south 2 (open) -> Route 201 (63, 5) + totals: 7 legs, 6 turns, 3 open, 0 localization + +== 00.04 onto_the_path (costs: town) + from: SandgemTown (26, 11) (27, 11) (28, 11) (26, 12) (27, 12) (28, 12) facing north (set) + target: SandgemTown (29, 12) facing west (tile) + start candidates: Sandgem Town (26, 11), Sandgem Town (27, 11), Sandgem Town (28, 11), Sandgem Town (26, 12), Sandgem Town (27, 12), Sandgem Town (28, 12) + 1. east 3 (to wall) -> Sandgem Town (29, 11), Sandgem Town (29, 12) + 2. north 1 (to wall) -> Sandgem Town (29, 11) + 3. south 1 (open) -> Sandgem Town (29, 12) + totals: 3 legs, 2 turns, 1 open, 2 localization + +== 00.04 to_ledge_column (costs: line) + from: Route201 (57, 5) (58, 5) (59, 5) (60, 5) (61, 5) (62, 5) (63, 5) facing west (set) + target: Route201 (55, 5) facing west (tile) + start candidates: Route 201 (57, 5), Route 201 (58, 5), Route 201 (59, 5), Route 201 (60, 5), Route 201 (61, 5), Route 201 (62, 5), Route 201 (63, 5) + 1. west 21 (to wall) -> Route 201 (42, 5) + 2. east 13 (open) -> Route 201 (55, 5) + totals: 2 legs, 1 turns, 1 open, 1 localization + +== 00.04 along_route_201_road (costs: line) + from: Route201 (55, 14) facing south (tile) + target: Route201 (15, 14) facing west (tile) + start candidates: Route 201 (55, 14) + 1. west 16 (open) -> Route 201 (39, 14) + 2. north 3 (open) -> Route 201 (39, 11) + 3. west 24 (open) -> Route 201 (15, 11) + 4. south 2 (open) -> Route 201 (15, 14) + totals: 4 legs, 3 turns, 4 open, 0 localization + +== 00.04 into_twinleaf (costs: line) + from: Route201 (15, 14) facing west (tile) + target: TwinleafTown (15, 22) facing south (tile) + start candidates: Route 201 (15, 14) + 1. south 33 (open) -> Twinleaf Town (15, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.04 to_moms_doorstep (costs: line) + from: TwinleafTown (15, 22) facing south (tile) + target: TwinleafTown (20, 22) facing north (tile) + start candidates: Twinleaf Town (15, 22) + 1. east 5 (open) -> Twinleaf Town (20, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.04 beside_mom (costs: route) + from: PlayerHouse1F (6, 9) facing north (tile) + target: PlayerHouse1F (6, 8) facing east (tile) + start candidates: PlayerHouse1F (6, 9) + 1. north 1 (open) -> PlayerHouse1F (6, 8) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.04 short_of_the_catch_tutorial (costs: route) + from: TwinleafTown (19, 22) facing east (tile) + target: Route202 (22, 27) facing west (tile) + start candidates: Twinleaf Town (19, 22) + 1. west 2 (open) -> Twinleaf Town (17, 22) + 2. north 34 (to wall) -> Route 201 (17, 13) + 3. east 40 (to wall) -> Route 201 (57, 13) + 4. west 7 (open) -> Route 201 (50, 13) + 5. north 7 (open) -> Route 201 (50, 6) + 6. east 43 (to wall) -> Sandgem Town (29, 13) + 7. west 5 (open) -> Sandgem Town (24, 13) + 8. north 21 (to wall) -> Route 202 (25, 24) + 9. west 3 (to wall) -> Route 202 (22, 24) + 10. south 3 (open) -> Route 202 (22, 27) + totals: 10 legs, 9 turns, 5 open, 0 localization + +== 00.04b to_catch_grass (costs: route) + from: Route202 (15, 25) (16, 25) (17, 25) (18, 25) (19, 25) (20, 25) (21, 25) (15, 26) (16, 26) (17, 26) (18, 26) (19, 26) (20, 26) (21, 26) (15, 27) (16, 27) (17, 27) (18, 27) (19, 27) (20, 27) (21, 27) (21, 28) (21, 29) (set) + target: Route202 (18, 25) (19, 25) (20, 25) (18, 26) (19, 26) (20, 26) (18, 27) (19, 27) (20, 27) (set) + start candidates: Route 202 (15, 25), Route 202 (16, 25), Route 202 (17, 25), Route 202 (18, 25), Route 202 (19, 25), Route 202 (20, 25), Route 202 (21, 25), Route 202 (15, 26), Route 202 (16, 26), Route 202 (17, 26), Route 202 (18, 26), Route 202 (19, 26), Route 202 (20, 26), Route 202 (21, 26), Route 202 (15, 27), Route 202 (16, 27), Route 202 (17, 27), Route 202 (18, 27), Route 202 (19, 27), Route 202 (20, 27), Route 202 (21, 27), Route 202 (21, 28), Route 202 (21, 29) + 1. north 4 (to wall) -> Route 202 (15, 25), Route 202 (16, 25), Route 202 (17, 25), Route 202 (18, 25), Route 202 (19, 25), Route 202 (20, 25), Route 202 (21, 25) + 2. east 8 (to wall) -> Route 202 (23, 25) + 3. west 3 (open) -> Route 202 (20, 25) + totals: 3 legs, 2 turns, 1 open, 2 localization + +== 00.04b into_sandgem (costs: robust) + from: Route202 (18, 25) (19, 25) (20, 25) (18, 26) (19, 26) (20, 26) (18, 27) (19, 27) (20, 27) (set) + target: SandgemTown (29, 5) (tile) + start candidates: Route 202 (18, 25), Route 202 (19, 25), Route 202 (20, 25), Route 202 (18, 26), Route 202 (19, 26), Route 202 (20, 26), Route 202 (18, 27), Route 202 (19, 27), Route 202 (20, 27) + 1. south 2 (to wall) -> Route 202 (18, 27), Route 202 (19, 27), Route 202 (20, 27) + 2. east 12 (to wall) -> Route 202 (30, 27) + 3. south 10 (to wall) -> Sandgem Town (29, 5) + totals: 3 legs, 2 turns, 0 open, 2 localization + +== 00.04b to_center_sign (costs: town) + from: SandgemTown (29, 5) (tile) + target: SandgemTown (20, 11) (tile) + start candidates: Sandgem Town (29, 5) + 1. west 5 (open) -> Sandgem Town (24, 5) + 2. south 6 (open) -> Sandgem Town (24, 11) + 3. west 4 (open) -> Sandgem Town (20, 11) + totals: 3 legs, 2 turns, 3 open, 0 localization + +== 00.04d north_to_jubilife (costs: route) + from: Route202 (30, 24) (tile) + target: Route202 (11, 0) (12, 0) (13, 0) (14, 0) (15, 0) (16, 0) (17, 0) (18, 0) (11, 1) (12, 1) (13, 1) (14, 1) (15, 1) (16, 1) (17, 1) (18, 1) (11, 2) (12, 2) (13, 2) (14, 2) (15, 2) (16, 2) (17, 2) (18, 2) (11, 3) (12, 3) (13, 3) (14, 3) (15, 3) (16, 3) (17, 3) (18, 3) (set) + start candidates: Route 202 (30, 24) + 1. south 2 (open) -> Route 202 (30, 26) + 2. west 27 (to wall) -> Route 202 (3, 26) + 3. north 12 (to wall) -> Route 202 (3, 14) + 4. east 14 (to wall) -> Route 202 (17, 14) + 5. south 8 (to wall) -> Route 202 (17, 22) + 6. east 13 (to wall) -> Route 202 (30, 22) + 7. north 18 (to wall) -> Route 202 (30, 4) + 8. south 1 (open) -> Route 202 (30, 5) + 9. west 12 (open) -> Route 202 (18, 5) + 10. north 2 (open) -> Route 202 (18, 3) + totals: 10 legs, 9 turns, 4 open, 0 localization + +== 00.05 to_the_center (costs: town) + from: unknown + target: JubilifeCity (52, 41) facing north (tile) + not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends) + +== 00.05 to_the_school (costs: town) + from: JubilifeCity (52, 41) facing north (tile) + target: JubilifeCity (40, 41) facing north (tile) + start candidates: Jubilife City (52, 41) + 1. west 12 (open) -> Jubilife City (40, 41) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.05b below_the_presidents_trigger (costs: town) + from: JubilifeCity (40, 41) facing south (tile) + target: JubilifeCity (46, 41) facing north (tile) + start candidates: Jubilife City (40, 41) + 1. east 6 (open) -> Jubilife City (46, 41) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.05b below_the_mart_clown (costs: town) + from: unknown + target: JubilifeCity (55, 34) facing north (tile) + not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends) + +== 00.05b below_the_tv_clown (costs: town) + from: JubilifeCity (55, 34) facing north (tile) + target: JubilifeCity (36, 17) facing north (tile) + start candidates: Jubilife City (55, 34) + 1. west 23 (to wall) -> Jubilife City (32, 34) + 2. north 10 (open) -> Jubilife City (32, 24) + 3. east 4 (open) -> Jubilife City (36, 24) + 4. north 7 (open) -> Jubilife City (36, 17) + totals: 4 legs, 3 turns, 3 open, 0 localization + +== 00.05b below_the_company_clown (costs: town) + from: JubilifeCity (36, 17) facing north (tile) + target: JubilifeCity (15, 19) facing north (tile) + start candidates: Jubilife City (36, 17) + 1. south 4 (open) -> Jubilife City (36, 21) + 2. west 21 (open) -> Jubilife City (15, 21) + 3. north 2 (open) -> Jubilife City (15, 19) + totals: 3 legs, 2 turns, 3 open, 0 localization + +== 00.05c to_main_boulevard (costs: line) + from: JubilifeCity (15, 19) facing north (tile) + target: JubilifeCity (15, 22) facing south (tile) + start candidates: Jubilife City (15, 19) + 1. south 3 (open) -> Jubilife City (15, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.05c along_main_boulevard (costs: line) + from: JubilifeCity (15, 22) facing south (tile) + target: JubilifeCity (45, 22) facing south (tile) + start candidates: Jubilife City (15, 22) + 1. east 30 (open) -> Jubilife City (45, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.05c beside_the_president (costs: line) + from: JubilifeCity (45, 22) facing south (tile) + target: JubilifeCity (45, 35) facing east (tile) + start candidates: Jubilife City (45, 22) + 1. south 13 (open) -> Jubilife City (45, 35) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.05c to_the_route_203_street (costs: line) + from: JubilifeCity (45, 35) facing east (tile) + target: JubilifeCity (58, 22) facing east (tile) + start candidates: Jubilife City (45, 35) + 1. north 13 (open) -> Jubilife City (45, 22) + 2. east 13 (open) -> Jubilife City (58, 22) + totals: 2 legs, 1 turns, 2 open, 0 localization + +== 01.01 west_of_barrys_trigger (costs: town) + from: JubilifeCity (58, 22) facing east (tile) + target: Route203 (4, 18) facing east (tile) + start candidates: Jubilife City (58, 22) + 1. east 9 (open) -> Route 203 (4, 18) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.02 by_the_gate (costs: route) + from: Route203 (5, 20) facing south (tile) + target: Route203 (55, 9) facing east (tile) + start candidates: Route 203 (5, 20) + 1. north 2 (open) -> Route 203 (5, 18) + 2. east 50 (to wall) -> Route 203 (55, 18) + 3. north 9 (open) -> Route 203 (55, 9) + totals: 3 legs, 2 turns, 2 open, 0 localization + +== 01.02 west_of_the_hikers_trigger (costs: route) + from: OreburghGate (4, 22) (5, 22) facing east (set) + target: OreburghGate (6, 22) facing east (tile) + start candidates: OreburghGate (4, 22), OreburghGate (5, 22) + 1. south 1 (to wall) -> OreburghGate (4, 23), OreburghGate (5, 23) + 2. east 2 (to wall) -> OreburghGate (6, 23) + 3. north 1 (open) -> OreburghGate (6, 22) + totals: 3 legs, 2 turns, 1 open, 2 localization + +== 01.02 past_curtis (costs: route) + from: OreburghGate (7, 22) facing east (tile) + target: OreburghGate (20, 22) facing east (tile) + start candidates: OreburghGate (7, 22) + 1. east 13 (open) -> OreburghGate (20, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.02 by_the_east_mouth (costs: route) + from: OreburghGate (20, 22) facing east (tile) + target: OreburghGate (26, 22) facing east (tile) + start candidates: OreburghGate (20, 22) + 1. east 6 (open) -> OreburghGate (26, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.02 west_of_the_welcome (costs: route) + from: OreburghCity (2, 13) (3, 13) facing east (set) + target: OreburghCity (9, 13) facing east (tile) + start candidates: Oreburgh City (2, 13), Oreburgh City (3, 13) + 1. north 3 (to wall) -> Oreburgh City (2, 10), Oreburgh City (3, 10) + 2. east 4 (to wall) -> Oreburgh City (6, 10) + 3. south 3 (open) -> Oreburgh City (6, 13) + 4. east 3 (open) -> Oreburgh City (9, 13) + totals: 4 legs, 3 turns, 2 open, 2 localization + +== 01.02b below_the_centers_door (costs: town) + from: OreburghCity (26, 22) facing north (tile) + target: OreburghCity (47, 21) facing north (tile) + start candidates: Oreburgh City (26, 22) + 1. east 22 (to wall) -> Oreburgh City (48, 22) + 2. north 1 (to wall) -> Oreburgh City (48, 21) + 3. west 1 (open) -> Oreburgh City (47, 21) + totals: 3 legs, 2 turns, 1 open, 0 localization + +== 01.03 above_the_mine (costs: town) + from: OreburghCity (47, 21) (46, 21) facing south (set) + target: OreburghCity (46, 57) facing south (tile) + start candidates: Oreburgh City (47, 21), Oreburgh City (46, 21) + 1. east 2 (to wall) -> Oreburgh City (48, 21) + 2. west 4 (open) -> Oreburgh City (44, 21) + 3. south 20 (to wall) -> Oreburgh City (44, 41) + 4. west 1 (open) -> Oreburgh City (43, 41) + 5. south 16 (to wall) -> Oreburgh City (43, 57) + 6. east 3 (open) -> Oreburgh City (46, 57) + totals: 6 legs, 5 turns, 3 open, 1 localization + +== 01.05 east_of_barrys_trigger (costs: town) + from: OreburghCity (26, 21) (26, 22) facing south (set) + target: OreburghCity (7, 13) facing west (tile) + start candidates: Oreburgh City (26, 21), Oreburgh City (26, 22) + 1. south 5 (to wall) -> Oreburgh City (26, 26) + 2. west 2 (to wall) -> Oreburgh City (24, 26) + 3. north 5 (to wall) -> Oreburgh City (24, 21) + 4. west 9 (open) -> Oreburgh City (15, 21) + 5. north 8 (open) -> Oreburgh City (15, 13) + 6. west 8 (open) -> Oreburgh City (7, 13) + totals: 6 legs, 5 turns, 3 open, 1 localization + +== 01.05 through_the_gate (costs: route) + from: OreburghGate (27, 22) (26, 22) facing west (set) + target: OreburghGate (5, 22) facing west (tile) + start candidates: OreburghGate (27, 22), OreburghGate (26, 22) + 1. north 2 (to wall) -> OreburghGate (27, 20), OreburghGate (26, 21) + 2. east 1 (to wall) -> OreburghGate (27, 20), OreburghGate (27, 21) + 3. south 3 (to wall) -> OreburghGate (27, 23) + 4. west 19 (to wall) -> OreburghGate (8, 23) + 5. north 1 (to wall) -> OreburghGate (8, 22) + 6. west 3 (open) -> OreburghGate (5, 22) + totals: 6 legs, 5 turns, 1 open, 3 localization + +== 01.06 below_rowans_trigger (costs: town) + from: Route203 (55, 9) facing west (tile) + target: JubilifeCity (47, 8) facing north (tile) + start candidates: Route 203 (55, 9) + 1. south 10 (to wall) -> Route 203 (55, 19) + 2. west 17 (to wall) -> Route 203 (38, 19) + 3. north 1 (open) -> Route 203 (38, 18) + 4. west 57 (open) -> Jubilife City (44, 22) + 5. north 14 (to wall) -> Jubilife City (44, 8) + 6. east 3 (to wall) -> Jubilife City (47, 8) + totals: 6 legs, 5 turns, 2 open, 0 localization + +== 01.08 below_the_ravaged_path (costs: town) + from: JubilifeCity (44, 5) facing west (tile) + target: Route204South (11, 2) facing north (tile) + start candidates: Jubilife City (44, 5) + 1. east 2 (open) -> Jubilife City (46, 5) + 2. north 19 (to wall) -> Route 204 (14, 18) + 3. west 2 (open) -> Route 204 (12, 18) + 4. north 16 (to wall) -> Route 204 (12, 2) + 5. west 1 (to wall) -> Route 204 (11, 2) + totals: 5 legs, 4 turns, 2 open, 0 localization + +== 01.09 west_of_the_rock (costs: route) + from: RavagedPath (19, 50) facing north (tile) + target: RavagedPath (21, 43) facing east (tile) + start candidates: RavagedPath (19, 50) + 1. north 7 (open) -> RavagedPath (19, 43) + 2. east 2 (open) -> RavagedPath (21, 43) + totals: 2 legs, 1 turns, 2 open, 0 localization + +== 01.09 above_the_way_out (costs: route) + from: RavagedPath (21, 43) facing east (tile) + target: RavagedPath (28, 44) facing south (tile) + start candidates: RavagedPath (21, 43) + 1. east 8 (to wall) -> RavagedPath (29, 43) + 2. south 1 (to wall) -> RavagedPath (29, 44) + 3. west 1 (open) -> RavagedPath (28, 44) + totals: 3 legs, 2 turns, 1 open, 0 localization + +== 01.10 line_1 (costs: line) + from: Route204North (20, 26) facing south (tile) + target: Route204North (20, 27) (tile) + start candidates: Route 204 (20, 26) + 1. south 1 (open) -> Route 204 (20, 27) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.10 line_2 (costs: line) + from: Route204North (20, 27) (tile) + target: Route204North (11, 27) (tile) + start candidates: Route 204 (20, 27) + 1. west 9 (open) -> Route 204 (11, 27) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.10 line_3 (costs: line) + from: Route204North (11, 27) (tile) + target: Route204North (11, 22) (tile) + start candidates: Route 204 (11, 27) + 1. north 5 (open) -> Route 204 (11, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.10 line_4 (costs: line) + from: Route204North (11, 22) (tile) + target: Route204North (19, 22) (tile) + start candidates: Route 204 (11, 22) + 1. east 8 (open) -> Route 204 (19, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.10 line_5 (costs: line) + from: Route204North (19, 22) (tile) + target: Route204North (19, 12) (tile) + start candidates: Route 204 (19, 22) + 1. north 10 (open) -> Route 204 (19, 12) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.10 line_6 (costs: line) + from: Route204North (19, 12) (tile) + target: Route204North (11, 12) (tile) + start candidates: Route 204 (19, 12) + 1. west 8 (open) -> Route 204 (11, 12) + totals: 1 legs, 0 turns, 1 open, 0 localization diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index a11e09f379..289837b23c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -15,6 +15,7 @@ #include #include #include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Filesystem/FileIO.h" #include "Common/Cpp/TestRunners/UnitTest.h" #include "Pokemon/AutoStory/Pokemon_StoryEvents.h" #include "Pokemon/AutoStory/Pokemon_StorySteps.h" @@ -252,20 +253,70 @@ UnitTestResult test_line_5_recovery_pins_the_wall_nearest_the_goal(Logger& logge return true; } -// The legs a ROUTE step from `from` plans, as walk_route() plans them (the -// step's costs, then the default ones), on `world`; nothing if none. -std::optional> route_step_plan(const StoryWorld& world, const Pokemon::Pose& from, const Pokemon::StoryStep& step){ - std::vector start; - for (const TilePos& pos : Pokemon::tiles_of(from)){ - start.push_back(story_to_world(world, from.map, pos)); +// A ROUTE step of the table, and where the steps before it in its row leave +// the player: the row's start, then each step's target or pose_after. A LEGS +// or STEP step that does not say where it ends leaves the start unknown. +struct TableRoute{ + std::string row; + const Pokemon::StoryStep* step; + std::optional from; + // The world the step is planned on; none if the start is unknown or no + // world joins its map and the target's. + const StoryWorld* world; +}; + +std::optional pose_after_step(const std::optional& at, const Pokemon::StoryStep& step){ + if (step.kind == StoryStepKind::ROUTE){ + return step.target; + } + if (step.pose_after){ + return step.pose_after; + } + return step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP ? std::nullopt : at; +} + +std::vector table_routes(){ + std::vector routes; + for (const StoryCheckpoint& row : story_checkpoints()){ + std::optional at = row.start; + for (const Pokemon::StoryStep& step : row.steps){ + if (step.kind == StoryStepKind::ROUTE){ + const bool known = at && !Pokemon::tiles_of(*at).empty(); + routes.push_back({row.id, &step, at, known ? story_plan_world(at->map, step.target->map) : nullptr}); + } + at = pose_after_step(at, step); + } } - std::vector targets; - for (const TilePos& pos : Pokemon::tiles_of(*step.target)){ - targets.push_back(story_to_world(world, step.target->map, pos)); + return routes; +} + +std::vector world_tiles(const StoryWorld& world, const Pokemon::Pose& pose){ + std::vector tiles; + for (const TilePos& pos : Pokemon::tiles_of(pose)){ + tiles.push_back(story_to_world(world, pose.map, pos)); } + return tiles; +} + +// The legs a table ROUTE step plans, as walk_route() plans them: the step's +// costs, then the default ones; no legs if neither plans. +struct RouteStepPlan{ + std::vector start; + std::optional> legs; + bool default_costs = false; // the step's own costs found no plan +}; + +RouteStepPlan plan_table_route(const TableRoute& route){ + const StoryWorld& world = *route.world; + const std::vector targets = world_tiles(world, *route.step->target); const auto goal = [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }; - std::optional> legs = plan_recovered_route(world, start, goal, *story_route_costs(step.variant)); - return legs ? legs : plan_recovered_route(world, start, goal, RobustPlanCosts()); + RouteStepPlan plan{.start = world_tiles(world, *route.from)}; + plan.legs = plan_recovered_route(world, plan.start, goal, *story_route_costs(route.step->variant)); + if (!plan.legs){ + plan.legs = plan_recovered_route(world, plan.start, goal, RobustPlanCosts()); + plan.default_costs = plan.legs.has_value(); + } + return plan; } // Why `planned` may slide into a door or a warp, or "": an open leg (not to @@ -303,26 +354,14 @@ struct PlannedStoryRoute{ // unknown place is logged, not planned. std::vector plan_story_routes(Logger& logger){ std::vector routes; - for (const StoryCheckpoint& row : story_checkpoints()){ - std::optional at = row.start; - for (const Pokemon::StoryStep& step : row.steps){ - const bool known = at && !Pokemon::tiles_of(*at).empty(); - const StoryWorld* world = step.kind == StoryStepKind::ROUTE && known - ? story_plan_world(at->map, step.target->map) : nullptr; - if (step.kind == StoryStepKind::ROUTE && world == nullptr){ - logger.log(std::format("{} {}: not checked, from {}.", row.id, step.name, at ? Pokemon::to_string(*at) : "nowhere known")); - } - if (world != nullptr){ - std::vector from; - for (const TilePos& pos : Pokemon::tiles_of(*at)){ - from.push_back(story_to_world(*world, at->map, pos)); - } - routes.push_back({row.id + " " + step.name, world, std::move(from), route_step_plan(*world, *at, step)}); - } - at = step.kind == StoryStepKind::ROUTE ? step.target - : step.pose_after ? step.pose_after - : step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP ? std::nullopt : at; + for (const TableRoute& route : table_routes()){ + if (route.world == nullptr){ + logger.log(std::format("{} {}: not checked, from {}.", route.row, route.step->name, + route.from ? Pokemon::to_string(*route.from) : "nowhere known")); + continue; } + RouteStepPlan plan = plan_table_route(route); + routes.push_back({route.row + " " + route.step->name, route.world, std::move(plan.start), std::move(plan.legs)}); } return routes; } @@ -451,6 +490,175 @@ UnitTestResult test_ravaged_path_keeps_off_the_youngster(Logger& logger){ } +// The route plan dump: every table ROUTE step's legs, in a golden file +// beside the story data, so a planner or table change shows its plans' diff +// in review. + +constexpr const char* ROUTE_PLANS_HEADER = + "BDSP AutoStory: the legs each ROUTE step of the story table plans.\n" + "Planned as the console's RouteWalker plans them: plan_recovered_route() on\n" + "story_plan_world(), from the tiles the row's steps before it leave the\n" + "player on, with the step's costs, then the default costs if those find none.\n" + "Written by the StoryTable test \"every ROUTE step plans as\n" + "Data/route_plans.golden.txt says\". After a planner or table change, run\n" + "that test with PA_UPDATE_ROUTE_PLANS=1 to rewrite this file\n" + "(PA_ROUTE_PLANS_GOLDEN= reads or writes another copy), and review\n" + "its diff.\n" + "turns: direction changes between legs. open: legs that stop in the open\n" + "(tapped, not held to a wall). localization: the wall holds at the start\n" + "that only bring several start tiles to one (plan_recovered_route()'s\n" + "anchor); 0 from one start tile.\n"; + +std::string tile_list(const StoryWorld& world, const std::vector& tiles){ + std::string out; + for (const TilePos& pos : tiles){ + out += (out.empty() ? "" : ", ") + describe(world, pos); + } + return out; +} + +// plan_recovered_route()'s wall holds from several start tiles: the legs up +// to where the tiles the player may be on first become one. +size_t localization_legs(const std::vector& start, const std::vector& legs){ + if (start.size() < 2){ + return 0; + } + for (size_t i = 0; i < legs.size(); i++){ + if (legs[i].after.size() == 1){ + return i + 1; + } + } + return 0; +} + +std::string plan_totals(const RouteStepPlan& plan){ + const std::vector& legs = *plan.legs; + size_t turns = 0; + size_t open = 0; + for (size_t i = 0; i < legs.size(); i++){ + turns += i > 0 && legs[i].leg.direction != legs[i - 1].leg.direction ? 1 : 0; + open += legs[i].leg.ends_at_wall ? 0 : 1; + } + return std::format(" totals: {} legs, {} turns, {} open, {} localization\n", + legs.size(), turns, open, localization_legs(plan.start, legs)); +} + +std::string dump_plan(const StoryWorld& world, const RouteStepPlan& plan){ + std::string out = " start candidates: " + tile_list(world, plan.start) + "\n"; + if (!plan.legs){ + return out + " NO PLAN\n"; + } + if (plan.default_costs){ + out += " the step's costs found no plan; planned with the default costs\n"; + } + for (size_t i = 0; i < plan.legs->size(); i++){ + const PlannedLeg& planned = (*plan.legs)[i]; + out += std::format(" {}. {} -> {}\n", i + 1, to_string(planned.leg), tile_list(world, planned.after)); + } + return out + plan_totals(plan); +} + +std::string dump_route(const TableRoute& route){ + const Pokemon::StoryStep& step = *route.step; + std::string out = std::format("== {} {} (costs: {})\n", route.row, step.name, step.variant.empty() ? "route" : step.variant); + out += " from: " + (route.from ? Pokemon::to_string(*route.from) : std::string("unknown")) + "\n"; + out += " target: " + Pokemon::to_string(*step.target) + "\n"; + if (route.world == nullptr){ + return out + (route.from && !Pokemon::tiles_of(*route.from).empty() + ? " not planned: no story world joins the two maps\n" + : " not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends)\n"); + } + return out + dump_plan(*route.world, plan_table_route(route)); +} + +std::string route_plans_text(){ + std::string out = ROUTE_PLANS_HEADER; + for (const TableRoute& route : table_routes()){ + out += "\n" + dump_route(route); + } + return out; +} + +// The golden file, in the Data folder beside this file's. +std::string route_plans_golden_path(){ + const char* path = std::getenv("PA_ROUTE_PLANS_GOLDEN"); + if (path != nullptr && path[0] != '\0'){ + return path; + } + const std::string self = __FILE__; + const size_t slash = self.find_last_of("/\\"); + return (slash == std::string::npos ? std::string() : self.substr(0, slash + 1)) + "Data/route_plans.golden.txt"; +} + +// `text` without carriage returns or a byte order mark. +std::string plain_lines(const std::string& text){ + std::string out = text.starts_with("\xef\xbb\xbf") ? text.substr(3) : text; + std::erase(out, '\r'); + return out; +} + +// `text` split into the header and one block per "== " step line. +std::vector plan_blocks(const std::string& text){ + std::vector blocks{""}; + size_t begin = 0; + while (begin < text.size()){ + const size_t end = std::min(text.find('\n', begin), text.size() - 1) + 1; + const std::string line = text.substr(begin, end - begin); + if (line.starts_with("== ")){ + blocks.push_back(""); + } + blocks.back() += line; + begin = end; + } + return blocks; +} + +// Each step whose block changed, as "-" (golden) and "+" (planned) blocks. +std::string plan_differences(const std::string& golden, const std::string& planned){ + const std::vector expected = plan_blocks(golden); + const std::vector actual = plan_blocks(planned); + std::string out; + size_t changed = 0; + for (size_t i = 0; i < std::max(expected.size(), actual.size()); i++){ + const std::string& was = i < expected.size() ? expected[i] : ""; + const std::string& now = i < actual.size() ? actual[i] : ""; + if (was != now && changed++ < 5){ + out += "\n--- golden:\n" + was + "+++ planned:\n" + now; + } + } + return changed == 0 ? "" : std::format("{} block(s) differ, the first ones:{}", changed, out); +} + +// Every table ROUTE step plans the legs the golden file lists. +UnitTestResult test_route_plans_golden(Logger& logger){ + const std::string path = route_plans_golden_path(); + const std::string planned = route_plans_text(); + const char* update = std::getenv("PA_UPDATE_ROUTE_PLANS"); + if (update != nullptr && update[0] != '\0' && update[0] != '0'){ + std::string crlf; + for (char ch : planned){ + crlf += ch == '\n' ? std::string("\r\n") : std::string(1, ch); + } + FileIO file; + if (!file.open(path, FileMode::WRITE | FileMode::BINARY) || file.write(crlf) != crlf.size()){ + return "Could not write " + path + "."; + } + logger.log("Wrote " + path + "."); + return true; + } + std::string golden; + if (!file_to_string(path, golden)){ + return "Could not read " + path + " (set PA_ROUTE_PLANS_GOLDEN to its path)."; + } + const std::string differences = plan_differences(plain_lines(golden), planned); + if (differences.empty()){ + return true; + } + return "The route plans differ from " + path + ". If the change is meant, rerun with PA_UPDATE_ROUTE_PLANS=1 " + "and review the file's diff. " + differences; +} + + struct AutoStoryStoryTableInput{ std::string name; std::function body; @@ -510,6 +718,10 @@ const AutoStoryStoryTableCase AUTO_STORY_STORY_TABLE_CASES[] = { .input = {"Story table: no open leg ends before a door it walks toward (lab-B, 2026-11-08)", test_story_routes_stop_short_of_doors}, .expectation = {}, }, + { + .input = {"Story table: every ROUTE step plans as Data/route_plans.golden.txt says", test_route_plans_golden}, + .expectation = {}, + }, { .input = {"Story table: every route plans, and none runs along a wander zone", test_story_routes_keep_off_wander_zones}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp new file mode 100644 index 0000000000..9dd3fd9b47 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -0,0 +1,275 @@ +/* BDSP AutoStory - Console failure cases on the story simulation + * + * From: https://github.com/PokemonAutomation/ + * + * One case per failure console B showed in its events and perception + * (#268's design note, the planner note), run on the story simulation + * with the knobs that make it happen there (SimWorldKnobs, SimMisses): + * walks that slide on onto a warp, fades the walks' watchers miss or read + * as a battle, banners missed or gone, dim floors, late first lines and + * people who wander. + * + * A case the program fails today is on KNOWN_FAILING with the change that + * is to fix it. Its test passes while the case still fails, and fails + * once the case passes: then take it off the list. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StorySim.h" +#include "PokemonBDSP_AutoStory_SimFailureCases_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +namespace{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::Pose; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + +// Cases the program fails today, with what is to fix each. +const std::map KNOWN_FAILING{ + {"01.05 old walk slides onto the Gate's west mouth, dim fade, banner gone", "#268 slice 2: walkers report warps"}, + {"01.05 old walk slides onto the Gate's west mouth, black fade", "#268 slice 2: walkers report warps"}, + {"01.05 old walk slides onto the Gate's west mouth, white fade", "#268 slices 2 and 3: a fade watcher that tells white from a battle"}, + {"01.05 through_the_gate is one run west", "planner: goal kinds and ms costs (PLANNER_DESIGN.md)"}, + {"any one missed fade or banner from 00.00 to 01.11: every row still passes", "#268 slice 1: door arrival = fade or banner"}, + {"01.08 with Route 204's youngster wandering (12..14, 2)", "planner: one recovery rule, a sidestep round a wanderer (PLANNER_DESIGN.md 4, 7)"}, +}; + +// The table's step `name` in row `row`. +const StoryStep& table_step(const std::string& row, const std::string& name){ + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const StoryStep& step : checkpoint.steps){ + if (checkpoint.id == row && step.name == name){ + return step; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + name + " in " + row); +} + +// Runs rows `from` to `to` of `rows` with `misses` and `knobs`: "" if they +// all pass, else where and why the run stopped. +std::string run_case( + Logger& logger, const std::string& from, const std::string& to, + SimMisses misses, SimWorldKnobs knobs, const std::vector& rows = story_checkpoints() +){ + SimExecutor executor(logger, std::move(misses), std::move(knobs)); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = from, .to = to}, rows); + return report.completed ? "" : std::format("stopped in {}: {}", executor.result().failed_step, executor.result().error); +} +UnitTestResult passes(const std::string& stopped){ + return stopped.empty() ? UnitTestResult(true) : UnitTestResult(stopped); +} + +// The old 01.05 walk west along row 22 to the tile beside the west mouth's +// warp (3, 22), as before #269 stopped routes two short of warps. +StoryStep old_walk_beside_the_west_mouth(){ + StoryStep step = table_step("01.05", "through_the_gate"); + step.target = Pokemon::tile_pose("OreburghGate", {TilePos{4, 22}}, Direction::WEST); + return step; +} + +// 01.05's walk west through the Gate whose last open leg runs a tile on; +// the old walk's slides onto the west mouth's warp to Route 203. +SimWorldKnobs gate_slide(SimFade fade, bool banner_up){ + const Pose far = *table_step("01.05", "out_of_oreburgh_gate").pose_after; + return {.slides = {{.step = "through_the_gate", .direction = Direction::WEST, .tiles = 1, + .far = far, .fade = fade, .banner_up = banner_up}}}; +} +UnitTestResult gate_old_walk_slides(Logger& logger, SimFade fade, bool banner_up){ + const std::vector rows = table_with("01.05", old_walk_beside_the_west_mouth()); + return passes(run_case(logger, "01.05", "01.05", {.fade = {}, .banner = {}}, gate_slide(fade, banner_up), rows)); +} + +// The planner's legs for 01.05's walk through the Gate: one run west +// along row 22 works on the console; at most a hold to find the row first. +UnitTestResult gate_plan_one_run(Logger& logger){ + const StoryWorld* world = story_plan_world("OreburghGate", "OreburghGate"); + const std::vector from{story_to_world(*world, "OreburghGate", {27, 22}), story_to_world(*world, "OreburghGate", {26, 22})}; + const TilePos goal = story_to_world(*world, "OreburghGate", {5, 22}); + const auto plan = plan_recovered_route(*world, from, [&](const TilePos& pos){ return pos == goal; }, *story_route_costs(table_step("01.05", "through_the_gate").variant)); + if (!plan){ + return "no plan"; + } + std::string legs; + for (const PlannedLeg& leg : *plan){ + legs += (legs.empty() ? "" : ", ") + to_string(leg.leg); + } + logger.log("through_the_gate plans: " + legs); + return plan->size() <= 2 ? UnitTestResult(true) : UnitTestResult(std::format("{} legs: {}", plan->size(), legs)); +} + +// Each fade and each banner the clean run looks for, missed alone: the +// row it falls in must still pass. A door step accepts only its fade +// today, so a missed fade there fails a real arrival (#268's Monte Carlo, +// 19/20 on 01.05). +UnitTestResult every_single_miss(Logger& logger){ + SimExecutor clean(logger); + if (!run_rows_on(clean, logger, {.from = "00.00", .to = "01.11"}).completed){ + return "the run fails without misses: " + clean.result().error; + } + const std::vector& rows = clean.result().rows; + std::vector failed; + const auto miss = [&](bool fade, size_t index){ + size_t k = 0; + while (k + 1 < rows.size() && (fade ? rows[k + 1].fades : rows[k + 1].banners) <= index){ + k++; + } + SimMisses misses{.fade = {}, .banner = {}}; + (fade ? misses.fade : misses.banner) = index - (fade ? rows[k].fades : rows[k].banners); + const std::string stopped = run_case(logger, rows[k].row, rows[k].row, misses, {}); + if (!stopped.empty()){ + failed.push_back(std::format("{} {} missed: {}", fade ? "fade" : "banner", index, stopped)); + } + }; + for (size_t i = 0; i < clean.misses().fades; i++){ + miss(true, i); + } + for (size_t i = 0; i < clean.misses().banners; i++){ + miss(false, i); + } + std::string out = std::format("{} of {} single misses fail their row:", failed.size(), clean.misses().fades + clean.misses().banners); + for (const std::string& line : failed){ + out += "\n " + line; + } + return failed.empty() ? UnitTestResult(true) : UnitTestResult(out); +} + +// Oreburgh's street at night (88, game clock 00:25; 104 by day, r74), the +// Gate's dim floor (46) and a cave mouth's dim fade (45 to 64): the tap +// steps judge their fades with tap_faded(), which took the Gate's floor +// for a fade under the old "brightness under 75" (lab-B 2026-11-08). +UnitTestResult night_and_dim_floors(Logger& logger){ + SimWorldKnobs knobs{ + .floor = {{"OreburghCity", 88}, {"Route203", 88}, {"OreburghGate", 46}}, + .fade_into = {{"OreburghGate", 64}, {"OreburghCity", 255}, {"Route203", 255}}, + }; + return passes(run_case(logger, "01.02", "01.05", {.fade = {}, .banner = {}}, knobs)); +} + +// 01.03: Roark's first line in the mine comes after the camera zooms in on +// us, some seconds after the A press (r98; the old event waited 8 s). +UnitTestResult roark_speaks_late(Logger& logger){ + std::string talk; + for (const StoryCheckpoint& row : story_checkpoints()){ + for (const StoryStep& step : row.steps){ + if (row.id == "01.03" && step.kind == StoryStepKind::TALK){ + talk = step.name; + } + } + } + return passes(run_case(logger, "01.03", "01.03", {.fade = {}, .banner = {}}, {.first_line = {{talk, 7000ms}}})); +} + +// `row` with everyone on its maps walking their wander boxes, seeds 1 to 8. +UnitTestResult wanderers_move(Logger& logger, const std::string& row){ + std::vector failed; + for (uint64_t seed = 1; seed <= 8; seed++){ + const std::string stopped = run_case(logger, row, row, {.fade = {}, .banner = {}}, {.wander_seed = seed}); + if (!stopped.empty()){ + failed.push_back(std::format("seed {}: {}", seed, stopped)); + } + } + std::string out = std::format("{} of 8 seeds fail:", failed.size()); + for (const std::string& line : failed){ + out += "\n " + line; + } + return failed.empty() ? UnitTestResult(true) : UnitTestResult(out); +} + +struct FailureCaseInput{ + std::string name; + std::function body; +}; +// Whether a case is expected to fail is KNOWN_FAILING's, by name. +struct FailureCaseExpectation{ +}; +struct FailureCase{ + FailureCaseInput input; + FailureCaseExpectation expectation; +}; + +class Test_AutoStoryFailureCase : public UnitTest{ +public: + explicit Test_AutoStoryFailureCase(FailureCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Console failure on the sim: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + UnitTestResult result; + try{ + result = m_case.input.body(logger); + }catch (Exception& e){ + result = std::string(e.name()) + ": " + e.message(); + } + const auto known = KNOWN_FAILING.find(m_case.input.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: + FailureCase m_case; +}; + +} // namespace + +const FailureCase AUTO_STORY_FAILURE_CASES[] = { + {.input = {"01.05 through_the_gate's last leg runs a tile on (lab-B 2026-11-08 15:31)", [](Logger& logger){ + return passes(run_case(logger, "01.05", "01.05", {.fade = {}, .banner = {}}, gate_slide(SimFade::DIM, false))); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, dim fade, banner gone", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::DIM, false); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, dim fade, banner up", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::DIM, true); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, black fade", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::BLACK, true); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, white fade", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::WHITE, true); + }}, .expectation = {}}, + {.input = {"01.05 through_the_gate is one run west", gate_plan_one_run}, .expectation = {}}, + {.input = {"any one missed fade or banner from 00.00 to 01.11: every row still passes", every_single_miss}, .expectation = {}}, + {.input = {"01.02 to 01.05 at night, the Gate's dim floor", night_and_dim_floors}, .expectation = {}}, + {.input = {"01.03 Roark's first line 7 s after the A press", roark_speaks_late}, .expectation = {}}, + {.input = {"01.03 with Oreburgh's people wandering (the pokefan on 45, 37..39)", [](Logger& logger){ + return wanderers_move(logger, "01.03"); + }}, .expectation = {}}, + {.input = {"01.08 with Route 204's youngster wandering (12..14, 2)", [](Logger& logger){ + return wanderers_move(logger, "01.08"); + }}, .expectation = {}}, +}; + +void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_FAILURE_CASES){ + database.add(item); + } +} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h new file mode 100644 index 0000000000..b196c4baf9 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h @@ -0,0 +1,27 @@ +/* BDSP AutoStory - Console failure cases on the story simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_SimFailureCases_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_SimFailureCases_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// Each failure console B showed in events and perception, run on the story +// simulation; the ones the program still fails are known failing. +void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp new file mode 100644 index 0000000000..c535b38c60 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -0,0 +1,591 @@ +/* BDSP AutoStory - Story simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StorySim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::Outcome; +using Pokemon::Pose; +using Pokemon::RunState; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + + +// A hold until something stops us. A door stops it at the fade, which +// fails the step; a fade missed lets the hold go on past the mouth (r81's +// timed walk south out of the Ravaged Path, onto Route 204's cliff). +void SimStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ + m_sim.tap(direction, ROUTE_TURN_TAP, false); + Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); + SimMove move = m_sim.hold(direction, limit, SimPace::WALK); + if (move.stop == SimStop::WARP && fade_missed() && m_far_side()){ + limit -= std::min(limit, move.time); + move = m_sim.hold(direction, limit, SimPace::WALK); + } + if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ + m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); + } +} + +// The D-pad, a tile at a time, until `map`'s banner reads; through a door +// the walk goes on beyond it (the fade eats no tiles of a hold). +bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&){ + const bool miss = banner_missed(); + size_t on = 0; + for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ + SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + const bool crossed = move.stop == SimStop::WARP && m_far_side(); + const bool stopped = !crossed && (move.distance == 0 || move.stop != SimStop::DONE); + on = on_map(map) ? on + 1 : 0; + if (on > 0 && (on > SIM_BANNER_TILES || stopped) && !miss){ + return true; + } + if (stopped){ + return false; + } + } + return false; +} + +double SimStoryStepIO::floor_here() const{ + for (const auto& [map, brightness] : m_knobs.floor){ + if (on_map(map)){ + return brightness; + } + } + return SIM_FLOOR; +} + +// D-pad taps, each looked at, until the fade and then the banner (the +// console's ConsoleStoryStepIO::tap_to_banner()): none if the banner shows +// before the first. Each look stands still, so a banner on the far side +// reads at once. A look the program's tap_faded() takes for the fade ends +// the taps, banner or not: a warp's fade, or a dim floor read as one; with +// the fade missed the next look still sees the banner. +std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ + if (m_misses.through == m_misses.tap_steps++){ + m_misses.missed = true; + if (m_far_side() && m_misses.through_banner){ + return 0; + } + } + if (std::exchange(m_misses.banner_up, "") == map){ + return 0; + } + bool crossed = false; + for (size_t tap = 1; tap <= max_taps; tap++){ + const double before = floor_here(); + const SimMove move = m_sim.tap(direction, 160ms, false); + if (move.stop == SimStop::DIALOG){ + return std::nullopt; + } + double look = floor_here(); + if (move.stop == SimStop::WARP){ + const auto fade = m_knobs.fade_into.find(map); + look = fade_missed() ? look : fade == m_knobs.fade_into.end() ? SIM_DOOR_FADE : fade->second; + crossed = m_far_side(); + } + if (crossed && on_map(map) && !banner_missed()){ + return tap; + } + if (tap_faded(before, look)){ + return std::nullopt; + } + } + return std::nullopt; +} + +WalkResult SimKnobRouteIO::walk_taps(Direction direction, size_t tiles, const std::string& label){ + const WalkResult result = GridSimRouteIO::walk_taps(direction, tiles, label); + if (result.stop != WalkStop::LIMIT || m_slid_steps.contains(m_step)){ + return result; + } + for (const SimSlide& item : m_knobs.slides){ + if (item.step == m_step && item.direction == direction){ + m_slid_steps.insert(m_step); + return slide_on(item, result); + } + } + return result; +} + +// The taps past the leg's end. Onto a warp the walk sees what the fade +// looks like to its watchers: a black fade ends it (TRANSITION), a white +// one is a wild battle to it, a dim one nothing. +WalkResult SimKnobRouteIO::slide_on(const SimSlide& slide, WalkResult result){ + m_misses.slid = true; + for (size_t tap = 0; tap < slide.tiles; tap++){ + const SimMove move = m_grid.tap(slide.direction, ROUTE_MS_PER_TILE_ACROSS, false); + if (move.stop != SimStop::WARP){ + note(std::format("[Sim] slid a tile on to {}.", to_string(m_grid.player().pos)), RouteNote::LOG); + continue; + } + note("[Sim] slid onto a warp to " + Pokemon::to_string(slide.far) + ".", RouteNote::LOG); + m_cross(slide.far); + m_misses.banner_up = slide.banner_up ? slide.far.map : ""; + if (slide.fade == SimFade::BLACK){ + result.stop = WalkStop::TRANSITION; + }else if (slide.fade == SimFade::WHITE){ + result.wild_battles++; + } + return result; + } + return result; +} + +bool SimKnobRouteIO::dialog_within(Milliseconds wait, Color color){ + const auto late = m_knobs.first_line.find(m_step); + if (late != m_knobs.first_line.end() && late->second > wait){ + note(std::format("[Sim] {}: the first line comes after {} ms, past the {} ms wait.", m_step, late->second.count(), wait.count()), RouteNote::LOG); + return false; + } + return GridSimRouteIO::dialog_within(wait, color); +} + +// The story variables whose coord events the table walks onto, from the +// row (and step) the table's reasons give, with the maps' coord events +// (Diamond's zone events; Platinum's for the houses): Barry's doorstep and +// Mom's warning in 00.01, Barry's Route 201 warning, then its pull-back +// row 19 once he has warned us (r14, r16); the lake's entrance in 00.02; +// Rowan's stop and Dawn at Sandgem's edge in 00.03; Dawn's catching +// tutorial on Route 202 from 00.04's start, Mom's call once she has healed +// us; the Poketch president on Jubilife's row 40 in 00.05b; Barry on Route +// 203 in 01.01; the Gate's Hiker and Oreburgh's welcome in 01.02; Barry's +// bump in Oreburgh after Roark in 01.05; and Rowan in Jubilife in 01.07. +// Left out: the Twinleaf guitarist (spent upstairs), Platinum's rival +// steps around our bedroom's start, Dawn at Jubilife's steps (BDSP starts +// her below them: an event), and Floaroma's (10..12, 29) (Diamond only). +std::vector story_vars(){ + return { + {.var = "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", .value = 0, .row = "00.01", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 0, .row = "00.01", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 1, .row = "00.01", .after = "barry_warns_us"}, + {.var = "VAR_VERITY_LAKEFRONT_STATE", .value = 0, .row = "00.02", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 2, .row = "00.03", .after = ""}, + {.var = "VAR_SANDGEM_TOWN_STATE", .value = 0, .row = "00.03", .after = ""}, + {.var = "VAR_ROUTE_202_STATE", .value = 0, .row = "00.04", .after = ""}, + {.var = "CONSOLE_MOMS_CALL", .value = 0, .row = "00.04", .after = "mom_heals_us"}, + {.var = "VAR_POKETCH_CAMPAIGN_STATE", .value = 1, .row = "00.05b", .after = ""}, + {.var = "VAR_ROUTE_203_RIVAL_STATE", .value = 0, .row = "01.01", .after = ""}, + {.var = "VAR_OREBURGH_GATE_1F_HIKER_STATE", .value = 1, .row = "01.02", .after = ""}, + {.var = "VAR_OREBURGH_CITY_STATE", .value = 0, .row = "01.02", .after = ""}, + {.var = "VAR_OREBURGH_CITY_STATE", .value = 2, .row = "01.05", .after = ""}, + {.var = "VAR_JUBILIFE_CITY_STATE", .value = 3, .row = "01.07", .after = ""}, + }; +} + +namespace{ + +// The maps' coord events (story_coord_events()) whose variable holds. +std::optional var_state(const CoordEvent& event){ + for (const VarState& state : story_vars()){ + if (state.var == event.var && state.value == event.value){ + return state; + } + } + return std::nullopt; +} + +RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ + return {.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; +} + +} // namespace + +std::vector story_triggers(){ + std::vector triggers; + for (const auto& [map, json] : bdsp_map_json()){ + for (const CoordEvent& event : story_coord_events(map)){ + const std::optional state = var_state(event); + if (state){ + triggers.push_back(row_trigger(map, event, *state)); + } + } + } + return triggers; +} + +namespace{ + +// Someone the maps do not have, on `tile` of `map`, talked to or walked round: +// from row `row` on, until row `until_row`'s step `until` has run if it is set. +struct SimPerson{ + std::string name; + std::string map; + TilePos tile; + std::string row; + std::string until_row = {}; + std::string until = {}; +}; +std::vector sim_people(){ + return { + // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). + {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04"}, + // Barry in the Gym's door, from the welcome (lab-B 2026-11-08) to his lines (r101, r104). + {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.02b", .until_row = "01.02b", .until = "barrys_lines"}, + }; +} + +// A house's stairs, entered by a step `side` from the map's "stairs" +// point into what the map draws as a wall (the table's 00.01: r8 and r9 +// for ours, r11 for Barry's). +struct SimStairs{ + std::string map; + Direction side; +}; +std::vector sim_stairs(){ + return { + {.map = "PlayerHouse2F", .side = Direction::EAST}, + {.map = "RivalHouse1F", .side = Direction::EAST}, + {.map = "RivalHouse2F", .side = Direction::WEST}, + }; +} + +} // namespace + +// The world the player walks on for `map`: the planner's, with what the +// console showed that the maps lack. Nothing for a room with no map. +const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ + const StoryWorld* world = story_plan_world(map, map); + std::vector here; + std::string who; + for (const SimPerson& person : sim_people()){ + const bool now = m_row >= person.row && (person.until.empty() || m_row < person.until_row || + (m_row == person.until_row && !m_ran.contains(person.until))); + if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ + here.push_back(person); + who += person.name + ";"; + } + } + if (here.empty()){ + return world; + } + std::unique_ptr& peopled = m_peopled[{world, who}]; + if (!peopled){ + peopled = std::make_unique(*world); + for (const SimPerson& person : here){ + peopled->block(story_to_world(*world, person.map, person.tile)); + } + } + return peopled.get(); +} + +SimWorld SimExecutor::setup(const StoryWorld* world) const{ + // B runs once the shoes' scene has given them: the scene ends at home. + SimWorld out{.world = world, .trainers = story_trainers(*world), .can_run = m_walks.can_run()}; + for (const SimStairs& stairs : sim_stairs()){ + if (sim_world(stairs.map) == world){ + out.doors.push_back(story_to_world(*world, stairs.map, map_point(stairs.map, "stairs").next(stairs.side))); + } + } + for (const RowTrigger& armed : m_armed){ + if (sim_world(armed.map) != world){ + continue; + } + SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; + for (const TilePos& pos : armed.trigger.tiles){ + trigger.tiles.push_back(story_to_world(*world, armed.map, pos)); + } + out.triggers.push_back(std::move(trigger)); + } + out.wanderers = wanderers(*world); + return out; +} + +namespace{ +bool on_world(const StoryWorld& world, const std::string& map){ + try{ + story_to_world(world, map, {0, 0}); + return true; + }catch (const InternalProgramError&){ + return false; + } +} +} // namespace + +// Everyone with a wander box on `world`'s maps, walking it from their tile +// (SimWorldKnobs::wander_seed), each with their own seed and start time. +std::vector SimExecutor::wanderers(const StoryWorld& world) const{ + std::vector out; + if (!m_knobs.wander_seed){ + return out; + } + for (const auto& [map, json] : bdsp_map_json()){ + if (!on_world(world, map)){ + continue; + } + for (const auto& object : story_map(map).objects){ + if (!object.wander){ + continue; + } + const uint64_t seed = *m_knobs.wander_seed * 1000003 + out.size() * 7919 + (uint64_t)(object.x * 31 + object.y); + const TilePos low = story_to_world(world, map, {object.wander->x0, object.wander->y0}); + const TilePos high = story_to_world(world, map, {object.wander->x1, object.wander->y1}); + out.push_back({ + .name = object.name, + .box = {.x0 = low.x, .y0 = low.y, .x1 = high.x, .y1 = high.y}, + .pos = story_to_world(world, map, {object.x, object.y}), + .seed = seed, + .step_interval = Milliseconds(2000), + .elapsed = Milliseconds(0), + .time_offset = Milliseconds((int64_t)(seed % 2000)), + }); + } + } + return out; +} + +// Arms the triggers of this row that start after `after`. +void SimExecutor::arm(const std::string& after){ + size_t armed = 0; + for (const RowTrigger& trigger : story_triggers()){ + if (trigger.row == m_row && trigger.after == after){ + m_armed.push_back(trigger); + armed++; + } + } + const SimPlayer& player = m_sim.player(); + if (armed > 0 && m_placed && on_grid(player.pos) && !player.dialog){ + m_sim.place(setup(&m_sim.world()), nearest_tile(player.pos), player.facing); + } +} + +// Puts the player on `pose`, on the world `on` if given, unless they stand +// on one of its tiles already. Returns whether the pose is on a map the +// simulation has. +bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ + const std::vector tiles = Pokemon::tiles_of(pose); + const StoryWorld* world = on != nullptr ? on : pose.map.empty() ? nullptr : sim_world(pose.map); + if (world == nullptr || tiles.empty()){ + return false; + } + // The program thinks we are on `pose`; we walk on from where the slide left us. + if (m_astray && m_placed){ + return true; + } + const SimPlayer& player = m_sim.player(); + const std::optional local = !m_placed || &m_sim.world() != world + ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); + if (local && on_grid(player.pos) && std::find(tiles.begin(), tiles.end(), *local) != tiles.end()){ + return true; + } + m_sim.place(setup(world), story_to_world(*world, pose.map, tiles.front()), Pokemon::facing_of(pose)); + m_placed = true; + return true; +} + +// Through a door or a cave mouth onto the step's far side, the player's +// facing kept: a hold goes on from there. +bool SimExecutor::cross(){ + return m_far && cross_to(*m_far); +} +bool SimExecutor::cross_to(const Pose& far){ + const StoryWorld* world = sim_world(far.map); + const std::vector tiles = Pokemon::tiles_of(far); + if (world == nullptr || tiles.empty()){ + return false; + } + m_sim.place(setup(world), story_to_world(*world, far.map, tiles.front()), std::nullopt); + return true; +} + +// Why the player does not stand on one of `pose`'s tiles, or "" if they +// do or the simulation cannot tell (no map, or not placed yet). +std::string SimExecutor::off_pose(const Pose& pose) const{ + const std::vector tiles = Pokemon::tiles_of(pose); + if (!m_placed || tiles.empty() || sim_world(pose.map) == nullptr){ + return ""; + } + const SimPlayer& player = m_sim.player(); + const TilePos at = nearest_tile(player.pos); + // In world tiles: a pose a leg worked out from the map it started on + // may lie past that map's edge, on the next map (Twinleaf's exit). + // story_to_world() throws for a map not on the player's world. + try{ + const auto there = [&](const TilePos& tile){ return story_to_world(m_sim.world(), pose.map, tile) == at; }; + if (on_grid(player.pos) && std::ranges::any_of(tiles, there)){ + return ""; + } + }catch (const InternalProgramError&){} + return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), at), Pokemon::to_string(pose)); +} + +// The program's run into the Center: past its door, the inside shows, a missed fade or not. +Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ + if (!sync(state.pose)){ + return Pokemon::outcome_ok(); + } + run_into_center(m_io, m_walks.can_run(), [this]{ + m_misses.fade_unseen = false; + return m_sim.player().warped.has_value(); + }, [&]{ + throw GridSimFailure{step.name + ": no door north of " + to_string(m_sim.player().pos)}; + }); + return Pokemon::outcome_ok(); +} + +// Why a walking step did not end where the table says, or "". A step +// through a door the simulation did not cross is not checked: the sim's +// maps have no warps' destinations. +std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ + const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP; + const std::optional expected = step.pose_after ? step.pose_after : outcome.pose; + if (!walks || !m_placed){ + return ""; + } + if (m_astray){ + m_result.unchecked.push_back(m_row + " " + step.name + " (slid on)"); + return ""; + } + if (!expected || Pokemon::tiles_of(*expected).empty()){ + m_result.unchecked.push_back(m_row + " " + step.name); + return ""; + } + const SimPlayer& player = m_sim.player(); + if (player.warped && !story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos))){ + return ""; + } + return off_pose(*expected); +} + +Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ + if (!m_start_mismatch.empty()){ + return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); + } + m_far = step.pose_after; + if (story_events().contains(step.variant)){ + return stub(); + } + // A scene goes on from where the step before left us. A route walks + // on the world it plans on (Jubilife alone has no Route 204 north of it). + const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || + step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK; + const StoryWorld* on = step.kind == StoryStepKind::ROUTE && step.target && !state.pose.map.empty() + ? story_plan_world(state.pose.map, step.target->map) : nullptr; + // A world of one map is sim_world()'s, with its people. + if (on != nullptr && on == story_plan_world(state.pose.map, state.pose.map)){ + on = nullptr; + } + if (walks && !sync(state.pose, on)){ + m_logger.log(std::format("[{}] {}: no map for {}; passed over.", m_row, step.name, Pokemon::to_string(state.pose))); + m_passed_over = true; + return Pokemon::outcome_ok(); + } + return Pokemon::StoryStepExecutor::run(state, step); +} + +Outcome SimExecutor::run(RunState& state, const StoryStep& step){ + Outcome outcome; + m_passed_over = false; + m_step = step.name; + try{ + outcome = run_step(state, step); + }catch (const GridSimFailure& e){ + outcome = Pokemon::outcome_failed("sim_failure", e.message); + } + m_astray |= std::exchange(m_misses.slid, false); + const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; + if (!mismatch.empty()){ + outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); + } + // What the simulation does not play (scenes, events, battles) ends + // where the table says it does. + if (outcome.succeeded() && step.pose_after){ + m_astray = false; + sync(*step.pose_after); + } + m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); + if (std::exchange(m_misses.missed, false) && m_result.missed_step.empty()){ + m_result.missed_step = m_row + " " + step.name; + } + if (!outcome.succeeded() && m_result.error.empty()){ + // The walker's last notes, to see why. + for (size_t i = m_notes.size() - std::min(m_notes.size(), 40); i < m_notes.size(); i++){ + m_logger.log(std::format("[{}] note: {}", m_row, m_notes[i])); + } + m_result.error = m_row + " " + Pokemon::to_string(outcome); + m_result.failed_step = m_row + " " + step.name; + } + m_result.world = m_placed ? &m_sim.world() : nullptr; + m_result.end = nearest_tile(m_sim.player().pos); + m_ran.insert(step.name); + arm(step.name); + return outcome; +} + +// Runs `range` of `rows` (the table unless given) on `executor`, stopping +// at the first failure. +Pokemon::SegmentReport run_rows_on( + SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, + const std::vector& rows +){ + std::set saved; + Pokemon::Segment segment = make_story_segment(rows, executor, saved); + Pokemon::SegmentPolicy policy; + policy.stop_at_first_failure = true; + Pokemon::SegmentHooks hooks; + hooks.reload = [](RunState&){ return Pokemon::outcome_ok(); }; + hooks.log = [&logger](const std::string& line){ logger.log(line); }; + RunState state; + return Pokemon::run_segment(state, segment, range, policy, hooks); +} + +// Runs `range` of the table on the simulation, stopping at the first failure. +UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ + SimExecutor executor(logger); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, range); + for (const std::string& step : executor.result().unchecked){ + logger.log("No end to check after " + step + "."); + } + if (!report.completed){ + return std::format("stopped at {} {}: {}", report.failed_checkpoint, report.failed_event, executor.result().error); + } + return true; +} + +// The table with row `row`'s step of `step`'s name replaced by `step`. +std::vector table_with(const std::string& row, const StoryStep& step){ + std::vector rows = story_checkpoints(); + for (StoryCheckpoint& checkpoint : rows){ + for (StoryStep& old : checkpoint.steps){ + if (checkpoint.id == row && old.name == step.name){ + old = step; + return rows; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + step.name + " in " + row); +} + +bool ends_on(const SimRun& run, const Pose& pose){ + const std::vector tiles = Pokemon::tiles_of(pose); + const std::optional local = run.world ? story_to_local(*run.world, pose.map, run.end) : std::nullopt; + return local && std::find(tiles.begin(), tiles.end(), *local) != tiles.end(); +} +std::string end_of(const SimRun& run){ + return run.world ? describe(*run.world, run.end) : "nowhere"; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h new file mode 100644 index 0000000000..ec681f290e --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -0,0 +1,393 @@ +/* BDSP AutoStory - Story simulation + * + * From: https://github.com/PokemonAutomation/ + * + * The story table's rows run as the program runs them (the segment + * runner, make_story_segment()), with the program's own walking steps + * (StoryWalkSteps) on the grid simulation; see StorySim_Tests.cpp for + * what is simulated and what is stubbed. Moved out of the tests so the + * console failure cases (SimFailureCases_Tests) run on the same executor. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StorySim_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StorySim_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_GridSim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Which detections the simulation misses on purpose (#162): the `fade`th +// door fade (run_into_door(), from 0) or the `banner`th map banner +// (run_until_map()) of the run goes unseen, though the player did go +// through. The console missed both (r75, r81). The `dark`th door run reads +// dark SIM_FALSE_DARK in, short of the door, as lab-B's did on 2026-11-08. +// The `through`th tap step (tap_to_banner(), from 0) starts on its far side, +// its banner gone unless `through_banner`: the walk before it slid onto the +// warp (lab-B 2026-11-08). The counts and flags below are the run's: how +// many fades and banners it looked for, whether a miss happened since the +// executor last looked, whether a missed fade is still unseen, whether a +// walk slid on (SimSlide) since the executor last looked, and the map whose +// banner a slide left up for the next step. +struct SimMisses{ + std::optional fade; + std::optional banner; + std::optional dark = {}; + std::optional through = {}; + bool through_banner = false; + size_t tap_steps = 0; + size_t fades = 0; + size_t banners = 0; + size_t doors = 0; + bool missed = false; + bool fade_unseen = false; + bool slid = false; + std::string banner_up = {}; +}; + +// How a warp's fade looks to the console's watchers (#268's design note). +enum class SimFade{ + // A door's: near black. Every watcher of a black screen sees it. + BLACK, + // A cave mouth's: dim, not black. A walk's strict black watcher (rgb + // sum 100, stddev 10; WalkRunner::hold()) misses it and the walk goes + // on (the Oreburgh Gate, lab-B 2026-11-08 16:03). + DIM, + // A cave exit's white: a walk's encounter-flash watcher reads it as a + // wild battle. + WHITE, +}; + +// An open leg that runs on past its end: the walk taps of the step `step` +// toward `direction` go `tiles` further, once per step. Onto a warp, the +// player lands on `far` (the sim's maps have no warps' destinations), the +// walk sees the fade as `fade` looks, and the far map's banner is still up +// for the next step (`banner_up`) or gone (01.05, lab-B 2026-11-08 15:31). +struct SimSlide{ + std::string step; + Pokemon::Direction direction = Pokemon::Direction::WEST; + size_t tiles = 1; + Pokemon::Pose far = {}; + SimFade fade = SimFade::DIM; + bool banner_up = false; +}; + +// What the console showed that the plain simulation leaves out, each off +// unless set. All of it is deterministic: wanderers walk from `wander_seed`. +struct SimWorldKnobs{ + std::vector slides = {}; + // The mean brightness (0 to 255) of a map's floor, by JSON map name, and + // of the fade into a map; a tap step judges its fade from these with the + // program's tap_faded(). Unset: 104 (Oreburgh's street by day) and 7 + // (a door's black). + std::map floor = {}; + std::map fade_into = {}; + // People with a wander box on their map walk it, a step tried every 2 s. + std::optional wander_seed = std::nullopt; + // How long after the A press a talk's first line shows, by step name. + std::map first_line = {}; +}; + +// The walker's RouteIO on the story simulation, with SimWorldKnobs' slides +// and late first lines. `step` names the step running now; `cross` puts +// the player on a pose past a warp. +class SimKnobRouteIO : public GridSimRouteIO{ +public: + SimKnobRouteIO( + GridSim& sim, std::vector& notes, SimMisses& misses, const SimWorldKnobs& knobs, + const std::string& step, std::function cross + ) + : GridSimRouteIO(sim, notes) + , m_grid(sim) + , m_misses(misses) + , m_knobs(knobs) + , m_step(step) + , m_cross(std::move(cross)) + {} + + virtual WalkResult walk_taps(Pokemon::Direction direction, size_t tiles, const std::string& label) override; + virtual bool dialog_within(Milliseconds wait, Color color) override; + +private: + WalkResult slide_on(const SimSlide& slide, WalkResult result); + + GridSim& m_grid; + SimMisses& m_misses; + const SimWorldKnobs& m_knobs; + const std::string& m_step; + std::function m_cross; + std::set m_slid_steps; +}; + +// How many tiles a held walk goes on into a map before its location +// banner reads: "it shows a tile or a few past the border" (the table's +// route_201_by_the_path(), measured on the console). Standing still, it +// reads at once. Through a cave mouth the fade comes first, and a hold +// whose fade went unseen goes on the same way (r75, r81). +constexpr size_t SIM_BANNER_TILES = 3; +// How far into a door run SimMisses::dark reads dark, short of the door. +constexpr Milliseconds SIM_FALSE_DARK = Milliseconds(1800); +// Brightness (0 to 255) of a floor where SimWorldKnobs does not say: +// Oreburgh's street by day (r74). +constexpr double SIM_FLOOR = 104; +// Brightness of a fade where SimWorldKnobs does not say: a door's black (by hand: 7). +constexpr double SIM_DOOR_FADE = 7; + +// What a run on the simulation did. +struct SimRun{ + // The first failure, as "row outcome", or "". + std::string error; + // The rows and steps where an injected miss happened and where the run + // first failed, as "row step": "" if none. + std::string missed_step; + std::string failed_step; + // Walking steps that end where nothing says, as "row step". + std::vector unchecked; + // Each row run, with the fades and banners looked for before it. + struct RowStart{ + std::string row; + size_t fades; + size_t banners; + }; + std::vector rows; + // Where the player stood after the last step, if placed. + const StoryWorld* world = nullptr; + Pokemon::TilePos end; +}; + +// StoryStepIO on the simulation. A walk through a door or a cave mouth +// stops on its tile, as the console stops at the fade; a hold that misses +// the fade carries on, onto `far_side()` (the step's pose_after: the +// sim's maps have no warps' destinations) and on along it. +class SimStoryStepIO : public StoryStepIO{ +public: + SimStoryStepIO( + GridSim& sim, std::vector& notes, SimMisses& misses, const SimWorldKnobs& knobs, + const std::string& step, std::function far_side, std::function cross + ) + : m_sim(sim) + , m_route(sim, notes, misses, knobs, step, std::move(cross)) + , m_misses(misses) + , m_knobs(knobs) + , m_far_side(std::move(far_side)) + {} + + virtual RouteIO& route() override{ + return m_route; + } + virtual void fight(const std::string&) override{ + m_sim.end_dialogue(); + } + virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; + virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; + virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) override{ + const SimPace pace = run ? SimPace::RUN : SimPace::WALK; + if (false_dark() && dark_from <= SIM_FALSE_DARK && SIM_FALSE_DARK < timeout){ + m_sim.hold(direction, SIM_FALSE_DARK, pace); + return true; + } + const bool warped = m_sim.hold(direction, timeout, pace).stop == SimStop::WARP; + if (warped && fade_missed()){ + m_misses.fade_unseen = true; + return false; + } + return warped; + } + // A scene may take us to another map (Mom walks us out, 00.04): with a + // dialogue open the stub scene plays it. Otherwise only a door fades. + // A fade missed on the way in stays missed: it was over before settle() + // looked, which then fails as it does on the console after 120 s. + virtual void settle(Button, const std::string& label, bool fade) override{ + const bool scene_fades = m_sim.player().dialog && m_far_side(); + if (fade && ((!m_sim.player().warped && !scene_fades) || m_misses.fade_unseen)){ + m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); + } + m_misses.fade_unseen = false; + m_sim.end_dialogue(); + } + virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) override; + +private: + // Whether the run misses this fade or this banner (SimMisses). + bool fade_missed(){ + const bool miss = m_misses.fade == m_misses.fades++; + m_misses.missed |= miss; + return miss; + } + bool false_dark(){ + const bool dark = m_misses.dark == m_misses.doors++; + m_misses.missed |= dark; + return dark; + } + bool banner_missed(){ + const bool miss = m_misses.banner == m_misses.banners++; + m_misses.missed |= miss; + return miss; + } + bool on_map(const std::string& map) const{ + return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); + } + // The brightness of the floor the player stands on (SimWorldKnobs::floor). + double floor_here() const; + + GridSim& m_sim; + SimKnobRouteIO m_route; + SimMisses& m_misses; + const SimWorldKnobs& m_knobs; + std::function m_far_side; +}; + +// A scene's trigger the simulation fires from row `row` on, once the step +// `after` has run ("" from the row's start), on `map`'s `tiles`. +struct RowTrigger{ + std::string row; + std::string after; + std::string map; + SimTrigger trigger; +}; + +// When a story variable holds the value its coord events wait for: from +// row `row` on, once the step `after` has run ("" from the row's start). +struct VarState{ + std::string var; + int value; + std::string row; + std::string after; +}; + +// The story variables whose coord events the table walks onto, and from +// which row and step each holds (the definition says why each). +std::vector story_vars(); +// The maps' coord events whose story variable holds, as triggers. +std::vector story_triggers(); + +// The program's walking steps on the simulation, the rest stubbed. +class SimExecutor : public Pokemon::StoryStepExecutor{ +public: + explicit SimExecutor(Logger& logger, SimMisses misses = {}, SimWorldKnobs knobs = {}) + : m_logger(logger) + , m_misses(misses) + , m_knobs(std::move(knobs)) + , m_sim({}, {0, 0}, Pokemon::Direction::NORTH, false) + , m_io(m_sim, m_notes, m_misses, m_knobs, m_step, [this]{ return cross(); }, [this](const Pokemon::Pose& far){ cross_to(far); }) + , m_walks(m_io) + {} + + const SimMisses& misses() const{ + return m_misses; + } + const SimRun& result() const{ + return m_result; + } + virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ + m_row = data.id; + m_start_mismatch = data.start ? off_pose(*data.start) : ""; + m_ran.clear(); + m_astray = false; + m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); + m_walks.begin_attempt(data.id); + arm(""); + } + virtual Pokemon::Outcome run(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; + +protected: + virtual Pokemon::Outcome route(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.route(state, step); } + virtual Pokemon::Outcome legs(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.legs(state, step); } + virtual Pokemon::Outcome step(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.step(state, step); } + virtual Pokemon::Outcome talk(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.talk(state, step); } + virtual Pokemon::Outcome mash(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.mash(state, step); } + virtual Pokemon::Outcome heal(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; + virtual Pokemon::Outcome new_game(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome options(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome answer(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome battle(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome train(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome shop(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome save(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome game(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + +private: + // A step the simulation does not play: its dialogue opened and closed. + Pokemon::Outcome stub(){ + m_sim.end_dialogue(); + return Pokemon::outcome_ok(); + } + const StoryWorld* sim_world(const std::string& map) const; + SimWorld setup(const StoryWorld* world) const; + void arm(const std::string& after); + bool sync(const Pokemon::Pose& pose, const StoryWorld* on = nullptr); + bool cross(); + bool cross_to(const Pokemon::Pose& far); + std::vector wanderers(const StoryWorld& world) const; + std::string off_pose(const Pokemon::Pose& pose) const; + std::string check(const Pokemon::StoryStep& step, const Pokemon::Outcome& outcome); + Pokemon::Outcome run_step(Pokemon::RunState& state, const Pokemon::StoryStep& step); + + Logger& m_logger; + std::vector m_notes; + SimMisses m_misses; + SimWorldKnobs m_knobs; + // The step running now. + std::string m_step; + GridSim m_sim; + SimStoryStepIO m_io; + StoryWalkSteps m_walks; + // The planner's worlds with sim_people() on them, by world and who. + mutable std::map, std::unique_ptr> m_peopled; + // The steps of this row that have run. + std::set m_ran; + std::string m_row; + std::vector m_armed; + // Where the step running now ends, if it says: a door's far side. + std::optional m_far; + // Why the player is not on this row's start, or "". + std::string m_start_mismatch; + // Whether the player has been put on a map yet. + bool m_placed = false; + // Whether the step running now is on a room with no map. + bool m_passed_over = false; + // Whether a walk slid on (SimSlide), so the player is not where the + // program thinks, until a step's pose_after puts them right. + bool m_astray = false; + SimRun m_result; +}; + +// Runs `range` of `rows` (the table unless given) on `executor`, stopping +// at the first failure. +Pokemon::SegmentReport run_rows_on( + SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, + const std::vector& rows = story_checkpoints() +); +// Runs `range` of the table on the simulation, stopping at the first failure. +UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range); +// The table with row `row`'s step of `step`'s name replaced by `step`. +std::vector table_with(const std::string& row, const Pokemon::StoryStep& step); +// Whether the run ended on one of `pose`'s tiles. +bool ends_on(const SimRun& run, const Pokemon::Pose& pose); +// Where the run ended, described; "nowhere" if never placed. +std::string end_of(const SimRun& run); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 5f6a1a86b7..181e4da95c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -49,6 +49,7 @@ #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_StorySim.h" #include "PokemonBDSP_AutoStory_StorySim_Tests.h" namespace PokemonAutomation{ @@ -66,661 +67,6 @@ using Pokemon::StoryStep; using Pokemon::StoryStepKind; using Pokemon::TilePos; -// Which detections the simulation misses on purpose (#162): the `fade`th -// door fade (run_into_door(), from 0) or the `banner`th map banner -// (run_until_map()) of the run goes unseen, though the player did go -// through. The console missed both (r75, r81). The `dark`th door run reads -// dark SIM_FALSE_DARK in, short of the door, as lab-B's did on 2026-11-08. -// The `through`th tap step (tap_to_banner(), from 0) starts on its far side, -// its banner gone unless `through_banner`: the walk before it slid onto the -// warp (lab-B 2026-11-08). The counts and flags below are the run's: how -// many fades and banners it looked for, whether a miss happened since the -// executor last looked, and whether a missed fade is still unseen. -struct SimMisses{ - std::optional fade; - std::optional banner; - std::optional dark = {}; - std::optional through = {}; - bool through_banner = false; - size_t tap_steps = 0; - size_t fades = 0; - size_t banners = 0; - size_t doors = 0; - bool missed = false; - bool fade_unseen = false; -}; - -// How many tiles a held walk goes on into a map before its location -// banner reads: "it shows a tile or a few past the border" (the table's -// route_201_by_the_path(), measured on the console). Standing still, it -// reads at once. Through a cave mouth the fade comes first, and a hold -// whose fade went unseen goes on the same way (r75, r81). -constexpr size_t SIM_BANNER_TILES = 3; -constexpr Milliseconds SIM_FALSE_DARK = 1800ms; - -// What a run on the simulation did. -struct SimRun{ - // The first failure, as "row outcome", or "". - std::string error; - // The rows and steps where an injected miss happened and where the run - // first failed, as "row step": "" if none. - std::string missed_step; - std::string failed_step; - // Walking steps that end where nothing says, as "row step". - std::vector unchecked; - // Each row run, with the fades and banners looked for before it. - struct RowStart{ - std::string row; - size_t fades; - size_t banners; - }; - std::vector rows; - // Where the player stood after the last step, if placed. - const StoryWorld* world = nullptr; - TilePos end; -}; - -// StoryStepIO on the simulation. A walk through a door or a cave mouth -// stops on its tile, as the console stops at the fade; a hold that misses -// the fade carries on, onto `far_side()` (the step's pose_after: the -// sim's maps have no warps' destinations) and on along it. -class SimStoryStepIO : public StoryStepIO{ -public: - SimStoryStepIO(GridSim& sim, std::vector& notes, SimMisses& misses, std::function far_side) - : m_sim(sim) - , m_route(sim, notes) - , m_misses(misses) - , m_far_side(std::move(far_side)) - {} - - virtual RouteIO& route() override{ - return m_route; - } - virtual void fight(const std::string&) override{ - m_sim.end_dialogue(); - } - virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string& label) override; - virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; - virtual bool run_into_door(Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) override{ - const SimPace pace = run ? SimPace::RUN : SimPace::WALK; - if (false_dark() && dark_from <= SIM_FALSE_DARK && SIM_FALSE_DARK < timeout){ - m_sim.hold(direction, SIM_FALSE_DARK, pace); - return true; - } - const bool warped = m_sim.hold(direction, timeout, pace).stop == SimStop::WARP; - if (warped && fade_missed()){ - m_misses.fade_unseen = true; - return false; - } - return warped; - } - // A scene may take us to another map (Mom walks us out, 00.04): with a - // dialogue open the stub scene plays it. Otherwise only a door fades. - // A fade missed on the way in stays missed: it was over before settle() - // looked, which then fails as it does on the console after 120 s. - virtual void settle(Button, const std::string& label, bool fade) override{ - const bool scene_fades = m_sim.player().dialog && m_far_side(); - if (fade && ((!m_sim.player().warped && !scene_fades) || m_misses.fade_unseen)){ - m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); - } - m_misses.fade_unseen = false; - m_sim.end_dialogue(); - } - virtual std::optional tap_to_banner(Direction direction, const std::string& map, size_t max_taps) override; - -private: - // Whether the run misses this fade or this banner (SimMisses). - bool fade_missed(){ - const bool miss = m_misses.fade == m_misses.fades++; - m_misses.missed |= miss; - return miss; - } - bool false_dark(){ - const bool dark = m_misses.dark == m_misses.doors++; - m_misses.missed |= dark; - return dark; - } - bool banner_missed(){ - const bool miss = m_misses.banner == m_misses.banners++; - m_misses.missed |= miss; - return miss; - } - bool on_map(const std::string& map) const{ - return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); - } - - GridSim& m_sim; - GridSimRouteIO m_route; - SimMisses& m_misses; - std::function m_far_side; -}; - -// A hold until something stops us. A door stops it at the fade, which -// fails the step; a fade missed lets the hold go on past the mouth (r81's -// timed walk south out of the Ravaged Path, onto Route 204's cliff). -void SimStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ - m_sim.tap(direction, ROUTE_TURN_TAP, false); - Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); - SimMove move = m_sim.hold(direction, limit, SimPace::WALK); - if (move.stop == SimStop::WARP && fade_missed() && m_far_side()){ - limit -= std::min(limit, move.time); - move = m_sim.hold(direction, limit, SimPace::WALK); - } - if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ - m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); - } -} - -// The D-pad, a tile at a time, until `map`'s banner reads; through a door -// the walk goes on beyond it (the fade eats no tiles of a hold). -bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&){ - const bool miss = banner_missed(); - size_t on = 0; - for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ - SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); - const bool crossed = move.stop == SimStop::WARP && m_far_side(); - const bool stopped = !crossed && (move.distance == 0 || move.stop != SimStop::DONE); - on = on_map(map) ? on + 1 : 0; - if (on > 0 && (on > SIM_BANNER_TILES || stopped) && !miss){ - return true; - } - if (stopped){ - return false; - } - } - return false; -} - -// D-pad taps, each looked at, until the fade and then the banner (the -// console's ConsoleStoryStepIO::tap_to_banner()): none if the banner shows -// before the first. Each look stands still, so a banner on the far side -// reads at once. A fade seen ends the taps, -// banner or not; with the fade missed the next look still sees the banner. -std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ - if (m_misses.through == m_misses.tap_steps++){ - m_misses.missed = true; - if (m_far_side() && m_misses.through_banner){ - return 0; - } - } - bool crossed = false; - for (size_t tap = 1; tap <= max_taps; tap++){ - const SimMove move = m_sim.tap(direction, 160ms, false); - if (move.stop == SimStop::DIALOG){ - return std::nullopt; - } - bool faded = false; - if (move.stop == SimStop::WARP){ - faded = !fade_missed(); - crossed = m_far_side(); - } - if (crossed && on_map(map) && !banner_missed()){ - return tap; - } - if (faded){ - return std::nullopt; - } - } - return std::nullopt; -} - -// A scene's trigger the simulation fires from row `row` on, once the step -// `after` has run ("" from the row's start), on `map`'s `tiles`. -struct RowTrigger{ - std::string row; - std::string after; - std::string map; - SimTrigger trigger; -}; - -// When a story variable holds the value its coord events wait for: from -// row `row` on, once the step `after` has run ("" from the row's start). -struct VarState{ - std::string var; - int value; - std::string row; - std::string after; -}; - -// The story variables whose coord events the table walks onto, from the -// row (and step) the table's reasons give, with the maps' coord events -// (Diamond's zone events; Platinum's for the houses): Barry's doorstep and -// Mom's warning in 00.01, Barry's Route 201 warning, then its pull-back -// row 19 once he has warned us (r14, r16); the lake's entrance in 00.02; -// Rowan's stop and Dawn at Sandgem's edge in 00.03; Dawn's catching -// tutorial on Route 202 from 00.04's start, Mom's call once she has healed -// us; the Poketch president on Jubilife's row 40 in 00.05b; Barry on Route -// 203 in 01.01; the Gate's Hiker and Oreburgh's welcome in 01.02; Barry's -// bump in Oreburgh after Roark in 01.05; and Rowan in Jubilife in 01.07. -// Left out: the Twinleaf guitarist (spent upstairs), Platinum's rival -// steps around our bedroom's start, Dawn at Jubilife's steps (BDSP starts -// her below them: an event), and Floaroma's (10..12, 29) (Diamond only). -std::vector story_vars(){ - return { - {.var = "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", .value = 0, .row = "00.01", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 0, .row = "00.01", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 1, .row = "00.01", .after = "barry_warns_us"}, - {.var = "VAR_VERITY_LAKEFRONT_STATE", .value = 0, .row = "00.02", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 2, .row = "00.03", .after = ""}, - {.var = "VAR_SANDGEM_TOWN_STATE", .value = 0, .row = "00.03", .after = ""}, - {.var = "VAR_ROUTE_202_STATE", .value = 0, .row = "00.04", .after = ""}, - {.var = "CONSOLE_MOMS_CALL", .value = 0, .row = "00.04", .after = "mom_heals_us"}, - {.var = "VAR_POKETCH_CAMPAIGN_STATE", .value = 1, .row = "00.05b", .after = ""}, - {.var = "VAR_ROUTE_203_RIVAL_STATE", .value = 0, .row = "01.01", .after = ""}, - {.var = "VAR_OREBURGH_GATE_1F_HIKER_STATE", .value = 1, .row = "01.02", .after = ""}, - {.var = "VAR_OREBURGH_CITY_STATE", .value = 0, .row = "01.02", .after = ""}, - {.var = "VAR_OREBURGH_CITY_STATE", .value = 2, .row = "01.05", .after = ""}, - {.var = "VAR_JUBILIFE_CITY_STATE", .value = 3, .row = "01.07", .after = ""}, - }; -} - -// The maps' coord events (story_coord_events()) whose variable holds. -std::optional var_state(const CoordEvent& event){ - for (const VarState& state : story_vars()){ - if (state.var == event.var && state.value == event.value){ - return state; - } - } - return std::nullopt; -} - -RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ - return {.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; -} - -std::vector story_triggers(){ - std::vector triggers; - for (const auto& [map, json] : bdsp_map_json()){ - for (const CoordEvent& event : story_coord_events(map)){ - const std::optional state = var_state(event); - if (state){ - triggers.push_back(row_trigger(map, event, *state)); - } - } - } - return triggers; -} - -// Someone the maps do not have, on `tile` of `map`, talked to or walked round: -// from row `row` on, until row `until_row`'s step `until` has run if it is set. -struct SimPerson{ - std::string name; - std::string map; - TilePos tile; - std::string row; - std::string until_row = {}; - std::string until = {}; -}; -std::vector sim_people(){ - return { - // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). - {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04"}, - // Barry in the Gym's door, from the welcome (lab-B 2026-11-08) to his lines (r101, r104). - {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.02b", .until_row = "01.02b", .until = "barrys_lines"}, - }; -} - -// A house's stairs, entered by a step `side` from the map's "stairs" -// point into what the map draws as a wall (the table's 00.01: r8 and r9 -// for ours, r11 for Barry's). -struct SimStairs{ - std::string map; - Direction side; -}; -std::vector sim_stairs(){ - return { - {.map = "PlayerHouse2F", .side = Direction::EAST}, - {.map = "RivalHouse1F", .side = Direction::EAST}, - {.map = "RivalHouse2F", .side = Direction::WEST}, - }; -} - -// The program's walking steps on the simulation, the rest stubbed. -class SimExecutor : public Pokemon::StoryStepExecutor{ -public: - explicit SimExecutor(Logger& logger, SimMisses misses = {}) - : m_logger(logger) - , m_misses(misses) - , m_sim({}, {0, 0}, Direction::NORTH, false) - , m_io(m_sim, m_notes, m_misses, [this]{ return cross(); }) - , m_walks(m_io) - {} - - const SimMisses& misses() const{ - return m_misses; - } - const SimRun& result() const{ - return m_result; - } - virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ - m_row = data.id; - m_start_mismatch = data.start ? off_pose(*data.start) : ""; - m_ran.clear(); - m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); - m_walks.begin_attempt(data.id); - arm(""); - } - virtual Outcome run(RunState& state, const StoryStep& step) override; - -protected: - virtual Outcome route(RunState& state, const StoryStep& step) override{ return m_walks.route(state, step); } - virtual Outcome legs(RunState& state, const StoryStep& step) override{ return m_walks.legs(state, step); } - virtual Outcome step(RunState& state, const StoryStep& step) override{ return m_walks.step(state, step); } - virtual Outcome talk(RunState& state, const StoryStep& step) override{ return m_walks.talk(state, step); } - virtual Outcome mash(RunState& state, const StoryStep& step) override{ return m_walks.mash(state, step); } - virtual Outcome heal(RunState& state, const StoryStep& step) override; - virtual Outcome new_game(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome options(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome answer(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome battle(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome train(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome shop(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome save(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome game(RunState&, const StoryStep&) override{ return stub(); } - -private: - // A step the simulation does not play: its dialogue opened and closed. - Outcome stub(){ - m_sim.end_dialogue(); - return Pokemon::outcome_ok(); - } - const StoryWorld* sim_world(const std::string& map) const; - SimWorld setup(const StoryWorld* world) const; - void arm(const std::string& after); - bool sync(const Pose& pose, const StoryWorld* on = nullptr); - bool cross(); - std::string off_pose(const Pose& pose) const; - std::string check(const StoryStep& step, const Outcome& outcome); - Outcome run_step(RunState& state, const StoryStep& step); - - Logger& m_logger; - std::vector m_notes; - SimMisses m_misses; - GridSim m_sim; - SimStoryStepIO m_io; - StoryWalkSteps m_walks; - // The planner's worlds with sim_people() on them, by world and who. - mutable std::map, std::unique_ptr> m_peopled; - // The steps of this row that have run. - std::set m_ran; - std::string m_row; - std::vector m_armed; - // Where the step running now ends, if it says: a door's far side. - std::optional m_far; - // Why the player is not on this row's start, or "". - std::string m_start_mismatch; - // Whether the player has been put on a map yet. - bool m_placed = false; - // Whether the step running now is on a room with no map. - bool m_passed_over = false; - SimRun m_result; -}; - -// The world the player walks on for `map`: the planner's, with what the -// console showed that the maps lack. Nothing for a room with no map. -const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ - const StoryWorld* world = story_plan_world(map, map); - std::vector here; - std::string who; - for (const SimPerson& person : sim_people()){ - const bool now = m_row >= person.row && (person.until.empty() || m_row < person.until_row || - (m_row == person.until_row && !m_ran.contains(person.until))); - if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ - here.push_back(person); - who += person.name + ";"; - } - } - if (here.empty()){ - return world; - } - std::unique_ptr& peopled = m_peopled[{world, who}]; - if (!peopled){ - peopled = std::make_unique(*world); - for (const SimPerson& person : here){ - peopled->block(story_to_world(*world, person.map, person.tile)); - } - } - return peopled.get(); -} - -SimWorld SimExecutor::setup(const StoryWorld* world) const{ - // B runs once the shoes' scene has given them: the scene ends at home. - SimWorld out{.world = world, .trainers = story_trainers(*world), .can_run = m_walks.can_run()}; - for (const SimStairs& stairs : sim_stairs()){ - if (sim_world(stairs.map) == world){ - out.doors.push_back(story_to_world(*world, stairs.map, map_point(stairs.map, "stairs").next(stairs.side))); - } - } - for (const RowTrigger& armed : m_armed){ - if (sim_world(armed.map) != world){ - continue; - } - SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; - for (const TilePos& pos : armed.trigger.tiles){ - trigger.tiles.push_back(story_to_world(*world, armed.map, pos)); - } - out.triggers.push_back(std::move(trigger)); - } - return out; -} - -// Arms the triggers of this row that start after `after`. -void SimExecutor::arm(const std::string& after){ - size_t armed = 0; - for (const RowTrigger& trigger : story_triggers()){ - if (trigger.row == m_row && trigger.after == after){ - m_armed.push_back(trigger); - armed++; - } - } - const SimPlayer& player = m_sim.player(); - if (armed > 0 && m_placed && on_grid(player.pos) && !player.dialog){ - m_sim.place(setup(&m_sim.world()), nearest_tile(player.pos), player.facing); - } -} - -// Puts the player on `pose`, on the world `on` if given, unless they stand -// on one of its tiles already. Returns whether the pose is on a map the -// simulation has. -bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ - const std::vector tiles = Pokemon::tiles_of(pose); - const StoryWorld* world = on != nullptr ? on : pose.map.empty() ? nullptr : sim_world(pose.map); - if (world == nullptr || tiles.empty()){ - return false; - } - const SimPlayer& player = m_sim.player(); - const std::optional local = !m_placed || &m_sim.world() != world - ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); - if (local && on_grid(player.pos) && std::find(tiles.begin(), tiles.end(), *local) != tiles.end()){ - return true; - } - m_sim.place(setup(world), story_to_world(*world, pose.map, tiles.front()), Pokemon::facing_of(pose)); - m_placed = true; - return true; -} - -// Through a door or a cave mouth onto the step's far side, the player's -// facing kept: a hold goes on from there. -bool SimExecutor::cross(){ - const StoryWorld* world = m_far ? sim_world(m_far->map) : nullptr; - const std::vector tiles = m_far ? Pokemon::tiles_of(*m_far) : std::vector{}; - if (world == nullptr || tiles.empty()){ - return false; - } - m_sim.place(setup(world), story_to_world(*world, m_far->map, tiles.front()), std::nullopt); - return true; -} - -// Why the player does not stand on one of `pose`'s tiles, or "" if they -// do or the simulation cannot tell (no map, or not placed yet). -std::string SimExecutor::off_pose(const Pose& pose) const{ - const std::vector tiles = Pokemon::tiles_of(pose); - if (!m_placed || tiles.empty() || sim_world(pose.map) == nullptr){ - return ""; - } - const SimPlayer& player = m_sim.player(); - const TilePos at = nearest_tile(player.pos); - // In world tiles: a pose a leg worked out from the map it started on - // may lie past that map's edge, on the next map (Twinleaf's exit). - // story_to_world() throws for a map not on the player's world. - try{ - const auto there = [&](const TilePos& tile){ return story_to_world(m_sim.world(), pose.map, tile) == at; }; - if (on_grid(player.pos) && std::ranges::any_of(tiles, there)){ - return ""; - } - }catch (const InternalProgramError&){} - return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), at), Pokemon::to_string(pose)); -} - -// The program's run into the Center: past its door, the inside shows, a missed fade or not. -Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ - if (!sync(state.pose)){ - return Pokemon::outcome_ok(); - } - run_into_center(m_io, m_walks.can_run(), [this]{ - m_misses.fade_unseen = false; - return m_sim.player().warped.has_value(); - }, [&]{ - throw GridSimFailure{step.name + ": no door north of " + to_string(m_sim.player().pos)}; - }); - return Pokemon::outcome_ok(); -} - -// Why a walking step did not end where the table says, or "". A step -// through a door the simulation did not cross is not checked: the sim's -// maps have no warps' destinations. -std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ - const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP; - const std::optional expected = step.pose_after ? step.pose_after : outcome.pose; - if (!walks || !m_placed){ - return ""; - } - if (!expected || Pokemon::tiles_of(*expected).empty()){ - m_result.unchecked.push_back(m_row + " " + step.name); - return ""; - } - const SimPlayer& player = m_sim.player(); - if (player.warped && !story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos))){ - return ""; - } - return off_pose(*expected); -} - -Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ - if (!m_start_mismatch.empty()){ - return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); - } - m_far = step.pose_after; - if (story_events().contains(step.variant)){ - return stub(); - } - // A scene goes on from where the step before left us. A route walks - // on the world it plans on (Jubilife alone has no Route 204 north of it). - const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || - step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK; - const StoryWorld* on = step.kind == StoryStepKind::ROUTE && step.target && !state.pose.map.empty() - ? story_plan_world(state.pose.map, step.target->map) : nullptr; - // A world of one map is sim_world()'s, with its people. - if (on != nullptr && on == story_plan_world(state.pose.map, state.pose.map)){ - on = nullptr; - } - if (walks && !sync(state.pose, on)){ - m_logger.log(std::format("[{}] {}: no map for {}; passed over.", m_row, step.name, Pokemon::to_string(state.pose))); - m_passed_over = true; - return Pokemon::outcome_ok(); - } - return Pokemon::StoryStepExecutor::run(state, step); -} - -Outcome SimExecutor::run(RunState& state, const StoryStep& step){ - Outcome outcome; - m_passed_over = false; - try{ - outcome = run_step(state, step); - }catch (const GridSimFailure& e){ - outcome = Pokemon::outcome_failed("sim_failure", e.message); - } - const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; - if (!mismatch.empty()){ - outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); - } - // What the simulation does not play (scenes, events, battles) ends - // where the table says it does. - if (outcome.succeeded() && step.pose_after){ - sync(*step.pose_after); - } - m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); - if (std::exchange(m_misses.missed, false) && m_result.missed_step.empty()){ - m_result.missed_step = m_row + " " + step.name; - } - if (!outcome.succeeded() && m_result.error.empty()){ - // The walker's last notes, to see why. - for (size_t i = m_notes.size() - std::min(m_notes.size(), 40); i < m_notes.size(); i++){ - m_logger.log(std::format("[{}] note: {}", m_row, m_notes[i])); - } - m_result.error = m_row + " " + Pokemon::to_string(outcome); - m_result.failed_step = m_row + " " + step.name; - } - m_result.world = m_placed ? &m_sim.world() : nullptr; - m_result.end = nearest_tile(m_sim.player().pos); - m_ran.insert(step.name); - arm(step.name); - return outcome; -} - -// Runs `range` of `rows` (the table unless given) on `executor`, stopping -// at the first failure. -Pokemon::SegmentReport run_rows_on( - SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, - const std::vector& rows = story_checkpoints() -){ - std::set saved; - Pokemon::Segment segment = make_story_segment(rows, executor, saved); - Pokemon::SegmentPolicy policy; - policy.stop_at_first_failure = true; - Pokemon::SegmentHooks hooks; - hooks.reload = [](RunState&){ return Pokemon::outcome_ok(); }; - hooks.log = [&logger](const std::string& line){ logger.log(line); }; - RunState state; - return Pokemon::run_segment(state, segment, range, policy, hooks); -} - -// Runs `range` of the table on the simulation, stopping at the first failure. -UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ - SimExecutor executor(logger); - const Pokemon::SegmentReport report = run_rows_on(executor, logger, range); - for (const std::string& step : executor.result().unchecked){ - logger.log("No end to check after " + step + "."); - } - if (!report.completed){ - return std::format("stopped at {} {}: {}", report.failed_checkpoint, report.failed_event, executor.result().error); - } - return true; -} - -// The table with row `row`'s step of `step`'s name replaced by `step`. -std::vector table_with(const std::string& row, const StoryStep& step){ - std::vector rows = story_checkpoints(); - for (StoryCheckpoint& checkpoint : rows){ - for (StoryStep& old : checkpoint.steps){ - if (checkpoint.id == row && old.name == step.name){ - old = step; - return rows; - } - } - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + step.name + " in " + row); -} - -bool ends_on(const SimRun& run, const Pose& pose){ - const std::vector tiles = Pokemon::tiles_of(pose); - const std::optional local = run.world ? story_to_local(*run.world, pose.map, run.end) : std::nullopt; - return local && std::find(tiles.begin(), tiles.end(), *local) != tiles.end(); -} -std::string end_of(const SimRun& run){ - return run.world ? describe(*run.world, run.end) : "nowhere"; -} - UnitTestResult run_exit_test(Logger& logger, const std::string& row_id, const StoryStep& old_step, const SimMisses& misses, const Pose& overshoot){ SimExecutor executor(logger, misses); const std::vector rows = table_with(row_id, old_step); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 1e5e2686ad..206fe066b2 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1722,6 +1722,10 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp From 0192d6bb572d70376f919c24beea60156de9c88e Mon Sep 17 00:00:00 2001 From: Di Fan <26423504+dayfine@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:46:42 -0800 Subject: [PATCH 072/166] BDSP AutoStory: a warp is a fade or a banner; walks report warps (#268 slices 1-3) (#284) * BDSP AutoStory: no route ends beside a warp walking toward it 01.05's open walk west to (2, 13), beside the Oreburgh Gate's mouth, slid onto the warp (lab-B 2026-11-08, four runs). A table test plans every ROUTE step as the walker does and fails on an open leg that may end on the tile before a door it walks toward. It flagged 01.05's old by_the_gate and four more: 00.03 above_the_door_again (now counted legs from the west), 01.02 by_the_east_mouth and 01.05 through_the_gate (two tiles short of the Gate's mouths, the taps go the rest), and 01.03 above_the_mine (two rows above the warp row, the door run goes on). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: the story sim's old steps in their own file Moved unchanged out of StorySim_Tests.cpp, which is at the 1000-line limit: r75's and r81's old cave exits and the old mine steps. The next commit adds 01.05's old tap into the Oreburgh Gate beside them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: a dim cave floor is not a tap step's fade On lab-B (2026-11-08 15:31 to 15:54) 01.05's walk slid into the Oreburgh Gate, and its tap step read the Gate's floor (about 46) as the fade and waited 8 s for a banner already gone. A look after a tap is the fade only when black (< 25) or a drop to dark from the look before the tap (tap_faded()). A banner before the first tap means the walk before took us through: the step ends with no tap. A tap step taps at most two past the door its map has ahead, so one begun through the warp with its banner gone fails a few tiles in, not across the Gate. Tests: tap_faded() on the Gate's floor and real fades; the story sim's 01.05 tap step begun through the Gate's mouth, banner up and gone (red before: 24 taps across the Gate); GridSim's part-tile offset taking the warp on the old open walk west. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: mark the tap step's fade and through-already checks as stopgaps Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: dump every story ROUTE step's planned legs to a golden file Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: the story's route plans golden file Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: a wall leg that never moved waits, then plans from its start On lab-B (2026-11-08 16:50, 01.08 below_the_ravaged_path) the leg "west 2 (to wall)" from Route 204 (13, 2) stopped at once, 0 chunks moved: the youngster who wanders (12, 2) to (14, 2) stood a tile ahead. The wait for the way needed a stop three tiles short of the wall, so he was talked to at once, and the replan from both (12, 2) and (13, 2) found no plan: an uncertain start needs a wall both tiles reach, and no wall is anchored from a tile someone wanders on. A walk to the wall that never moved stopped where it began, so someone stands on the next tile: it now waits for the way on short legs too, and if they stay, the replan starts from the start tile alone with their tile marked. Two Planned route tests replay the run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: red tests for routes along wander zones and short wall legs On lab-B (2026-11-08, 01.08 below_the_ravaged_path) the plan "north 35 (to wall) to (13, 2), west 2 (to wall) to (11, 2)" walked along the row Route 204 South's youngster wanders, (12..14, 2). He stopped the leg west after 1 of 2 tiles; the check at the wall allowed a tile short on legs of two or three tiles, so the route logged arriving at (11, 2) from (13, 2). New tests, red on this commit: - Route planner: a leg may cross a row zone (one tile of it) but not run along it (two tiles, the start among them); no plan when the row is the only way. - Story table: every ROUTE step plans and none runs along a wander zone; 01.08's plan walks at most one tile of (12..14, 2). - Planned route: a 2-tile leg to a wall that ran out of time after 1 tile is a stop short of the wall, not the wall. The two #271 tests that replayed the console's leg along the youngster's row now replay it on a plain room: the planner will no longer plan it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: no route runs along a wander zone; short wall legs walk every tile plan_robust_route() no longer uses a leg that walks two tiles in a row of a zone where someone wanders (the leg's start among them): along a row zone, or through a 2-D one. Crossing a row zone through one tile is still planned at per_wander_tile, with #271's wait if he stands there. With no other way there is no plan; nothing falls back. A leg to a wall of 3 tiles or fewer that runs out of time short of its tiles is now a stop short of the wall (talk, then plan again), and the check at the wall needs every tile on such legs. Plans that change: 01.08 below_the_ravaged_path goes up column 14, then 12, and crosses the youngster's row at (12, 2) only; 00.05b below_the_tv_clown and 01.03 above_the_mine go round their wanderers. The story sim now plans ROUTE steps as walk_route() does (from a wall for a few start tiles, then default costs): from 01.03's two start tiles the search over both ran out of budget on the longer way. The grid sim's wait test crosses a row zone on a plain room, and Segment00Lines' reference line for 00.03 goes along Route 201's row 13, above the Breeder. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: red tests for 01.10's line-5 recovery wall and a battle on line 7 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: recovery takes the cheapest whole walk; 01.10 runs into Floaroma Recovery from a few possible tiles pinned the wall with the fewest held tiles and ignored the way on to the goal: after Taylor's battle on line 5 it held south 12 and walked 12 back where north 13 and 5 south would do. It now plans the way on from every anchor and keeps the cheapest whole walk. 01.10's last line ran an open leg up column 11, which has no wall north; a wild battle on it left no plan. The row now runs north until Floaroma's banner, which ends the same from any tile of the column, and 01.11 starts from the rows the run may stop on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: keep the story table under the length limit; line-7 cases as a table Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: red sim test for 01.11's walk to the old woman lab-B 2026-11-08 18:41: 01.11's 8 taps west, then north, ended below the old man and no one answered the old woman's talk. A grid sim test walks 01.11 to her from each of the nine tiles Floaroma's banner stops us on: the old taps (OldStorySteps) must miss her from x 10 and 12, and the table's walk must end below her from all nine. The westedge batch found the field's edge 3 taps west of the old man, a column west of Floaroma's map. SimGround adds that column beside the map, for this test and for the story sim's 01.11 from now on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: 01.11 walks west to the field's edge, then 4 taps east 8 taps west from where Floaroma's banner stops us (any of x 10..12) did not end below the old woman: on lab-B (2026-11-08 18:41) they ended below the old man. A walk west until the field's edge stops us ends on one column from every arrival; from below the old man the edge is 3 taps west (westedge batch 2026-11-08), so her column is 4 taps east of it. That edge is x = -1, a column west of Floaroma's map. The map is left as it is (a TODO in the table): the field may go on past it, or the old couple may stand a tile east of their map points. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: regenerate the route plans golden after #277, #278 and #279 Rewritten with PA_UPDATE_ROUTE_PLANS=1 on the merged tree: the recovery goal (#278) shortens several localizations, the wander-zone costs (#277) reroute 00.05b and 01.08, and 01.10's line 7 and into_floaroma are no longer ROUTE steps (#279). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: move the story sim's executor out of its tests SimStoryStepIO, SimExecutor and the run helpers move unchanged from StorySim_Tests.cpp to Simulation/PokemonBDSP_AutoStory_StorySim.{h,cpp}, so other test files can run rows on the same simulation. The header qualifies Pokemon:: names; the helpers that were file-local stay in an anonymous namespace. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: console failure cases on the story sim, known failing until fixed Sim knobs (SimWorldKnobs, all off unless a case sets them): - slides: an open leg's taps run on; onto a warp the walk sees the fade as it looks to its watchers (black: TRANSITION, dim: nothing, white: a wild battle), and the far map's banner is up or gone for the next step; - floor and fade brightness per map, judged by the program's tap_faded(); - wanderers: everyone with a wander box on the maps walks it, seeded; - late first lines for a talk. SimFailureCases_Tests runs one case per console failure. Those the program fails today are on KNOWN_FAILING with the change that is to fix them; their tests pass while they still fail and fail once they pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: console failure cases on the story sim (known failing until fixed) (#281) * BDSP AutoStory: move the story sim's executor out of its tests SimStoryStepIO, SimExecutor and the run helpers move unchanged from StorySim_Tests.cpp to Simulation/PokemonBDSP_AutoStory_StorySim.{h,cpp}, so other test files can run rows on the same simulation. The header qualifies Pokemon:: names; the helpers that were file-local stay in an anonymous namespace. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: console failure cases on the story sim, known failing until fixed Sim knobs (SimWorldKnobs, all off unless a case sets them): - slides: an open leg's taps run on; onto a warp the walk sees the fade as it looks to its watchers (black: TRANSITION, dim: nothing, white: a wild battle), and the far map's banner is up or gone for the next step; - floor and fade brightness per map, judged by the program's tap_faded(); - wanderers: everyone with a wander box on the maps walks it, seeded; - late first lines for a talk. SimFailureCases_Tests runs one case per console failure. Those the program fails today are on KNOWN_FAILING with the change that is to fix them; their tests pass while they still fail and fail once they pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --------- Co-authored-by: Claude Opus 5.5 * BDSP AutoStory: a warp is a fade or a banner; walks report warps (#268 slices 1-3) Slice 1: a door step is through on its fade or the far map's banner, either alone (story_arrival_banner(): towns, routes and caves show one, houses and other floors none). run_into_door() watches the banner too and returns what it saw; settle() takes the banner after the fact. A tap step ends on a fade or the banner; the banner after a fade is evidence only. Slice 2: walks report the fade that ended a TRANSITION and any banner read (WalkResult::warp, WarpSeen). A planned route whose leg fades with a warp a tile or two past its end hands over as arrived (walk_route_to_warp()), and the door or tap step after it is done. Slice 3: a fade is a uniform screen, dark (to rgb sum 225, a cave's dim fade) or white (fade_of(), the shared watchers' stddev test). A white flash with no battle after it is a cave exit's fade, not an encounter. Removes the tap step's brightness-drop test and its banner-only "through already" check (the TODO(#268 slice 2/3) stopgaps). Banner reads are gated on the box showing, at most two per showing (LocationBannerReads). leg_path() moves to StoryWorld beside warp_within() to keep PlannedRoute.cpp under 1000 lines. Sim: the walk and tap step judge the sim's fades with fade_of(); floors are textured, fades uniform (a model). Three #281 cases pass and leave KNOWN_FAILING; the every-miss case stays, its single-signal warps listed, and a new case checks every warp that shows both. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --------- Co-authored-by: Claude Opus 5.5 --- .../Data/PokemonBDSP_AutoStory_StoryWorld.cpp | 32 ++++ .../Data/PokemonBDSP_AutoStory_StoryWorld.h | 7 + ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 4 +- .../PokemonBDSP_AutoStory_StoryExecutor.cpp | 4 +- .../PokemonBDSP_AutoStory_StoryPlaces.cpp | 19 +++ .../PokemonBDSP_AutoStory_StoryPlaces.h | 5 + .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 144 ++++++++++-------- .../PokemonBDSP_AutoStory_StoryStepIO.h | 36 ++--- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 53 +++++-- .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 4 + .../PokemonBDSP_AutoStory_Walk_Tests.cpp | 41 ++--- .../PokemonBDSP_AutoStory_GridSim.cpp | 5 +- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 6 +- ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 46 ++++-- .../PokemonBDSP_AutoStory_StorySim.cpp | 43 +++--- .../PokemonBDSP_AutoStory_StorySim.h | 58 ++++--- .../Utils/PokemonBDSP_AutoStory_Location.cpp | 43 ++++++ .../Utils/PokemonBDSP_AutoStory_Location.h | 43 ++++++ .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 55 +++---- .../PokemonBDSP_AutoStory_PlannedRoute.h | 15 ++ .../Utils/PokemonBDSP_AutoStory_Walk.cpp | 67 ++++++-- .../Utils/PokemonBDSP_AutoStory_Walk.h | 45 +++++- 22 files changed, 571 insertions(+), 204 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp index fb9e7a89f5..ae35f4b51b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp @@ -5,6 +5,7 @@ */ #include +#include #include #include "Common/Cpp/Exceptions.h" #include "PokemonBDSP_AutoStory_StoryWorld.h" @@ -294,6 +295,37 @@ std::optional step(const StoryWorld& world, const TilePos& from, Direct return std::nullopt; } +std::vector leg_path(const StoryWorld& grid, TilePos from, Direction direction, size_t tiles){ + std::vector path; + size_t travelled = 0; + while (travelled < tiles){ + const std::optional next = step(grid, from, direction); + if (!next){ + break; + } + travelled += std::abs(next->x - from.x) + std::abs(next->y - from.y); + from = *next; + path.push_back(from); + } + return path; +} + +bool warp_within(const StoryWorld& world, const std::vector& from, Direction direction, size_t reach){ + for (TilePos pos : from){ + for (size_t i = 0; i < reach; i++){ + if (world.tile(pos.next(direction)) == TileKind::DOOR){ + return true; + } + const std::optional next = step(world, pos, direction); + if (!next){ + break; + } + pos = *next; + } + } + return false; +} + // Someone standing in the way stops us too, but is no wall to stop against: // they may turn and talk, or walk off (r29 ran east into Mom, who talked). bool at_wall(const StoryWorld& world, const TilePos& pos, Direction direction){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h index 9cf790e24f..6940a5be4d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h @@ -128,6 +128,13 @@ std::optional step(const StoryWorld& world, const Pokemon::Til // in place. Doors and tiles off the maps are not walls: walking into a // door enters the building, and ground off the maps may be an exit. bool at_wall(const StoryWorld& world, const Pokemon::TilePos& pos, Pokemon::Direction direction); +// The tiles the player passes when walking `tiles` tiles from `from`, the +// first one after `from` first. Stops early where the player is stopped. +std::vector leg_path(const StoryWorld& grid, Pokemon::TilePos from, Pokemon::Direction direction, size_t tiles); +// Whether a warp (a door's tile) lies within `reach` tiles `direction` of +// one of `from`, nothing stopping the player before it: where a walk that +// ran on past its leg's end may have gone through (#268 slice 2). +bool warp_within(const StoryWorld& world, const std::vector& from, Pokemon::Direction direction, size_t reach); // "Route 201 (45, 3)", or "world (x, y)" if no map holds it. std::string describe(const StoryWorld& world, const Pokemon::TilePos& pos); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index 5af1245470..64f2ec71dc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -86,9 +86,9 @@ class RecoveryStepIO : public StoryStepIO{ virtual void fight(const std::string&) override{ throw GridSimFailure{"unexpected trainer"}; } virtual void walk_until_stopped(Direction, size_t, const std::string&) override{ throw GridSimFailure{"unexpected blind hold"}; } virtual bool run_until_map(Direction, Milliseconds, const std::string&, const std::string&) override{ throw GridSimFailure{"unexpected banner walk"}; } - virtual bool run_into_door(Direction, bool, Milliseconds = Milliseconds(12000), Milliseconds = Milliseconds(0)) override{ throw GridSimFailure{"unexpected door"}; } + virtual WarpSeen run_into_door(Direction, bool, Milliseconds = Milliseconds(12000), Milliseconds = Milliseconds(0), const std::string& = "") override{ throw GridSimFailure{"unexpected door"}; } virtual std::optional tap_to_banner(Direction, const std::string&, size_t) override{ throw GridSimFailure{"unexpected banner"}; } - virtual void settle(Button, const std::string&, bool) override{ throw GridSimFailure{"unexpected scene"}; } + virtual void settle(Button, const std::string&, bool, const std::string&) override{ throw GridSimFailure{"unexpected scene"}; } private: RouteIO& m_route; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp index 80e5d6bbe8..47c25de07f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp @@ -241,9 +241,9 @@ Outcome StoryExecutor::heal(RunState&, const StoryStep& step){ // Out the same way: south until the fade. The walk out's indoor check // read "not a room" a step from the counter and stopped inside (r50, r59). route_turn(stream(), context(), Direction::SOUTH); - const bool out = m_io.run_into_door(Direction::SOUTH, m_walks.can_run()); + const bool out = m_io.run_into_door(Direction::SOUTH, m_walks.can_run()).any(); stream().log(std::format("[{}] {}: south out of the Center: {}.", m_checkpoint, step.name, out ? "faded" : "no fade yet")); - m_io.settle(BUTTON_B, label_of(step), !out); + m_io.settle(BUTTON_B, label_of(step), !out, ""); // r143a's heal said it had walked out while still inside. context().wait_for_all_requests(); VideoSnapshot screen = stream().video().snapshot(); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp index 72d05f3667..1493ad8daa 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp @@ -230,6 +230,25 @@ const std::string& story_banner_name(const std::string& map){ return banner_name(map); } +std::string story_arrival_banner(const std::string& from, const std::string& to){ + // The named places, by the place each map is part of: the mine's two floors are one. + static const std::map caves{ + {"OreburghGate", "OreburghGate"}, + {"OreburghMine", "OreburghMine"}, + {"OreburghMineB1F", "OreburghMine"}, + {"RavagedPath", "RavagedPath"}, + }; + const auto place = [](const std::string& map) -> std::string{ + if (banner_names().contains(map)){ + return banner_name(map); + } + const auto cave = caves.find(map); + return cave == caves.end() ? "" : cave->second; + }; + const std::string there = place(to); + return there.empty() || there == place(from) ? "" : story_banner_name(to); +} + const StoryWorld* story_plan_world(const std::string& from, const std::string& to){ for (const PlanWorld& world : plan_worlds()){ if (world.maps.contains(from) && world.maps.contains(to)){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h index 62006d2cf3..a6f0dbbfd0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h @@ -33,6 +33,11 @@ const StoryWorld* story_plan_world(const std::string& from, const std::string& t // The location banner of the JSON map `map` ("Route 204" for both of its // halves), or `map` itself for one no banner list names. const std::string& story_banner_name(const std::string& map); +// The banner (story_banner_name()) a warp from the JSON map `from` onto +// `to` shows, or "" if none: arriving in another town, route or cave shows +// its name (out of the Gym, Oreburgh City's), arriving in a house, a lab, +// a school or another floor of the same cave shows none. +std::string story_arrival_banner(const std::string& from, const std::string& to); // The tile `local` of the map `map` in `world`. Pokemon::TilePos story_to_world(const StoryWorld& world, const std::string& map, const Pokemon::TilePos& local); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index 43df0cf73f..46b0279e63 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -6,6 +6,7 @@ #include #include +#include #include "Common/Cpp/PrettyPrint.h" #include "Common/Cpp/Filesystem/Filesystem.h" #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" @@ -50,16 +51,41 @@ namespace{ // A step or scene that ends on another map (`fade`) must fade on the way, // and only the quiet after the fade counts: r30's scene went quiet for 5 s // before the fade home, and r28 "went out" a tile beside the door and -// walked a whole route in the house. No fade is a map mismatch. +// walked a whole route in the house. No fade is a map mismatch. The far +// map's banner `banner`, if it has one, counts as the fade: a fade the run +// missed is over, but its banner comes after it (#268 slice 1). constexpr double FADE_DARKNESS = 75; // brightness 0 to 255; cave fades reach ~45..64, r24's dim fade goes darker -void settle(VideoStream& stream, ProControllerContext& context, Button button, const std::string& label, bool fade){ +// What settle() has seen of the warp so far: the darkest frame, and the banner. +class SettleWarp{ +public: + explicit SettleWarp(const std::string& banner) + : m_banner(banner) + {} + void look(const ImageViewRGB32& frame, WallClock now){ + m_darkest = std::min(m_darkest, image_average(frame).sum() / 3); + m_banner_seen |= !m_banner.empty() && location_banner_matches(m_reads.read(frame, now), m_banner); + } + bool seen() const{ + return m_darkest < FADE_DARKNESS || m_banner_seen; + } + std::string describe() const{ + return std::format("darkest frame {:.0f}{}", m_darkest, m_banner_seen ? ", banner read" : ""); + } + +private: + const std::string& m_banner; + double m_darkest = 255; + LocationBannerReads m_reads; + bool m_banner_seen = false; +}; +void settle(VideoStream& stream, ProControllerContext& context, Button button, const std::string& label, bool fade, const std::string& banner){ const WallClock none = WallClock::max(); const WallClock deadline = current_time() + 120s; ShortDialogDetector dialog; OverworldDetector overworld; BattleMenuDetector battle_menu(BattleType::STANDARD); WallClock quiet_since = none, calm_since = none; - double darkest = 255; + SettleWarp warp(banner); VideoSnapshot previous; while (current_time() < deadline){ context.wait_for_all_requests(); @@ -71,21 +97,22 @@ void settle(VideoStream& stream, ProControllerContext& context, Button button, c continue; } if (frame){ - darkest = std::min(darkest, image_average(*frame.frame).sum() / 3); + warp.look(*frame.frame, now); } + const bool warped = !fade || warp.seen(); const bool talking = frame && dialog.detect(frame); const bool still = frame && previous && walk_screen_change(*previous.frame, *frame.frame) < WALK_TAP_BLOCKED_CHANGE; previous = frame; - const bool calm = !talking && overworld.detect(frame) && (!fade || darkest < FADE_DARKNESS); + const bool calm = !talking && overworld.detect(frame) && warped; calm_since = calm ? (calm_since == none ? now : calm_since) : none; if (calm && now - calm_since >= 15000ms){ - stream.log(std::format("[Story] {}: settled on calm overworld; darkest frame {:.0f}.", label, darkest)); + stream.log(std::format("[Story] {}: settled on calm overworld; {}.", label, warp.describe())); return; } - if (!talking && still && overworld.detect(frame) && (!fade || darkest < FADE_DARKNESS)){ + if (!talking && still && overworld.detect(frame) && warped){ quiet_since = quiet_since == none ? now : quiet_since; if (now - quiet_since >= 5000ms){ - stream.log(std::format("[Story] {}: settled; darkest frame {:.0f}.", label, darkest)); + stream.log(std::format("[Story] {}: settled; {}.", label, warp.describe())); return; } }else{ @@ -94,8 +121,8 @@ void settle(VideoStream& stream, ProControllerContext& context, Button button, c pbf_press_button(context, talking ? button : BUTTON_B, 80ms, 1200ms); } OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - fade && darkest >= FADE_DARKNESS - ? label + ": no fade within 120 s, so we are not where the step goes (map mismatch)." + fade && !warp.seen() + ? label + ": no fade or banner within 120 s, so we are not where the step goes (map mismatch)." : label + ": not back on a quiet overworld within 120 s.", stream); } @@ -140,25 +167,32 @@ class DarkFrom : public VisualInferenceCallback{ }; // How one hold toward a door ended: run_until()'s index (0 dark, 1 white, -// 2 a line, 3 a wild battle; -1 time up), and when the screen last went dark. +// 2 a line, 3 a wild battle, 4 the far map's banner; -1 time up), when the +// screen last went dark, and the banner read. struct DoorHoldEnd{ int ret; WallClock went_dark; + std::string banner; }; -DoorHoldEnd hold_into_door(VideoStream& stream, ProControllerContext& context, DpadPosition dpad, bool run, Milliseconds hold, Milliseconds dark_from){ +DoorHoldEnd hold_into_door(VideoStream& stream, ProControllerContext& context, DpadPosition dpad, bool run, Milliseconds hold, Milliseconds dark_from, const std::string& banner){ BlackScreenWatcher dark(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, 3 * FADE_DARKNESS, 60, BlackScreenWatcher::FinderType::PRESENT, 50ms); DarkFrom late_dark(dark, current_time() + dark_from); WhiteScreenWatcher white(COLOR_BLUE, {0.1, 0.1, 0.8, 0.8}, WhiteScreenWatcher::FinderType::PRESENT, 60ms); ShortDialogWatcher dialog(COLOR_YELLOW); BattleMenuWatcher battle(BattleType::STANDARD, COLOR_YELLOW); + LocationBannerWatcher far_banner(banner); + std::vector watchers{{late_dark}, {white}, {dialog}, {battle}}; + if (!banner.empty()){ + watchers.emplace_back(far_banner); + } const int ret = run_until(stream, context, [&](ProControllerContext& context){ if (run){ ssf_press_button(context, BUTTON_B, 0ms, hold, 0ms); } pbf_press_dpad(context, dpad, hold, 0ms); - }, {{late_dark}, {white}, {dialog}, {battle}}); - return {.ret = ret, .went_dark = late_dark.went_dark()}; + }, watchers); + return {.ret = ret, .went_dark = late_dark.went_dark(), .banner = ret == 4 ? far_banner.seen() : ""}; } // Wild battles a run into a door flees and runs on after. @@ -171,11 +205,13 @@ constexpr size_t DOOR_RUN_BATTLES = 3; // 2026-11-08: dark at 1.8 s, halfway down the mine's entrance hall). A wild // battle on the way is fled, and the run goes on for the time it had left: // only the running counts, up to the battle's fade. -bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction direction, bool run, Milliseconds timeout, Milliseconds dark_from){ +// The far map's banner `banner` shows after the fade, so it ends the run +// only when the fade went unseen (#268 slice 1). +WarpSeen run_into_door(VideoStream& stream, ProControllerContext& context, Direction direction, bool run, Milliseconds timeout, Milliseconds dark_from, const std::string& banner){ Milliseconds left = timeout; for (size_t battles = 0;; battles++){ const WallClock start = current_time(); - const DoorHoldEnd end = hold_into_door(stream, context, dpad_toward(direction), run, left, dark_from); + const DoorHoldEnd end = hold_into_door(stream, context, dpad_toward(direction), run, left, dark_from, banner); if (end.ret == 3){ const WallClock stopped = std::min(end.went_dark, current_time()); const Milliseconds ran = std::chrono::duration_cast(stopped - start) - ROUTE_START_DELAY; @@ -187,7 +223,7 @@ bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction if (battles < DOOR_RUN_BATTLES && left > 0ms){ continue; } - return false; + return {}; } if (end.ret == 0){ stream.log("[Story] run_into_door: black screen fade detected."); @@ -195,6 +231,8 @@ bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction stream.log("[Story] run_into_door: white screen fade detected."); }else if (end.ret == 2){ stream.log("[Story] run_into_door: dialog detected."); + }else if (end.ret == 4){ + stream.log("[Story] run_into_door: no fade seen, but the banner \"" + end.banner + "\" read."); }else if (end.went_dark != WallClock::max()){ // Dark only before dark_from: early, or the door's fade itself. stream.log(std::format("[Story] run_into_door: timed out; dark {} ms in, before dark_from {} ms.", @@ -202,7 +240,10 @@ bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction }else{ stream.log("[Story] run_into_door: timed out without detecting fade."); } - return end.ret == 0 || end.ret == 1; + return { + .fade = end.ret == 0 ? WarpFade::BLACK : end.ret == 1 ? WarpFade::WHITE : WarpFade::NONE, + .banner = end.banner, + }; } } @@ -232,14 +273,15 @@ void log_new_banner_read(VideoStream& stream, const std::string& read, std::stri } // Looks for the location banner `banner` for up to `wait`, and with -// `before` (the brightness before the tap) for the fade (tap_faded()). -// Logs each distinct banner read and how the wait ended: the Oreburgh Gate's -// entry missed its banner twice (lab-B, 2026-11-08 15:31 and 15:39) though -// a hand probe saw it 1.5 s after the fade, and nothing said why. -TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const std::string& banner, Milliseconds wait, std::optional before){ +// `fade` for the fade (fade_of_screen()). Logs each distinct banner read +// and how the wait ended: the Oreburgh Gate's entry missed its banner twice +// (lab-B, 2026-11-08 15:31 and 15:39) though a hand probe saw it 1.5 s +// after the fade, and nothing said why. +TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const std::string& banner, Milliseconds wait, bool fade){ const WallClock start = current_time(); const WallClock deadline = start + wait; std::string last_read; + LocationBannerReads reads; double darkest = 255; // Every 500 ms of a long wait (the one after a fade) a frame goes to // Screenshots/AutoStory/banner/, to see what the game showed. @@ -248,18 +290,17 @@ TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const while (true){ context.wait_for_all_requests(); const VideoSnapshot screen = stream.video().snapshot(); - if (!before && screen && current_time() >= next_frame){ + if (!fade && screen && current_time() >= next_frame){ keep_banner_frame(*screen.frame, folder, banner); next_frame += 500ms; } - const std::string read = screen ? read_location_banner(*screen.frame) : ""; + const std::string read = screen ? reads.read(*screen.frame, current_time()) : ""; log_new_banner_read(stream, read, last_read, banner, start); if (screen && location_banner_matches(read, banner)){ return TapLook::BANNER; } - const double brightness = brightness_of(screen); - darkest = std::min(darkest, brightness); - if (before && tap_faded(*before, brightness)){ + darkest = std::min(darkest, brightness_of(screen)); + if (fade && screen && fade_of_screen(*screen.frame) != WarpFade::NONE){ return TapLook::DARK; } if (current_time() >= deadline){ @@ -274,19 +315,6 @@ TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const } // namespace -// Black as the Gym's door fades (< 25), or a drop to dark: a look under -// FADE_DARKNESS is not a fade by itself, since a cave's floor is that dim -// (the Oreburgh Gate's about 46, lab-B 2026-11-08), but a fade into a cave -// from a lit street goes from about 120 to 45..64. -// TODO(#268 slice 3): stopgap. A uniform-screen fade watcher (the shared -// Black/WhiteScreen stddev test, as in upstream #1717) should replace this -// brightness drop; remove it once that watcher passes the Gate frames. -constexpr double TAP_FADE_BLACK = 25; -constexpr double TAP_FADE_DROP = 0.7; -bool tap_faded(double before, double after){ - return after < TAP_FADE_BLACK || (after < FADE_DARKNESS && after < before * TAP_FADE_DROP); -} - ConsoleStoryStepIO::ConsoleStoryStepIO(VideoStream& stream, ProControllerContext& context) : m_stream(stream) , m_context(context) @@ -316,48 +344,40 @@ bool ConsoleStoryStepIO::run_until_map(Direction direction, Milliseconds limit, return walk.stop == WalkStop::ARRIVED; } -bool ConsoleStoryStepIO::run_into_door(Direction direction, bool run, Milliseconds timeout, Milliseconds dark_from){ - return PokemonBDSP::run_into_door(m_stream, m_context, direction, run, timeout, dark_from); +WarpSeen ConsoleStoryStepIO::run_into_door(Direction direction, bool run, Milliseconds timeout, Milliseconds dark_from, const std::string& banner){ + return PokemonBDSP::run_into_door(m_stream, m_context, direction, run, timeout, dark_from, banner); } // A held walk can carry on past a fade that goes unseen: out of the Gym it // walked on south (r219g), and through the Oreburgh Gate's west mouth on // west into a pocket by Route 203's pond (r75). Taps during the fade are -// eaten. The banner before the first tap means we are through already: -// the walk before slid onto the warp (lab-B 2026-11-08 15:31). -// TODO(#268 slice 2): stopgap. The "through already" check sees only a -// banner still on screen; once walkers report the fade or banner they saw -// (WalkResult::warp), read that instead and remove this check. +// eaten, so a fade ends the taps; the banner after it is evidence, not +// required (#268 slice 1). The watch starts before the first tap: a walk +// before that slid onto the warp unseen may have left its banner up +// (lab-B 2026-11-08 15:31). std::optional ConsoleStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ const std::string& banner = story_banner_name(map); m_context.wait_for_all_requests(); - VideoSnapshot screen = m_stream.video().snapshot(); - if (screen && location_banner_matches(read_location_banner(*screen.frame), banner)){ + if (look_after_tap(m_stream, m_context, banner, 0ms, true) == TapLook::BANNER){ m_stream.log("[Banner] \"" + banner + "\" shows before the first tap: through already."); return 0; } for (size_t tap = 1; tap <= max_taps; tap++){ - const double before = brightness_of(screen); pbf_press_dpad(m_context, dpad_toward(direction), 160ms, 0ms); - TapLook look = look_after_tap(m_stream, m_context, banner, 1500ms, before); - const bool faded = look == TapLook::DARK; - if (faded){ - look = look_after_tap(m_stream, m_context, banner, 8000ms, std::nullopt); + const TapLook look = look_after_tap(m_stream, m_context, banner, 1500ms, true); + if (look == TapLook::DARK && look_after_tap(m_stream, m_context, banner, 8000ms, false) != TapLook::BANNER){ + m_stream.log("[Banner] a fade, no \"" + banner + "\" banner after it: counting the fade.", COLOR_ORANGE); } - if (look == TapLook::BANNER){ + if (look != TapLook::NOTHING){ m_context.wait_for(1000ms); return tap; } - if (faded){ - break; - } - screen = m_stream.video().snapshot(); } return std::nullopt; } -void ConsoleStoryStepIO::settle(Button button, const std::string& label, bool fade){ - PokemonBDSP::settle(m_stream, m_context, button, label, fade); +void ConsoleStoryStepIO::settle(Button button, const std::string& label, bool fade, const std::string& banner){ + PokemonBDSP::settle(m_stream, m_context, button, label, fade, banner); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h index a48007ee2f..6aa734d890 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h @@ -44,28 +44,27 @@ class StoryStepIO{ // JSON map's name) shows, for at most `limit`. Returns whether it showed. virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string& label) = 0; // Holds the D-pad toward a door (running with `run`) for `timeout` until - // the screen goes dark or a line shows. A dark screen in the first - // `dark_from` of running is not the door's fade, and a wild battle on the - // way is fled, the run going on for the time left. Returns whether it went dark. - virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) = 0; + // the screen goes dark or white, `banner` (a map's banner name, "" for + // none) reads, or a line shows. A dark screen in the first `dark_from` + // of running is not the door's fade, and a wild battle on the way is + // fled, the run going on for the time left. Returns what it saw of the + // warp: the fade or the banner, either one alone (#268 slice 1). + virtual WarpSeen run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), + Milliseconds dark_from = Milliseconds(0), const std::string& banner = "") = 0; // D-pad taps `direction` one at a time, each looked at, toward a door - // or cave mouth, until the fade (then no more taps) and the location - // banner of `map` (a JSON map's name), for at most `max_taps`. Returns - // the taps it took (0 if the banner shows before the first: through - // already), or nothing if no banner showed. + // or cave mouth, until its fade (fade_of(): uniform, so a dim cave floor + // is none) or the location banner of `map` (a JSON map's name), for at + // most `max_taps`; after a fade, no more taps. Either one alone is the + // way through. The watch starts before the first tap: a banner up then + // is 0 taps. Returns the taps it took, or nothing if neither showed. virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) = 0; // Presses through any text until the overworld is quiet; with `fade`, a - // fade must come first (a map change). Fails otherwise. - virtual void settle(Button button, const std::string& label, bool fade) = 0; + // warp must come first (a map change): a fade, or the banner `banner` + // ("" for a fade only). Fails otherwise. + virtual void settle(Button button, const std::string& label, bool fade, const std::string& banner) = 0; }; -// Whether a look after a tap toward a door or a cave mouth shows its fade, -// from its brightness `after` and that of the look before the tap, -// `before` (the mean of r, g and b, 0 to 255). -bool tap_faded(double before, double after); - - // The console. class ConsoleStoryStepIO : public StoryStepIO{ public: @@ -77,9 +76,10 @@ class ConsoleStoryStepIO : public StoryStepIO{ virtual void fight(const std::string& trainer) override; virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string& label) override; - virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) override; + virtual WarpSeen run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), + Milliseconds dark_from = Milliseconds(0), const std::string& banner = "") override; virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) override; - virtual void settle(Button button, const std::string& label, bool fade) override; + virtual void settle(Button button, const std::string& label, bool fade, const std::string& banner) override; private: VideoStream& m_stream; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index 8a0d50e0b9..f79162b485 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -7,12 +7,14 @@ #include #include #include +#include #include "Common/Cpp/Color.h" #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Pokemon/Navigation/Pokemon_MapData.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP_AutoStory_StoryExecutor.h" @@ -52,7 +54,7 @@ std::string label_of(const StoryStep& step){ CenterEntry run_into_center(StoryStepIO& io, bool run, const std::function& inside, const std::function& line_up){ - if (io.run_into_door(Direction::NORTH, run)){ + if (io.run_into_door(Direction::NORTH, run).any()){ return CenterEntry::FADED; } if (inside()){ @@ -67,6 +69,7 @@ void StoryWalkSteps::begin_attempt(const std::string& row){ // A row starts from its save: after the shoes' row, the save has them. m_can_run = row > std::string(RUNNING_SHOES_ROW); m_trainers.clear(); + m_warp = {}; } void StoryWalkSteps::turn(Direction direction){ @@ -105,10 +108,11 @@ Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }, label_of(step), {}, *costs, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK }; - const std::vector at = walk_route(m_io.route(), *maps, start, trainers, plan); + RouteEnd end = walk_route_to_warp(m_io.route(), *maps, start, trainers, plan); sights = std::move(trainers.sights); + m_warp = std::move(end.warp); std::vector local; - for (const TilePos& pos : at){ + for (const TilePos& pos : end.tiles){ const std::optional tile = story_to_local(*maps, goal.map, pos); if (!tile){ fail(m_io.route(), std::format("{}: the walk ended off {}.", step.name, goal.map)); @@ -119,6 +123,7 @@ Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep } Outcome StoryWalkSteps::route(RunState& state, const StoryStep& step){ + m_warp = {}; if (Pokemon::tiles_of(state.pose).empty()){ return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); } @@ -193,20 +198,38 @@ size_t taps_to_banner(const Pose& from, Direction direction){ // there; a banner before any tap means the walk before took us through. Outcome StoryWalkSteps::tap_to_banner(const Pose& from, const StoryStep& step){ const std::string map = step.pose_after ? step.pose_after->map : ""; + if (through_already(step)){ + return Pokemon::outcome_ok(); + } const size_t limit = taps_to_banner(from, step.direction); const std::optional taps = m_io.tap_to_banner(step.direction, map, limit); if (!taps){ - return Pokemon::outcome_failed("no_banner", std::format("{} in {} taps {}: through already, its banner gone?", + return Pokemon::outcome_failed("no_banner", std::format("no fade and no {} banner in {} taps {}", map, limit, direction_name(step.direction))); } if (*taps == 0){ log(std::format("[{}] {}: {}'s banner before any tap: through already.", m_row, step.name, map)); }else{ - log(std::format("[{}] {}: {}'s banner after {} taps {}.", m_row, step.name, map, *taps, direction_name(step.direction))); + log(std::format("[{}] {}: through to {} after {} taps {}.", m_row, step.name, map, *taps, direction_name(step.direction))); } return Pokemon::outcome_ok(); } +// The route before ran on through this step's warp (walk_route_to_warp()): +// the step is done, unless the banner it read names another map. +bool StoryWalkSteps::through_already(const StoryStep& step){ + const WarpSeen through = std::exchange(m_warp, {}); + if (!through.any()){ + return false; + } + const std::string map = step.pose_after ? step.pose_after->map : ""; + if (!through.banner.empty() && !location_banner_matches(through.banner, story_banner_name(map))){ + fail(m_io.route(), std::format("{}: the walk before went through a warp to \"{}\", not {}.", step.name, through.banner, map)); + } + log(std::format("[{}] {}: through already; the walk before saw {}.", m_row, step.name, describe(through))); + return true; +} + namespace{ // A run into a door: how long to hold, and for how long of it a dark screen // is not yet the door's fade (run_into_door()). @@ -352,6 +375,7 @@ Outcome StoryWalkSteps::counted_wall(const Pose& from, const StoryStep& step){ } Outcome StoryWalkSteps::legs(RunState& state, const StoryStep& step){ + m_warp = {}; if (step.variant == "counted_wall"){ return counted_wall(state.pose, step); } @@ -385,7 +409,7 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ if (walk.wild_battles > 0){ return Pokemon::outcome_failed("interrupted_step", step.name); } - m_io.settle(BUTTON_B, label_of(step), false); + m_io.settle(BUTTON_B, label_of(step), false, ""); return Pokemon::outcome_ok(); } // A step through a door: walk (or run) on until the screen goes dark, @@ -394,12 +418,19 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ // 00.01; Dawn's tour, 00.04). Without the fade, settle must see it itself // (r33 was outside, "no fade"). No separate turn tap first: at 1 tile // from the door, a 50 ms turn tap can step in before run_into_door() watches. + // A fade or the far map's banner is the way through, either one (#268 + // slice 1); with neither yet, settle() waits for one. if (step.pose_after && step.pose_after->map != state.pose.map){ + if (through_already(step)){ + m_io.settle(BUTTON_B, label_of(step), false, ""); + return Pokemon::outcome_ok(); + } + const std::string banner = story_arrival_banner(state.pose.map, step.pose_after->map); const DoorRun door = door_run(state.pose.map, state.pose, step.direction, m_can_run); - const bool faded = m_io.run_into_door(step.direction, m_can_run, door.timeout, door.dark_from); + const WarpSeen seen = m_io.run_into_door(step.direction, m_can_run, door.timeout, door.dark_from, banner); log(std::format("[{}] {}: {} through the door (timeout {} ms, dark from {} ms): {}.", m_row, step.name, - direction_name(step.direction), door.timeout.count(), door.dark_from.count(), faded ? "faded" : "no fade yet")); - m_io.settle(BUTTON_B, label_of(step), !faded); + direction_name(step.direction), door.timeout.count(), door.dark_from.count(), seen.any() ? describe(seen) : "nothing yet")); + m_io.settle(BUTTON_B, label_of(step), !seen.any(), banner); return Pokemon::outcome_ok(); } turn(step.direction); @@ -416,6 +447,7 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ } Outcome StoryWalkSteps::talk(RunState& state, const StoryStep& step){ + m_warp = {}; // Face whom we talk to: a route ends facing its last leg, not its goal // (r40 reached Mom facing north). They block the tile, so the tap only turns. if (const std::optional facing = Pokemon::facing_of(state.pose)){ @@ -432,6 +464,7 @@ Outcome StoryWalkSteps::talk(RunState& state, const StoryStep& step){ } Outcome StoryWalkSteps::mash(RunState& state, const StoryStep& step){ + m_warp = {}; // The step before may have played the scene already (a door step settles // its arrival scene), so its first line is not required. if (!m_io.route().dialog_within(15000ms, COLOR_CYAN)){ @@ -439,7 +472,7 @@ Outcome StoryWalkSteps::mash(RunState& state, const StoryStep& step){ } m_io.settle(step.variant == "a" ? BUTTON_A : BUTTON_B, label_of(step), step.pose_after && step.pose_after->map != state.pose.map && - story_plan_world(state.pose.map, step.pose_after->map) == nullptr); + story_plan_world(state.pose.map, step.pose_after->map) == nullptr, ""); if (m_row == RUNNING_SHOES_ROW && step.name == RUNNING_SHOES_STEP){ m_can_run = true; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index a7c4aad024..c284f97065 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -76,6 +76,7 @@ class StoryWalkSteps{ Pokemon::Outcome leg_to_dialogue(const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_map(const Pokemon::StoryStep& step); Pokemon::Outcome tap_to_banner(const Pokemon::Pose& from, const Pokemon::StoryStep& step); + bool through_already(const Pokemon::StoryStep& step); void turn(Pokemon::Direction direction); void log(const std::string& text); @@ -86,6 +87,9 @@ class StoryWalkSteps{ // in its tiles, from its first walk this attempt; all of them again at // each attempt. std::map> m_trainers; + // The warp the last route ran on through at its end (walk_route_to_warp()), + // for the step after it, which goes through that warp. + WarpSeen m_warp; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp index 4bacc207a3..fd86f221cc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp @@ -14,6 +14,7 @@ #include "Utils/PokemonBDSP_AutoStory_Indoors.h" #include "Utils/PokemonBDSP_AutoStory_Location.h" #include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "Utils/PokemonBDSP_AutoStory_Walk.h" #include "Actions/PokemonBDSP_AutoStory_Talks.h" #include "PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP_AutoStory_Walk_Tests.h" @@ -121,29 +122,33 @@ UnitTestResult test_door_fade(Logger&){ return true; } -// A tap step's fade is a real one: black, or a drop to dark from the look -// before the tap. The Oreburgh Gate's floor, about 46 before and after a -// tap inside it, is no fade: read as one, the tap into the Gate from -// Oreburgh, already through, waited 8 s for a banner gone (lab-B, -// 2026-11-08 15:31 to 15:54). -UnitTestResult test_tap_fade(Logger&){ +// A fade is uniform (fade_of(): the shared watchers' stddev test), dark or +// white; a floor is textured. The Oreburgh Gate's floor, about 46, is no +// fade: read as one, the tap into the Gate from Oreburgh, already +// through, waited 8 s for a banner gone (lab-B, 2026-11-08 15:31 to +// 15:54). A cave mouth's dim fade (45 to 64 measured) is one. The stddevs +// are a model; the Gate's frames on the console are to check them. +UnitTestResult test_fade_of(Logger&){ struct Case{ std::string name; - double before; - double after; - bool faded; + double brightness; + double stddev; + WarpFade fade; }; const std::vector cases{ - {.name = "inside the Gate, its floor", .before = 46, .after = 46, .faded = false}, - {.name = "inside the Gate, a darker patch", .before = 52, .after = 44, .faded = false}, - {.name = "on a street", .before = 120, .after = 112, .faded = false}, - {.name = "the street into the Gate's mouth, to black", .before = 120, .after = 8, .faded = true}, - {.name = "the street into a cave, a dim fade (45 to 64 measured)", .before = 120, .after = 60, .faded = true}, - {.name = "out of the Gate, from its floor to black", .before = 46, .after = 12, .faded = true}, + {.name = "inside the Gate, its floor", .brightness = 46, .stddev = 20, .fade = WarpFade::NONE}, + {.name = "Oreburgh's street at night", .brightness = 88, .stddev = 20, .fade = WarpFade::NONE}, + {.name = "a door's black", .brightness = 7, .stddev = 1, .fade = WarpFade::BLACK}, + {.name = "a cave mouth's dim fade", .brightness = 64, .stddev = 2, .fade = WarpFade::BLACK}, + {.name = "a grey screen, neither dark nor white", .brightness = 120, .stddev = 1, .fade = WarpFade::NONE}, + {.name = "a cave exit's white", .brightness = 250, .stddev = 1, .fade = WarpFade::WHITE}, + {.name = "a bright textured screen", .brightness = 250, .stddev = 20, .fade = WarpFade::NONE}, }; for (const Case& item : cases){ - if (tap_faded(item.before, item.after) != item.faded){ - return item.name + (item.faded ? ": no fade read." : ": read as a fade."); + const ImageStats stats(FloatPixel(item.brightness, item.brightness, item.brightness), FloatPixel(item.stddev, item.stddev, item.stddev), 1); + const WarpFade fade = fade_of(stats); + if (fade != item.fade){ + return item.name + ": " + warp_fade_name(fade) + ", expected " + warp_fade_name(item.fade) + "."; } } return true; @@ -315,7 +320,7 @@ const AutoStoryWalkCase AUTO_STORY_WALK_CASES[] = { .expectation = {}, }, { - .input = {"a tap into a door fades to black or drops to dark, not a dim floor (lab-B, 2026-11-08)", test_tap_fade}, + .input = {"a fade is uniform, dark or white; a dim floor is none (lab-B, 2026-11-08)", test_fade_of}, .expectation = {}, }, { diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp index 38630ad729..2be33f0f4c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -441,7 +441,9 @@ WalkResult GridSimRouteIO::walk_to_wall(const RouteWallWalk& walk){ const SimMove move = m_sim.hold(walk.direction, walk.limit, pace); m_notes.push_back(std::format("[Sim] {}: held {} to {} at {}.", walk.label, direction_name(walk.direction), sim_stop_name(move.stop), to_string(m_sim.player().pos))); - return {.stop = walk_stop(move.stop), .walked = move.time, .wild_battles = wild_battles, .moved_chunks = (size_t)(move.distance / SIM_TILE)}; + WalkResult result{.stop = walk_stop(move.stop), .walked = move.time, .wild_battles = wild_battles, .moved_chunks = (size_t)(move.distance / SIM_TILE)}; + result.warp.fade = move.stop == SimStop::WARP ? WarpFade::BLACK : WarpFade::NONE; + return result; } std::optional GridSimRouteIO::take_encounter(Direction direction, size_t tiles, size_t tap, const std::string& label){ @@ -484,6 +486,7 @@ WalkResult GridSimRouteIO::walk_taps(Direction direction, size_t tiles, const st result.moved_chunks += move.distance > 0 ? 1 : 0; if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ result.stop = walk_stop(move.stop); + result.warp.fade = move.stop == SimStop::WARP ? WarpFade::BLACK : WarpFade::NONE; }else if (still >= 2){ result.stop = WalkStop::BLOCKED; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 6901c3c2e5..30b7c55788 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -427,15 +427,15 @@ class WalkStepsIO : public StoryStepIO{ unsupported("a run onto " + map); return false; } - virtual bool run_into_door(Direction, bool, Milliseconds, Milliseconds) override{ + virtual WarpSeen run_into_door(Direction, bool, Milliseconds, Milliseconds, const std::string&) override{ unsupported("a run into a door"); - return false; + return {}; } virtual std::optional tap_to_banner(Direction, const std::string& map, size_t) override{ unsupported("taps to " + map + "'s banner"); return std::nullopt; } - virtual void settle(Button, const std::string& label, bool) override{ + virtual void settle(Button, const std::string& label, bool, const std::string&) override{ unsupported(label + "'s settle"); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp index 9dd3fd9b47..a0968abb0f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include "Common/Cpp/Exceptions.h" @@ -44,14 +45,22 @@ using Pokemon::TilePos; // Cases the program fails today, with what is to fix each. const std::map KNOWN_FAILING{ - {"01.05 old walk slides onto the Gate's west mouth, dim fade, banner gone", "#268 slice 2: walkers report warps"}, - {"01.05 old walk slides onto the Gate's west mouth, black fade", "#268 slice 2: walkers report warps"}, - {"01.05 old walk slides onto the Gate's west mouth, white fade", "#268 slices 2 and 3: a fade watcher that tells white from a battle"}, {"01.05 through_the_gate is one run west", "planner: goal kinds and ms costs (PLANNER_DESIGN.md)"}, - {"any one missed fade or banner from 00.00 to 01.11: every row still passes", "#268 slice 1: door arrival = fade or banner"}, + {"any one missed fade or banner from 00.00 to 01.11: every row still passes", + "a third signal where a warp gives one (ONE_SIGNAL_STEPS): position (PLANNER_DESIGN.md 2, 4)"}, {"01.08 with Route 204's youngster wandering (12..14, 2)", "planner: one recovery rule, a sidestep round a wanderer (PLANNER_DESIGN.md 4, 7)"}, }; +// Warps that give one signal only (#268 slice 1: door = fade or banner), so +// a miss there leaves nothing to go on: a fade and no banner (stairs, into +// a building, between the mine's floors), or a banner and no fade (an open +// border crossed by run_until_map()). +const std::set ONE_SIGNAL_STEPS{ + "00.01 down_the_stairs", "00.01 into_barrys_house", "00.01 up_barrys_stairs", "00.01 down_barrys_stairs", + "00.04 into_the_house", "00.05 into_the_school", "01.03 into_the_coal_room", "01.03 up_to_the_hall", + "00.04 to_route_201", "01.10 into_floaroma", +}; + // The table's step `name` in row `row`. const StoryStep& table_step(const std::string& row, const std::string& name){ for (const StoryCheckpoint& checkpoint : story_checkpoints()){ @@ -117,10 +126,10 @@ UnitTestResult gate_plan_one_run(Logger& logger){ } // Each fade and each banner the clean run looks for, missed alone: the -// row it falls in must still pass. A door step accepts only its fade -// today, so a missed fade there fails a real arrival (#268's Monte Carlo, -// 19/20 on 01.05). -UnitTestResult every_single_miss(Logger& logger){ +// row it falls in must still pass, but for a miss in one of `skip`'s steps. +// A door step once accepted only its fade, so a missed fade there failed a +// real arrival (#268's Monte Carlo, 19/20 on 01.05). +UnitTestResult every_single_miss(Logger& logger, const std::set& skip){ SimExecutor clean(logger); if (!run_rows_on(clean, logger, {.from = "00.00", .to = "01.11"}).completed){ return "the run fails without misses: " + clean.result().error; @@ -134,9 +143,12 @@ UnitTestResult every_single_miss(Logger& logger){ } SimMisses misses{.fade = {}, .banner = {}}; (fade ? misses.fade : misses.banner) = index - (fade ? rows[k].fades : rows[k].banners); - const std::string stopped = run_case(logger, rows[k].row, rows[k].row, misses, {}); - if (!stopped.empty()){ - failed.push_back(std::format("{} {} missed: {}", fade ? "fade" : "banner", index, stopped)); + SimExecutor executor(logger, misses); + if (!run_rows_on(executor, logger, {.from = rows[k].row, .to = rows[k].row}).completed + && !skip.contains(executor.result().failed_step) + ){ + failed.push_back(std::format("{} {} missed: stopped in {}: {}", fade ? "fade" : "banner", index, + executor.result().failed_step, executor.result().error)); } }; for (size_t i = 0; i < clean.misses().fades; i++){ @@ -154,8 +166,9 @@ UnitTestResult every_single_miss(Logger& logger){ // Oreburgh's street at night (88, game clock 00:25; 104 by day, r74), the // Gate's dim floor (46) and a cave mouth's dim fade (45 to 64): the tap -// steps judge their fades with tap_faded(), which took the Gate's floor -// for a fade under the old "brightness under 75" (lab-B 2026-11-08). +// steps judge their fades with fade_of(): uniform, so a textured floor +// is none. The old "brightness under 75" took the Gate's floor for a fade +// (lab-B 2026-11-08). UnitTestResult night_and_dim_floors(Logger& logger){ SimWorldKnobs knobs{ .floor = {{"OreburghCity", 88}, {"Route203", 88}, {"OreburghGate", 46}}, @@ -253,7 +266,12 @@ const FailureCase AUTO_STORY_FAILURE_CASES[] = { return gate_old_walk_slides(logger, SimFade::WHITE, true); }}, .expectation = {}}, {.input = {"01.05 through_the_gate is one run west", gate_plan_one_run}, .expectation = {}}, - {.input = {"any one missed fade or banner from 00.00 to 01.11: every row still passes", every_single_miss}, .expectation = {}}, + {.input = {"any one missed fade or banner from 00.00 to 01.11: every row still passes", [](Logger& logger){ + return every_single_miss(logger, {}); + }}, .expectation = {}}, + {.input = {"any one missed fade or banner at a warp that shows both: its row still passes", [](Logger& logger){ + return every_single_miss(logger, ONE_SIGNAL_STEPS); + }}, .expectation = {}}, {.input = {"01.02 to 01.05 at night, the Gate's dim floor", night_and_dim_floors}, .expectation = {}}, {.input = {"01.03 Roark's first line 7 s after the A press", roark_speaks_late}, .expectation = {}}, {.input = {"01.03 with Oreburgh's people wandering (the pokefan on 45, 37..39)", [](Logger& logger){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index c535b38c60..835ee14d1f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -29,6 +29,10 @@ using Pokemon::StoryStepKind; using Pokemon::TilePos; +ImageStats sim_screen(double brightness, double stddev){ + return ImageStats(FloatPixel(brightness, brightness, brightness), FloatPixel(stddev, stddev, stddev), 1); +} + // A hold until something stops us. A door stops it at the fade, which // fails the step; a fade missed lets the hold go on past the mouth (r81's // timed walk south out of the Ravaged Path, onto Route 204's cliff). @@ -74,12 +78,12 @@ double SimStoryStepIO::floor_here() const{ return SIM_FLOOR; } -// D-pad taps, each looked at, until the fade and then the banner (the -// console's ConsoleStoryStepIO::tap_to_banner()): none if the banner shows -// before the first. Each look stands still, so a banner on the far side -// reads at once. A look the program's tap_faded() takes for the fade ends -// the taps, banner or not: a warp's fade, or a dim floor read as one; with -// the fade missed the next look still sees the banner. +// D-pad taps, each looked at, until the fade or the banner (the console's +// ConsoleStoryStepIO::tap_to_banner()): none if the banner shows before +// the first. Each look stands still, so a banner on the far side reads at +// once. A look the program's fade_of() takes for a fade ends the taps: a +// warp's fade, or a floor read as one; with the fade missed the look still +// sees the banner. std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ if (m_misses.through == m_misses.tap_steps++){ m_misses.missed = true; @@ -92,23 +96,22 @@ std::optional SimStoryStepIO::tap_to_banner(Direction direction, const s } bool crossed = false; for (size_t tap = 1; tap <= max_taps; tap++){ - const double before = floor_here(); const SimMove move = m_sim.tap(direction, 160ms, false); if (move.stop == SimStop::DIALOG){ return std::nullopt; } - double look = floor_here(); + ImageStats look = sim_screen(floor_here(), SIM_FLOOR_STDDEV); if (move.stop == SimStop::WARP){ const auto fade = m_knobs.fade_into.find(map); - look = fade_missed() ? look : fade == m_knobs.fade_into.end() ? SIM_DOOR_FADE : fade->second; + if (!fade_missed()){ + look = sim_screen(fade == m_knobs.fade_into.end() ? SIM_DOOR_FADE : fade->second, SIM_FADE_STDDEV); + } crossed = m_far_side(); } - if (crossed && on_map(map) && !banner_missed()){ + const bool banner = crossed && on_map(map) && !banner_missed(); + if (banner || fade_of(look) != WarpFade::NONE){ return tap; } - if (tap_faded(before, look)){ - return std::nullopt; - } } return std::nullopt; } @@ -127,9 +130,11 @@ WalkResult SimKnobRouteIO::walk_taps(Direction direction, size_t tiles, const st return result; } -// The taps past the leg's end. Onto a warp the walk sees what the fade -// looks like to its watchers: a black fade ends it (TRANSITION), a white -// one is a wild battle to it, a dim one nothing. +// The taps past the leg's end. Onto a warp the walk sees the fade as the +// program's fade_of() judges it, the walk's watchers' test: a fade ends +// it (TRANSITION), a white one too, as no battle follows it. The walk ends +// at the fade, before the banner shows (about 1.5 s after it), so it +// reads none. WalkResult SimKnobRouteIO::slide_on(const SimSlide& slide, WalkResult result){ m_misses.slid = true; for (size_t tap = 0; tap < slide.tiles; tap++){ @@ -141,10 +146,10 @@ WalkResult SimKnobRouteIO::slide_on(const SimSlide& slide, WalkResult result){ note("[Sim] slid onto a warp to " + Pokemon::to_string(slide.far) + ".", RouteNote::LOG); m_cross(slide.far); m_misses.banner_up = slide.banner_up ? slide.far.map : ""; - if (slide.fade == SimFade::BLACK){ + const double brightness = slide.fade == SimFade::BLACK ? SIM_DOOR_FADE : slide.fade == SimFade::DIM ? SIM_DIM_FADE : SIM_WHITE_FADE; + result.warp.fade = fade_of(sim_screen(brightness, SIM_FADE_STDDEV)); + if (result.warp.fade != WarpFade::NONE){ result.stop = WalkStop::TRANSITION; - }else if (slide.fade == SimFade::WHITE){ - result.wild_battles++; } return result; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index ec681f290e..e20575b083 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -23,6 +23,7 @@ #include #include "Common/Cpp/Logging/AbstractLogger.h" #include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/ImageTools/ImageStats.h" #include "Pokemon/AutoStory/Pokemon_StorySegments.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" @@ -63,16 +64,17 @@ struct SimMisses{ std::string banner_up = {}; }; -// How a warp's fade looks to the console's watchers (#268's design note). +// How a warp's fade looks on the screen (#268's design note); the +// program's fade_of() judges it, as the walk's watchers do. enum class SimFade{ - // A door's: near black. Every watcher of a black screen sees it. + // A door's: near black (SIM_DOOR_FADE). BLACK, - // A cave mouth's: dim, not black. A walk's strict black watcher (rgb - // sum 100, stddev 10; WalkRunner::hold()) misses it and the walk goes - // on (the Oreburgh Gate, lab-B 2026-11-08 16:03). + // A cave mouth's: dim, not black (SIM_DIM_FADE). The walk's old strict + // black watcher (rgb sum 100) missed it and the walk went on (the + // Oreburgh Gate, lab-B 2026-11-08 16:03). DIM, - // A cave exit's white: a walk's encounter-flash watcher reads it as a - // wild battle. + // A cave exit's white. The walk's old encounter-flash watcher read it + // as a wild battle. WHITE, }; @@ -96,8 +98,9 @@ struct SimWorldKnobs{ std::vector slides = {}; // The mean brightness (0 to 255) of a map's floor, by JSON map name, and // of the fade into a map; a tap step judges its fade from these with the - // program's tap_faded(). Unset: 104 (Oreburgh's street by day) and 7 - // (a door's black). + // program's fade_of(), a floor textured, a fade uniform (SIM_FLOOR_STDDEV, + // SIM_FADE_STDDEV). Unset: 104 (Oreburgh's street by day) and 7 (a + // door's black). std::map floor = {}; std::map fade_into = {}; // People with a wander box on their map walk it, a step tried every 2 s. @@ -150,6 +153,17 @@ constexpr Milliseconds SIM_FALSE_DARK = Milliseconds(1800); constexpr double SIM_FLOOR = 104; // Brightness of a fade where SimWorldKnobs does not say: a door's black (by hand: 7). constexpr double SIM_DOOR_FADE = 7; +// Brightness of a cave mouth's dim fade (45 to 64 measured). +constexpr double SIM_DIM_FADE = 55; +// Brightness of a cave exit's white fade. +constexpr double SIM_WHITE_FADE = 250; +// The spread (stddev a channel) of a fade: uniform. A model, not measured +// on the console. +constexpr double SIM_FADE_STDDEV = 1; +// The spread of a floor, which the game draws with texture. A model too. +constexpr double SIM_FLOOR_STDDEV = 20; +// The screen's middle as fade_of() reads it: `brightness` a channel, `stddev` a channel. +ImageStats sim_screen(double brightness, double stddev); // What a run on the simulation did. struct SimRun{ @@ -198,24 +212,32 @@ class SimStoryStepIO : public StoryStepIO{ } virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; - virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0)) override{ + // A door's fade stops the run; with the fade missed, the run goes on + // holding and sees the far map's `banner` show after it, if it has one + // (story_arrival_banner(): the sim's maps have no banners of their own). + virtual WarpSeen run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), + Milliseconds dark_from = Milliseconds(0), const std::string& banner = "") override{ const SimPace pace = run ? SimPace::RUN : SimPace::WALK; if (false_dark() && dark_from <= SIM_FALSE_DARK && SIM_FALSE_DARK < timeout){ m_sim.hold(direction, SIM_FALSE_DARK, pace); - return true; + return {.fade = WarpFade::BLACK}; } - const bool warped = m_sim.hold(direction, timeout, pace).stop == SimStop::WARP; - if (warped && fade_missed()){ - m_misses.fade_unseen = true; - return false; + if (m_sim.hold(direction, timeout, pace).stop != SimStop::WARP){ + return {}; } - return warped; + if (!fade_missed()){ + return {.fade = WarpFade::BLACK}; + } + m_misses.fade_unseen = true; + return {.banner = !banner.empty() && !banner_missed() ? banner : ""}; } // A scene may take us to another map (Mom walks us out, 00.04): with a // dialogue open the stub scene plays it. Otherwise only a door fades. // A fade missed on the way in stays missed: it was over before settle() - // looked, which then fails as it does on the console after 120 s. - virtual void settle(Button, const std::string& label, bool fade) override{ + // looked, which then fails as it does on the console after 120 s. The + // run before looked for the banner (run_into_door()), so settle() sees + // none here. + virtual void settle(Button, const std::string& label, bool fade, const std::string&) override{ const bool scene_fades = m_sim.player().dialog && m_far_side(); if (fade && ((!m_sim.player().warped && !scene_fades) || m_misses.fade_unseen)){ m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp index df31791552..9556ec5018 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.cpp @@ -6,11 +6,13 @@ #include #include +#include #include #include "CommonFramework/ImageTools/ImageBoxes.h" #include "CommonFramework/ImageTools/ImageStats.h" #include "CommonFramework/ImageTypes/ImageRGB32.h" #include "CommonFramework/Language.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" #include "CommonTools/Images/ImageFilter.h" #include "CommonTools/OCR/OCR_RawTesseractOCR.h" #include "PokemonBDSP_AutoStory_Location.h" @@ -143,6 +145,47 @@ bool location_banner_matches(const std::string& read, const std::string& expecte } +std::string LocationBannerReads::read(const ImageViewRGB32& screen, WallClock now){ + if (!location_banner_showing(screen)){ + m_reads = 0; + return ""; + } + if (m_reads >= 2 || (m_reads == 1 && now - m_first < std::chrono::milliseconds(300))){ + return ""; + } + if (m_reads == 0){ + m_first = now; + } + m_reads++; + return read_location_banner(screen); +} + +LocationBannerWatcher::LocationBannerWatcher(std::string expected) + : VisualInferenceCallback("LocationBannerWatcher") + , m_expected(std::move(expected)) +{} +void LocationBannerWatcher::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_CYAN, LOCATION_BANNER_WHITE); +} +bool LocationBannerWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + const std::string read = m_reads.read(frame, timestamp); + if (read.empty() || m_matched){ + return m_matched; + } + m_last_read = read; + if (!m_expected.empty() && location_banner_matches(read, m_expected)){ + m_seen = read; + m_matched = true; + return true; + } + if (m_seen.empty() && m_expected.empty()){ + m_seen = read; + } + return false; +} + + + } // namespace PokemonBDSP } // namespace NintendoSwitch } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h index cb4e4c8626..d2baff6d70 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h @@ -11,8 +11,10 @@ #define PokemonAutomation_PokemonBDSP_AutoStory_Location_H #include +#include "Common/Cpp/Time.h" #include "CommonFramework/Language.h" #include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -63,6 +65,47 @@ std::string read_save_screen_location(const ImageViewRGB32& screen); // read as Route 202. bool location_banner_matches(const std::string& read, const std::string& expected); +// Reads the location banner at most twice per showing: when its box shows, +// and once more 300 ms later in case the first frame caught it sliding in. +// The box test runs on every frame; OCR (tens of ms) only then (#268's cost +// rule: the old look read every poll while the box showed, 30 to 40 reads). +class LocationBannerReads{ +public: + // The banner's text if this frame was read, "" if not. + std::string read(const ImageViewRGB32& screen, WallClock now); + +private: + size_t m_reads = 0; + WallClock m_first = WallClock::min(); +}; + +// Watches the location banner through an action. With `expected` (a map's +// banner name) it stops the action when that banner reads; without, it +// only keeps the first banner read. +class LocationBannerWatcher : public VisualInferenceCallback{ +public: + explicit LocationBannerWatcher(std::string expected = ""); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + // The expected banner if it read, else the first banner read; "" if none. + const std::string& seen() const{ + return m_seen; + } + // The last banner read, for the log. + const std::string& last_read() const{ + return m_last_read; + } + +private: + std::string m_expected; + LocationBannerReads m_reads; + std::string m_seen; + std::string m_last_read; + bool m_matched = false; +}; + } // namespace PokemonBDSP } // namespace NintendoSwitch diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index b2f2d0354f..5a8263eeb2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -69,23 +69,6 @@ void log_leg_done(RouteIO& io, const StoryWorld& maps, const std::string& label, assumed ? EndBasis::ASSUMED : EndBasis::WALKED, assumed ? std::to_string(wild_battles) + " wild battle(s) on the way" : ""), RouteNote::LOG); } -// The tiles the player passes when walking `tiles` tiles from `from`, the -// first one after `from` first. Stops early where the player is stopped. -std::vector leg_path(const StoryWorld& grid, TilePos from, Direction direction, size_t tiles){ - std::vector path; - size_t travelled = 0; - while (travelled < tiles){ - const std::optional next = step(grid, from, direction); - if (!next){ - break; - } - travelled += std::abs(next->x - from.x) + std::abs(next->y - from.y); - from = *next; - path.push_back(from); - } - return path; -} - // The map all of `tiles` are on, or empty if they are on several or none. std::string map_of(const StoryWorld& maps, const std::vector& tiles){ std::string name; @@ -195,7 +178,10 @@ size_t min_tiles_at_wall(size_t expected_tiles){ enum class LegNext{ NEXT_LEG, REPLAN, + ARRIVED_EARLY, // through a warp at the leg's end (walk_route_to_warp()) }; +// How far past a leg's end a walk that ran on may have gone. +constexpr size_t WARP_SLIDE_TILES = 2; // One planned leg as it is walked: where it goes, and the location // banners read on the way. @@ -246,7 +232,7 @@ class RouteWalker{ , m_plan(plan) {} - std::vector run(std::vector from); + RouteEnd run(std::vector from); private: std::vector plan_legs() const; @@ -290,11 +276,12 @@ class RouteWalker{ // Every banner read on the way, to check the map we arrive on against. std::vector m_all_banners; std::string m_map_start; + WarpSeen m_warp; // Dialogue the map does not explain, so far on this route. size_t m_unexplained_talks = 0; }; -std::vector RouteWalker::run(std::vector from){ +RouteEnd RouteWalker::run(std::vector from){ // Tiles to avoid are ground the game lets us walk on (a trainer's line // of sight), so they are off the map, not walls: a leg must not end // "at" one, or the walk would run on through it. @@ -309,12 +296,12 @@ std::vector RouteWalker::run(std::vector from){ const std::vector legs = plan_legs(); m_io.note(m_plan.label + ": " + std::to_string(legs.size()) + " legs planned", RouteNote::STATUS); log_plan(m_io, m_maps, m_plan.label, m_from, legs); - bool replanned = false; - for (size_t number = 1; number <= legs.size() && !replanned; number++){ - replanned = walk_leg(legs[number - 1], number, legs.size()) == LegNext::REPLAN; + LegNext next = LegNext::NEXT_LEG; + for (size_t number = 1; number <= legs.size() && next == LegNext::NEXT_LEG; number++){ + next = walk_leg(legs[number - 1], number, legs.size()); } - if (!replanned){ - return arrive(); + if (next != LegNext::REPLAN){ + return {next == LegNext::ARRIVED_EARLY ? m_from : arrive(), m_warp}; } } fail(m_io, m_plan.label + ": too many plans."); @@ -356,10 +343,15 @@ LegNext RouteWalker::walk_leg(const PlannedLeg& planned, size_t number, size_t c return next; } m_facing = planned.leg.direction; - check_banners(walk); if (walk.result.stop == WalkStop::TRANSITION){ - fail(m_io, walk.label + ": unexpected transition."); + if (!warp_within(m_grid, m_from, planned.leg.direction, planned.leg.tiles + WARP_SLIDE_TILES)){ + fail(m_io, walk.label + ": unexpected transition."); + } + m_io.note("[Route] " + walk.label + ": through the warp at its end (" + describe(walk.result.warp) + "); handing over.", RouteNote::WARNING); + m_warp = walk.result.warp; + return LegNext::ARRIVED_EARLY; } + check_banners(walk); return after_leg(walk); } @@ -857,6 +849,17 @@ std::vector walk_route( std::vector walk_route( RouteIO& io, const StoryWorld& maps, std::vector from, RouteTrainers& trainers, const RouteWalkPlan& plan +){ + RouteEnd end = walk_route_to_warp(io, maps, std::move(from), trainers, plan); + if (end.warp.any()){ + fail(io, plan.label + ": unexpected transition."); + } + return std::move(end.tiles); +} + +RouteEnd walk_route_to_warp( + RouteIO& io, const StoryWorld& maps, std::vector from, + RouteTrainers& trainers, const RouteWalkPlan& plan ){ return RouteWalker(io, maps, trainers, plan).run(std::move(from)); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h index 0f6efccc0a..777019cfdd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h @@ -71,6 +71,21 @@ std::vector walk_route( RouteTrainers& trainers, const RouteWalkPlan& plan ); +// Where walk_route_to_warp() ended: on `tiles`, or through a warp it saw +// (`warp`), with `tiles` where the leg that went through began. +struct RouteEnd{ + std::vector tiles; + WarpSeen warp = {}; +}; +// walk_route(), but a fade on a leg with a warp at most a tile or two past +// its end ends the walk there, as arrived early: the walk ran on onto the +// warp (01.05's Oreburgh Gate, lab-B 2026-11-08), and the step after goes +// through it (#268 slice 2). Any other fade fails as in walk_route(). +RouteEnd walk_route_to_warp( + RouteIO& io, const StoryWorld& maps, std::vector from, + RouteTrainers& trainers, const RouteWalkPlan& plan +); + // The corners of a line a human walked, and the costs to plan each // stretch with. struct WaypointWalkPlan{ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp index fdc6357556..f1a18078fb 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp @@ -9,6 +9,7 @@ #include #include "Common/Cpp/Exceptions.h" #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" #include "CommonFramework/ImageTools/ImageDiff.h" #include "CommonFramework/ImageTypes/ImageRGB32.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" @@ -20,6 +21,7 @@ #include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" #include "PokemonBDSP/Inference/PokemonBDSP_TransitionWatchers.h" #include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP_AutoStory_Walk.h" namespace PokemonAutomation{ @@ -40,6 +42,37 @@ const char* walk_stop_name(WalkStop stop){ 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 "?"; +} + +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)))); +} + +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; +} + double walk_screen_change(const ImageViewRGB32& before, const ImageViewRGB32& after){ // Small copies: only the whole-view scroll matters, not detail. return ImageMatch::pixel_RMSD(before.scale_to(192, 108), after.scale_to(192, 108)); @@ -80,7 +113,7 @@ DpadPosition dpad_toward(JoystickPosition stick){ bool black_screen_was_battle(VideoStream& stream, ProControllerContext& context){ BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); BattleDialogWatcher battle_dialog(COLOR_YELLOW); - BlackScreenWatcher gone(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, 100, 10, + BlackScreenWatcher gone(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, FADE_MAX_DARK_SUM, FADE_MAX_STDDEV_SUM, BlackScreenWatcher::FinderType::GONE, 500ms); const int ret = wait_until(stream, context, 10s, {{battle_menu}, {battle_dialog}, {gone}}); if (ret == 2){ @@ -95,12 +128,16 @@ bool black_screen_was_battle(VideoStream& stream, ProControllerContext& context) // A grass encounter opens with a leaf animation, neither white nor black, and // shows the battle's text box a few seconds later. After a change of the // whole screen that walking cannot make, wait for the battle to show. -bool battle_follows(VideoStream& stream, ProControllerContext& context){ +bool battle_follows(VideoStream& stream, ProControllerContext& context, Milliseconds wait = 5000ms){ BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); BattleDialogWatcher battle_dialog(COLOR_YELLOW); - return wait_until(stream, context, 5s, {{battle_menu}, {battle_dialog}}) >= 0; + return wait_until(stream, context, wait, {{battle_menu}, {battle_dialog}}) >= 0; } +// After a white flash: an encounter's, if its battle shows; else a cave +// exit's white fade (#268 slice 3), which the walk once fled as a battle. +constexpr Milliseconds WHITE_FLASH_BATTLE_WAIT = 8000ms; + } // namespace // A step in tall grass that was started before the stick was released still @@ -250,19 +287,24 @@ class WalkUntil{ } private: + // The banner watcher only looks (m_banner keeps the first read); a + // fade ends the chunk: dark (fade_of()'s uniform test, a cave's dim + // fade too) or the white of an encounter or a cave exit. int hold(Milliseconds chunk){ WhiteScreenOverWatcher encounter_flash(COLOR_YELLOW, {0.1, 0.1, 0.8, 0.8}); - BlackScreenWatcher black(COLOR_RED); + BlackScreenWatcher black(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, FADE_MAX_DARK_SUM, FADE_MAX_STDDEV_SUM); BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); ShortDialogWatcher dialog(COLOR_YELLOW); BattleDialogWatcher battle_dialog(COLOR_YELLOW); - return run_until( + const int ret = run_until( m_stream, m_context, [&](ProControllerContext& context){ press(context, chunk); }, - {{encounter_flash}, {black}, {battle_menu}, {dialog}, {battle_dialog}} + {{encounter_flash}, {black}, {battle_menu}, {dialog}, {battle_dialog}, {m_banner}} ); + m_result.warp.banner = m_banner.seen(); + return ret; } void press(ProControllerContext& context, Milliseconds chunk) const{ @@ -286,10 +328,13 @@ class WalkUntil{ // The watchers: 0 the encounter flash, 1 black, 2 the battle menu, 3 a // dialogue, 4 the battle's text box. ChunkVerdict after_watchers(int ret){ - bool battle = ret == 0 || ret == 2 || ret == 4; - if (ret == 1){ - battle = black_screen_was_battle(m_stream, m_context); + bool battle = ret == 2 || ret == 4; + if (ret == 0 || ret == 1){ + battle = ret == 0 + ? battle_follows(m_stream, m_context, WHITE_FLASH_BATTLE_WAIT) + : black_screen_was_battle(m_stream, m_context); if (!battle){ + m_result.warp.fade = ret == 0 ? WarpFade::WHITE : WarpFade::BLACK; return {ChunkNext::STOP, WalkStop::TRANSITION}; } } @@ -422,6 +467,7 @@ class WalkUntil{ size_t m_unchanged = 0; size_t m_chunks = 0; double m_largest = 0; + LocationBannerWatcher m_banner; }; WalkResult walk_until_spec( @@ -487,7 +533,7 @@ WalkResult walk_for( WalkResult result{WalkStop::LIMIT, duration, 0}; context.wait_for_all_requests(); WhiteScreenOverWatcher encounter_flash(COLOR_YELLOW, {0.1, 0.1, 0.8, 0.8}); - BlackScreenWatcher black(COLOR_RED); + BlackScreenWatcher black(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, FADE_MAX_DARK_SUM, FADE_MAX_STDDEV_SUM); BattleMenuWatcher battle_menu(BattleType::STANDARD, COLOR_YELLOW); ShortDialogWatcher dialog(COLOR_YELLOW); BattleDialogWatcher battle_dialog(COLOR_YELLOW); @@ -507,6 +553,7 @@ WalkResult walk_for( battle = black_screen_was_battle(stream, context); if (!battle){ result.stop = WalkStop::TRANSITION; + result.warp.fade = WarpFade::BLACK; } } if (battle){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h index f83f45ce07..311e3c784e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h @@ -14,6 +14,7 @@ #include #include #include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTools/ImageStats.h" #include "CommonFramework/ImageTypes/ImageViewRGB32.h" #include "CommonFramework/Tools/VideoStream.h" #include "Controllers/Joystick.h" @@ -33,7 +34,7 @@ using WildBattleEscape = std::function; // hold where we are. enum class WalkOrigin{ CURRENT_LEG, MAY_PRECEDE_LEG }; +// How a screen's fade looks (#268's design note, slice 3). +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); + +// 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 (the Oreburgh Gate's, 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); + +// 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(); + } +}; +// How it was seen, for the log: a black fade, banner "Route 203". +std::string describe(const WarpSeen& seen); + // Result metrics and terminal state returned by automated walking execution. struct WalkResult{ WalkStop stop; @@ -59,6 +99,9 @@ struct WalkResult{ // taps into Taylor's freeze). size_t moved_chunks = 0; WalkOrigin origin = WalkOrigin::CURRENT_LEG; + // The fade that ended a TRANSITION, and any location banner read on + // the way (#268 slice 2: walkers report warps). + WarpSeen warp = {}; }; // Holds the left stick at `stick` until one of the WalkStop events. Wild battles on From 24384dee2c2e1f7029a39ee06bcf0dcb04371bee Mon Sep 17 00:00:00 2001 From: Di Fan <26423504+dayfine@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:24:21 -0800 Subject: [PATCH 073/166] BDSP AutoStory: talk-over from events, one rule for scenes and post-battle speeches (#268 slice 4) (#289) settle(), settle_after_battle(), talk_or_fight()'s loop and confirm_battle_overworld() each judged the end of a talk their own way: 5 s still, 5 s or 4 s with no still check, 1.5 s for Roark's speech. A scene with no box for a few seconds after a battle (someone walking off, the badge fanfare) read as over, and the Potion's menu opened under the next line. TalkOver judges it from looks (box, overworld, still, fade_of() fade, banner, battle start): B while quiet until 5 s of still, box-free overworld (15 s if it never goes still), only after the warp a step needs; never A off a box. talk_over() drives it on the console; all four loops use it, and Roark's extra finish_dialogue() goes. The story sim plays scripted scenes (SimWorldKnobs::scenes) through the same judge in settle() and after a battle step. Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss Co-authored-by: Claude Opus 5.5 --- .../Actions/PokemonBDSP_AutoStory_Battle.cpp | 34 +--- .../Actions/PokemonBDSP_AutoStory_Battle.h | 6 +- .../PokemonBDSP_AutoStory_Events_Oreburgh.cpp | 8 +- .../PokemonBDSP_AutoStory_TalkOver.cpp | 156 ++++++++++++++++++ .../Actions/PokemonBDSP_AutoStory_TalkOver.h | 137 +++++++++++++++ .../Actions/PokemonBDSP_AutoStory_Talks.cpp | 89 ++-------- .../Actions/PokemonBDSP_AutoStory_Talks.h | 6 +- .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 100 ++--------- ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 72 ++++++++ .../PokemonBDSP_AutoStory_StorySim.cpp | 85 ++++++++++ .../PokemonBDSP_AutoStory_StorySim.h | 47 ++++-- SerialPrograms/cmake/SourceFiles.cmake | 2 + 12 files changed, 527 insertions(+), 215 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.cpp index 737834e023..e177f711a6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.cpp @@ -19,7 +19,6 @@ #include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" #include "CommonTools/Async/InferenceRoutines.h" #include "CommonTools/OCR/OCR_RawTesseractOCR.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" #include "PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h" @@ -30,6 +29,7 @@ #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP_AutoStory_Bag.h" #include "PokemonBDSP_AutoStory_BattleMoves.h" +#include "PokemonBDSP_AutoStory_TalkOver.h" #include "PokemonBDSP_AutoStory_Battle.h" namespace PokemonAutomation{ @@ -378,37 +378,7 @@ void fight_with_best_move(VideoStream& stream, ProControllerContext& context, co void confirm_battle_overworld(VideoStream& stream, ProControllerContext& context, const std::string& label){ - OverworldDetector overworld; - ShortDialogDetector dialogue(COLOR_YELLOW); - BlackScreenDetector black; - VideoOverlaySet overlays(stream.overlay()); - overworld.make_overlays(overlays); - dialogue.make_overlays(overlays); - black.make_overlays(overlays); - const auto deadline = std::chrono::steady_clock::now() + 180s; - auto quiet_since = std::chrono::steady_clock::now(); - bool finished = false; - while (std::chrono::steady_clock::now() < deadline){ - const auto frame = stream.video().snapshot(); - if (!frame){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": No video frame.", stream); - } - const auto now = std::chrono::steady_clock::now(); - if (dialogue.detect(frame) || black.detect(frame) || !overworld.detect(frame)){ - quiet_since = now; - }else if (now - quiet_since >= 4s){ - finished = true; - break; - } - pbf_mash_button(context, BUTTON_B, 100ms); - context.wait_for_all_requests(); - } - if (!finished){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": Dialogue-free overworld not confirmed for four seconds.", stream); - } - context.wait_for_all_requests(); + talk_over(stream, context, label); } void fight_story_battle(VideoStream& stream, ProControllerContext& context, const std::string& label, BattleFormat format){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.h index 13dfe78cf5..371ab3877e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.h @@ -35,8 +35,10 @@ enum class BattleFormat{ DOUBLES, }; -// Mashes B until the overworld has shown with no dialogue for four seconds. -// Fails with a screenshot after three minutes. +// The speeches after a battle, to their end: talk_over(), B through the +// lines until the overworld is quiet. Roark's badge lines pause for the +// fanfare, and someone may walk off before the next line, so a moment +// with no box is not the end. Fails with a screenshot after two minutes. void confirm_battle_overworld(VideoStream& stream, ProControllerContext& context, const std::string& label); // A story battle that may go badly: the best move each turn, Potions diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Oreburgh.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Oreburgh.cpp index ad5b2079fe..5dc0f36dea 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Oreburgh.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Oreburgh.cpp @@ -98,12 +98,10 @@ bool oreburgh_gym_battles(VideoStream& stream, ProControllerContext& context){ if (dialogue_opens(stream, context, 3000ms)){ // His lines pause for more than 4 s before the battle (r210d: "only // talked"), so the battle is expected. + // His badge speech is over when talk_or_fight() returns: the + // battle ends with its speeches (confirm_battle_overworld()). if (talk_or_fight(stream, context, "Roark", TalkExpect::BATTLE)){ - if (in_pokemon_center(stream)){ - return false; - } - finish_dialogue(stream, context, BUTTON_B, "Roark after the battle"); - return true; + return !in_pokemon_center(stream); } continue; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.cpp new file mode 100644 index 0000000000..5b51629ff2 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.cpp @@ -0,0 +1,156 @@ +/* BDSP AutoStory - Talk-over + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" +#include "PokemonBDSP_AutoStory_WildBattle.h" +#include "PokemonBDSP_AutoStory_TalkOver.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +SceneMove TalkOver::look(const SceneLook& look, WallClock now){ + if (look.battle){ + m_quiet_since = WallClock::max(); + m_calm_since = WallClock::max(); + return SceneMove::BATTLE; + } + if (look.fade != WarpFade::NONE){ + m_fade = look.fade; + } + m_banner |= look.banner; + const bool calm = !look.box && look.overworld && warped(); + const bool quiet = calm && look.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 look.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_banner){ + out += out.empty() ? "banner read" : ", banner read"; + } + return out; +} + + +namespace{ + +// The detectors talk_over() looks with. +class SceneEyes{ +public: + SceneEyes(TalkOverWatch watch, const std::string& banner) + : m_watch(watch) + , m_banner(banner) + , m_wild_menu(BattleType::STANDARD) + , m_trainer_menu(BattleType::TRAINER) + {} + + SceneLook look(const VideoSnapshot& frame, WallClock now){ + SceneLook out; + if (!frame){ + m_previous = VideoSnapshot(); + return out; + } + const ImageViewRGB32& screen = *frame.frame; + out.battle = m_wild_menu.detect(screen) || (m_watch == TalkOverWatch::TRAINER && + (m_trainer_menu.detect(screen) || m_black.detect(screen))); + out.box = m_dialog.detect(screen); + out.overworld = m_overworld.detect(screen); + out.still = m_previous && walk_screen_change(*m_previous.frame, screen) < WALK_TAP_BLOCKED_CHANGE; + out.fade = fade_of_screen(screen); + out.banner = !m_banner.empty() && location_banner_matches(m_reads.read(screen, now), m_banner); + m_previous = frame; + return out; + } + +private: + TalkOverWatch m_watch; + const std::string& m_banner; + ShortDialogDetector m_dialog; + OverworldDetector m_overworld; + BattleMenuDetector m_wild_menu; + BattleMenuDetector m_trainer_menu; + BlackScreenDetector m_black; + LocationBannerReads m_reads; + VideoSnapshot m_previous; +}; + +} // namespace + +TalkOverEnd talk_over(VideoStream& stream, ProControllerContext& context, const std::string& label, const TalkOverSpec& spec){ + const WallClock deadline = current_time() + TALK_OVER_LIMIT; + TalkOver judge(spec.rule); + SceneEyes eyes(spec.watch, spec.banner); + while (current_time() < deadline){ + context.wait_for_all_requests(); + const WallClock now = current_time(); + switch (judge.look(eyes.look(stream.video().snapshot(), now), now)){ + case SceneMove::DONE: + stream.log(std::format("[Talk-over] {}: over; {}.", label, judge.describe())); + return TalkOverEnd::QUIET; + case SceneMove::BATTLE: + if (spec.watch == TalkOverWatch::TRAINER){ + stream.log("[Talk-over] " + label + ": a battle started."); + return TalkOverEnd::BATTLE; + } + stream.log("[Talk-over] " + label + ": in a wild battle; fleeing."); + run_from_wild_battle(stream, context); + continue; + case SceneMove::NEXT: + pbf_press_button(context, spec.next, TALK_OVER_HOLD, TALK_OVER_RELEASE); + continue; + case SceneMove::B: + pbf_press_button(context, BUTTON_B, TALK_OVER_HOLD, TALK_OVER_RELEASE); + continue; + } + } + const long long seconds = std::chrono::duration_cast(TALK_OVER_LIMIT).count(); + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + !judge.warped() + ? std::format("{}: no fade or banner within {} s, so we are not where the step goes (map mismatch).", label, seconds) + : !spec.rule.end_on_quiet + ? std::format("{}: no battle within {} s of the talk.", label, seconds) + : std::format("{}: not back on a quiet overworld within {} s.", label, seconds), + stream); +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h new file mode 100644 index 0000000000..9961a86d8e --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h @@ -0,0 +1,137 @@ +/* BDSP AutoStory - Talk-over + * + * From: https://github.com/PokemonAutomation/ + * + * When a talk or a scene is over, judged from what the screen shows over + * time (#268's design note, slice 4): one rule for scenes, the speeches + * after a battle and a trainer's lines before one. It replaces the loops + * each of those had (settle(), settle_after_battle(), talk_or_fight()'s, + * confirm_battle_overworld()'s), which differed in how long the quiet had + * to last and whether the screen had to be still. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_TalkOver_H +#define PokemonAutomation_PokemonBDSP_AutoStory_TalkOver_H + +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// What one look at the screen showed. +struct SceneLook{ + // A dialogue box. + bool box = false; + // The overworld, as OverworldDetector reads it. + bool overworld = false; + // The screen barely changed since the look before (WALK_TAP_BLOCKED_CHANGE). + bool still = false; + // A fade, by fade_of(): uniform, so a dim cave floor is none. + WarpFade fade = WarpFade::NONE; + // The expected map's location banner read. + bool banner = false; + // A battle started (TalkOverWatch says what counts). + bool battle = false; +}; + +// 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); +// One press is held this long, +constexpr Milliseconds TALK_OVER_HOLD = Milliseconds(80); +// then released this long before the next look. +constexpr Milliseconds TALK_OVER_RELEASE = Milliseconds(1200); +// How long a talk-over may take before the step fails. +constexpr Milliseconds TALK_OVER_LIMIT = Milliseconds(120000); + +// The judgement, from looks alone: tests drive it with scripted scenes. +class TalkOver{ +public: + explicit TalkOver(TalkOverRule rule = {}) + : m_rule(rule) + {} + + SceneMove look(const SceneLook& 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; + WarpFade m_fade = WarpFade::NONE; + bool m_banner = false; + WallClock m_quiet_since = WallClock::max(); + WallClock m_calm_since = WallClock::max(); +}; + + +// What counts as a battle starting during a talk-over. +enum class TalkOverWatch{ + // A wild battle's menu; it is fled and the talk-over goes on. A black + // screen is a fade (a scene that changes map). + SCENE, + // A trainer's battle: its menu (Roark's read as STANDARD, r210d) or the + // black screen it opens with. The talk-over ends there. + TRAINER, +}; + +// How talk_over() presses and looks. +struct TalkOverSpec{ + // Pressed while a box shows: B, or A for lines that give an item. + Button next = BUTTON_B; + TalkOverRule rule = {}; + TalkOverWatch watch = TalkOverWatch::SCENE; + // The expected map's banner name for TalkOverRule::warp ("" for a fade only). + std::string banner = ""; +}; + +// How talk_over() ended. +enum class TalkOverEnd{ + QUIET, + BATTLE, // Only with TalkOverWatch::TRAINER. +}; + +// Presses through any text and scene on the console until TalkOver says it +// is over. Fails with a screenshot after TALK_OVER_LIMIT. +TalkOverEnd talk_over(VideoStream& stream, ProControllerContext& context, const std::string& label, const TalkOverSpec& spec = {}); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp index c7bb6ce399..710fd83672 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp @@ -18,17 +18,16 @@ #include "CommonTools/Async/InferenceRoutines.h" #include "CommonTools/OCR/OCR_RawTesseractOCR.h" #include "CommonTools/OCR/OCR_Routines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" #include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" -#include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h" #include "PokemonBDSP_AutoStory_Bag.h" #include "PokemonBDSP_AutoStory_Battle.h" +#include "PokemonBDSP_AutoStory_TalkOver.h" #include "PokemonBDSP_AutoStory_WildBattle.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walks.h" #include "PokemonBDSP_AutoStory_Talks.h" @@ -53,79 +52,23 @@ bool dialogue_opens(VideoStream& stream, ProControllerContext& context, Millisec return wait_until(stream, context, timeout, {{dialog}}) == 0; } -namespace{ - -// Lines after a trainer battle (Roark's badge, r211d) keep the menu from -// opening: finish them before the Potion. They pause for the badge's -// fanfare, so "no box for a moment" is not the end: after four lines Roark -// went quiet, the Potion's menu opened under his next line and failed -// (lab-B, 2026-10-31 09:45 and 2026-11-08 15:06). Done once the overworld -// shows with no box for 5 s. -void settle_after_battle(VideoStream& stream, ProControllerContext& context){ - ShortDialogDetector dialog; - OverworldDetector overworld; - auto calm_since = std::chrono::steady_clock::now(); - const auto give_up = calm_since + 60s; - while (std::chrono::steady_clock::now() < give_up){ - context.wait_for_all_requests(); - const auto frame = stream.video().snapshot(); - const bool box = frame && dialog.detect(*frame.frame); - if (box || !frame || !overworld.detect(*frame.frame)){ - calm_since = std::chrono::steady_clock::now(); - }else if (std::chrono::steady_clock::now() - calm_since >= 5s){ - return; - } - if (box){ - pbf_press_button(context, BUTTON_B, 80ms, 1100ms); - }else{ - pbf_wait(context, 300ms); - } - } -} - -} // namespace - bool talk_or_fight(VideoStream& stream, ProControllerContext& context, const std::string& label, TalkExpect expect, BattleFormat format){ - ShortDialogDetector dialog; - OverworldDetector overworld; - BattleMenuDetector battle_menu(BattleType::TRAINER); - // Roark's battle menu read as STANDARD, not TRAINER, and nothing fought - // it (r210d): either counts here, as only a trainer's battle can start. - BattleMenuDetector battle_menu_standard(BattleType::STANDARD); - BlackScreenDetector black; - auto quiet_since = std::chrono::steady_clock::now(); - for (size_t check = 0; check < 120; check++){ - context.wait_for_all_requests(); - const auto frame = stream.video().snapshot(); - if (!frame){ - fail_step(stream, label + ": No video frame."); - } - if (battle_menu.detect(*frame.frame) || battle_menu_standard.detect(*frame.frame) || black.detect(*frame.frame)){ - route_status(stream, "Fighting " + label + "."); - fight_story_battle(stream, context, label, format); - settle_after_battle(stream, context); - if (!in_pokemon_center(stream)){ - use_potion_first_pokemon(stream, context, 0.8); - } - return true; - } - const bool talking = dialog.detect(*frame.frame); - if (!talking && overworld.detect(*frame.frame)){ - if (expect != TalkExpect::BATTLE && std::chrono::steady_clock::now() - quiet_since >= 4s){ - route_status(stream, label + " only talked."); - return false; - } - pbf_wait(context, 300ms); - continue; - } - quiet_since = std::chrono::steady_clock::now(); - if (talking){ - pbf_press_button(context, BUTTON_B, 80ms, 1100ms); - }else{ - pbf_wait(context, 300ms); - } + const TalkOverEnd end = talk_over(stream, context, label, { + .rule = {.end_on_quiet = expect != TalkExpect::BATTLE}, + .watch = TalkOverWatch::TRAINER, + }); + if (end == TalkOverEnd::QUIET){ + route_status(stream, label + " only talked."); + return false; + } + route_status(stream, "Fighting " + label + "."); + // The battle ends with its speeches over (confirm_battle_overworld()): + // Roark's badge lines keep the Potion's menu from opening until then. + fight_story_battle(stream, context, label, format); + if (!in_pokemon_center(stream)){ + use_potion_first_pokemon(stream, context, 0.8); } - fail_step(stream, label + ": neither a battle nor the overworld after the dialogue."); + return true; } // A rough check that we stand in a Pokemon Center: its floor fills the lower diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.h index 31591f9c02..77851d6c44 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.h @@ -36,9 +36,9 @@ bool dialogue_opens(VideoStream& stream, ProControllerContext& context, Millisec // followed by a Potion if HP is under half. Anyone else's ends back in the // overworld. Returns whether there was a battle. Between a trainer's last // line and the battle the overworld shows with no dialogue for a moment, -// so "only talked" needs 4 s of it, and never comes when `expect` is -// BATTLE. `format` DOUBLES for tag and twin battles. A lost battle ends in -// the last Pokemon Center; see in_pokemon_center(). +// so "only talked" is talk_over()'s quiet, and never comes when `expect` +// is BATTLE. `format` DOUBLES for tag and twin battles. A lost battle ends +// in the last Pokemon Center; see in_pokemon_center(). enum class TalkExpect{ TALK_OR_BATTLE, BATTLE, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index 46b0279e63..ea04347f31 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -23,6 +23,7 @@ #include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "Actions/PokemonBDSP_AutoStory_TalkOver.h" #include "Actions/PokemonBDSP_AutoStory_Talks.h" #include "PokemonBDSP_AutoStory_Walks.h" #include "Actions/PokemonBDSP_AutoStory_WildBattle.h" @@ -39,93 +40,9 @@ using Pokemon::Direction; namespace{ -// One rule for scenes and map changes: v2's long B mashes, with an end -// check. Press through the text, and keep pressing B while the screen is -// quiet: a scene can pause while someone walks off (Dawn and Barry after -// Rowan leaves, r23), fade dimly, not to black, to another map (r25), or -// wait on a box the detector misses (r26). B never starts a talk on the -// overworld. Done once the overworld has shown, with no text and a still -// screen, for 5 s of presses: after r31's fade home a scripted walk-in ran -// 5 s with no text before Mom spoke. -// -// A step or scene that ends on another map (`fade`) must fade on the way, -// and only the quiet after the fade counts: r30's scene went quiet for 5 s -// before the fade home, and r28 "went out" a tile beside the door and -// walked a whole route in the house. No fade is a map mismatch. The far -// map's banner `banner`, if it has one, counts as the fade: a fade the run -// missed is over, but its banner comes after it (#268 slice 1). -constexpr double FADE_DARKNESS = 75; // brightness 0 to 255; cave fades reach ~45..64, r24's dim fade goes darker -// What settle() has seen of the warp so far: the darkest frame, and the banner. -class SettleWarp{ -public: - explicit SettleWarp(const std::string& banner) - : m_banner(banner) - {} - void look(const ImageViewRGB32& frame, WallClock now){ - m_darkest = std::min(m_darkest, image_average(frame).sum() / 3); - m_banner_seen |= !m_banner.empty() && location_banner_matches(m_reads.read(frame, now), m_banner); - } - bool seen() const{ - return m_darkest < FADE_DARKNESS || m_banner_seen; - } - std::string describe() const{ - return std::format("darkest frame {:.0f}{}", m_darkest, m_banner_seen ? ", banner read" : ""); - } - -private: - const std::string& m_banner; - double m_darkest = 255; - LocationBannerReads m_reads; - bool m_banner_seen = false; -}; -void settle(VideoStream& stream, ProControllerContext& context, Button button, const std::string& label, bool fade, const std::string& banner){ - const WallClock none = WallClock::max(); - const WallClock deadline = current_time() + 120s; - ShortDialogDetector dialog; - OverworldDetector overworld; - BattleMenuDetector battle_menu(BattleType::STANDARD); - WallClock quiet_since = none, calm_since = none; - SettleWarp warp(banner); - VideoSnapshot previous; - while (current_time() < deadline){ - context.wait_for_all_requests(); - const auto frame = stream.video().snapshot(); - const WallClock now = current_time(); - if (frame && battle_menu.detect(frame)){ - stream.log("[Story] " + label + ": in wild battle during settle; fleeing."); - run_from_wild_battle(stream, context); - continue; - } - if (frame){ - warp.look(*frame.frame, now); - } - const bool warped = !fade || warp.seen(); - const bool talking = frame && dialog.detect(frame); - const bool still = frame && previous && walk_screen_change(*previous.frame, *frame.frame) < WALK_TAP_BLOCKED_CHANGE; - previous = frame; - const bool calm = !talking && overworld.detect(frame) && warped; - calm_since = calm ? (calm_since == none ? now : calm_since) : none; - if (calm && now - calm_since >= 15000ms){ - stream.log(std::format("[Story] {}: settled on calm overworld; {}.", label, warp.describe())); - return; - } - if (!talking && still && overworld.detect(frame) && warped){ - quiet_since = quiet_since == none ? now : quiet_since; - if (now - quiet_since >= 5000ms){ - stream.log(std::format("[Story] {}: settled; {}.", label, warp.describe())); - return; - } - }else{ - quiet_since = none; - } - pbf_press_button(context, talking ? button : BUTTON_B, 80ms, 1200ms); - } - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - fade && !warp.seen() - ? label + ": no fade or banner within 120 s, so we are not where the step goes (map mismatch)." - : label + ": not back on a quiet overworld within 120 s.", - stream); -} +// A door run's dark screen, a channel's mean brightness 0 to 255: cave +// fades reach ~45..64, r24's dim fade goes darker. +constexpr double FADE_DARKNESS = 75; DpadPosition dpad_toward(Direction direction){ return @@ -376,8 +293,15 @@ std::optional ConsoleStoryStepIO::tap_to_banner(Direction direction, con return std::nullopt; } +// One rule for scenes and map changes (talk_over()): press through the +// text, and keep pressing B while the screen is quiet, until the overworld +// is quiet. A step or scene that ends on another map (`fade`) must fade on +// the way, and only the quiet after the fade counts: r28 "went out" a tile +// beside the door and walked a whole route in the house. The far map's +// banner `banner`, if it has one, counts as the fade: a fade the run +// missed is over, but its banner comes after it (#268 slice 1). void ConsoleStoryStepIO::settle(Button button, const std::string& label, bool fade, const std::string& banner){ - PokemonBDSP::settle(m_stream, m_context, button, label, fade, banner); + talk_over(m_stream, m_context, label, {.next = button, .rule = {.warp = fade}, .banner = banner}); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp index a0968abb0f..97f98b9c59 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -207,6 +207,75 @@ UnitTestResult wanderers_move(Logger& logger, const std::string& row){ return failed.empty() ? UnitTestResult(true) : UnitTestResult(out); } +// Roark's badge speech after the battle: four lines, the fanfare's pause +// with no box, then the badge's and the TM's lines (lab-B 2026-10-31 09:45 +// and 2026-11-08 15:06: "no box for a moment" read as the end, and the +// Potion's menu opened under his next line). Then a scene: someone walks +// off with no box for 6 s before the last line, as Rowan does in r23 (the +// walk is a model, not measured after Roark). Played on the talk-over the +// battle's end runs (confirm_battle_overworld()). +UnitTestResult roark_badge_speech(Logger& logger){ + const SimScene scene{ + sim_line("Roark: the battle's last line"), + sim_line("Roark: you beat me"), + sim_line("Roark: the Coal Badge"), + sim_line("Received the Coal Badge"), + sim_pause("the badge's fanfare", 3000ms, false), + sim_line("Roark: the TM"), + sim_line("Roark: Stealth Rock"), + sim_pause("someone walks off", 6000ms, true), + sim_line("the last line"), + }; + const std::string early = play_scene(scene, {}); + logger.log("Roark's badge speech: " + (early.empty() ? std::string("over after the last line") : early)); + return passes(early); +} + +// 01.07: after the tag battle the screen fades back from the battle and +// the grunts run off before anyone speaks: a scene that opens with no box, +// 6 s of people moving (Rowan's cutscene shape), then Rowan's and Dawn's +// lines, and Bebe walks over with hers. The lengths are a model: r80 saved +// over her lines. +UnitTestResult grunts_run_off_before_rowan(Logger& logger){ + SimWorldKnobs knobs; + knobs.scenes["galactic_grunts"] = { + sim_fade("back from the battle", 1000ms), + sim_pause("the grunts run off", 6000ms, true), + sim_line("Rowan"), + sim_line("Rowan"), + sim_line("Dawn"), + sim_pause("Bebe walks over", 5000ms, true), + sim_line("Bebe"), + sim_line("Bebe: the Pokemon Center's PC"), + }; + return passes(run_case(logger, "01.07", "01.07", {.fade = {}, .banner = {}}, knobs)); +} + +// 00.03: Rowan's scene opens with no box: Rowan and Dawn walk back and +// stand a moment before his first line; after he leaves, Dawn's and +// Barry's lines, the fade home, and Mom walks over before she speaks +// (r23, r24, r31). The scene changes map, so only the quiet after the +// fade counts. +UnitTestResult rowans_scene_opens_with_no_box(Logger& logger){ + SimWorldKnobs knobs; + knobs.scenes["rowan_and_dawn"] = { + sim_pause("Rowan and Dawn walk back", 7000ms, true), + sim_pause("they stand a moment", 3000ms, false), + sim_line("Rowan"), + sim_line("Rowan"), + sim_pause("Rowan leaves", 6000ms, true), + sim_pause("Dawn and Barry stand", 3000ms, false), + sim_line("Dawn"), + sim_line("Barry"), + sim_fade("the fade home", 1500ms), + sim_pause("home, still", 4000ms, false), + sim_pause("Mom walks over", 5000ms, true), + sim_line("Mom: the Running Shoes"), + sim_line("Mom"), + }; + return passes(run_case(logger, "00.03", "00.03", {.fade = {}, .banner = {}}, knobs)); +} + struct FailureCaseInput{ std::string name; std::function body; @@ -280,6 +349,9 @@ const FailureCase AUTO_STORY_FAILURE_CASES[] = { {.input = {"01.08 with Route 204's youngster wandering (12..14, 2)", [](Logger& logger){ return wanderers_move(logger, "01.08"); }}, .expectation = {}}, + {.input = {"01.04 Roark's badge speech: the fanfare's pause, then a scene", roark_badge_speech}, .expectation = {}}, + {.input = {"01.07 after the tag battle the grunts run off before anyone speaks", grunts_run_off_before_rowan}, .expectation = {}}, + {.input = {"00.03 Rowan's scene opens with no box and fades home", rowans_scene_opens_with_no_box}, .expectation = {}}, }; void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index 835ee14d1f..04ec9ce644 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -33,6 +33,77 @@ ImageStats sim_screen(double brightness, double stddev){ return ImageStats(FloatPixel(brightness, brightness, brightness), FloatPixel(stddev, stddev, stddev), 1); } +SimBeat sim_line(std::string what){ + return {.what = std::move(what), .line = true}; +} +SimBeat sim_pause(std::string what, Milliseconds length, bool moving){ + return {.what = std::move(what), .length = length, .moving = moving}; +} +SimBeat sim_fade(std::string what, Milliseconds length, WarpFade fade){ + return {.what = std::move(what), .length = length, .overworld = false, .fade = fade}; +} + +std::string play_scene(const SimScene& scene, const TalkOverRule& rule){ + const Milliseconds press = TALK_OVER_HOLD + TALK_OVER_RELEASE; + TalkOver judge(rule); + const WallClock start = WallClock(); + WallClock now = start; + WallClock beat_start = start; + size_t beat = 0; + const auto at = [&]{ + return std::format("{} ms in, at beat {} of {}", std::chrono::duration_cast(now - start).count(), beat + 1, scene.size()); + }; + while (now - start < TALK_OVER_LIMIT){ + while (beat < scene.size() && !scene[beat].line && now - beat_start >= scene[beat].length){ + beat_start += scene[beat].length; + beat++; + } + SceneLook look{.overworld = true, .still = true}; + if (beat < scene.size()){ + const SimBeat& shown = scene[beat]; + look = {.box = shown.line, .overworld = shown.overworld, .still = !shown.moving, .fade = shown.fade}; + } + switch (judge.look(look, now)){ + case SceneMove::DONE: + return beat < scene.size() ? std::format("judged over {} ({})", at(), scene[beat].what) : ""; + case SceneMove::BATTLE: + return "read a battle " + at(); + case SceneMove::NEXT: + case SceneMove::B: + // Either press closes a line; nothing else answers one. + if (beat < scene.size() && scene[beat].line){ + beat++; + beat_start = now + press; + } + break; + } + now += press; + } + return "never judged over: " + at() + ", " + judge.describe(); +} + +// Plays the step's scene knob through TalkOver if it has one. Without, a +// scene may take us to another map (Mom walks us out, 00.04): with a +// dialogue open the stub scene plays it. Otherwise only a door fades. +void SimStoryStepIO::settle(Button, const std::string& label, bool fade, const std::string&){ + const auto scene = m_knobs.scenes.find(m_step); + if (scene != m_knobs.scenes.end()){ + m_misses.fade_unseen = false; + m_sim.end_dialogue(); + const std::string early = play_scene(scene->second, {.warp = fade}); + if (!early.empty()){ + m_route.note(label + ": talk-over " + early + ".", RouteNote::FAILURE); + } + return; + } + const bool scene_fades = m_sim.player().dialog && m_far_side(); + if (fade && ((!m_sim.player().warped && !scene_fades) || m_misses.fade_unseen)){ + m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); + } + m_misses.fade_unseen = false; + m_sim.end_dialogue(); +} + // A hold until something stops us. A door stops it at the fade, which // fails the step; a fade missed lets the hold go on past the mouth (r81's // timed walk south out of the Ravaged Path, onto Route 204's cliff). @@ -447,6 +518,20 @@ Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ return Pokemon::outcome_ok(); } +// The battle is not played. The speeches after it are, when the knobs +// script them, as the console's battle ends: confirm_battle_overworld()'s +// talk-over. +Outcome SimExecutor::battle(RunState&, const StoryStep& step){ + const auto scene = m_knobs.scenes.find(step.name); + if (scene != m_knobs.scenes.end()){ + const std::string early = play_scene(scene->second, {}); + if (!early.empty()){ + return Pokemon::outcome_failed("talk_over", step.name + ": " + early); + } + } + return stub(); +} + // Why a walking step did not end where the table says, or "". A step // through a door the simulation did not cross is not checked: the sim's // maps have no warps' destinations. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index e20575b083..de8a781481 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -25,6 +25,7 @@ #include "Common/Cpp/TestRunners/UnitTest.h" #include "CommonFramework/ImageTools/ImageStats.h" #include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" @@ -92,6 +93,31 @@ struct SimSlide{ bool banner_up = false; }; +// One beat of a scripted scene: a line, up until a press, or `length` of +// screen with no box, `overworld` or not (a battle's end, a fade), +// `moving` (someone walking, the camera panning) or still, faded as `fade`. +struct SimBeat{ + std::string what; + bool line = false; + Milliseconds length = Milliseconds(0); + bool overworld = true; + bool moving = false; + WarpFade fade = WarpFade::NONE; +}; +// A line, up until a press. +SimBeat sim_line(std::string what); +// `length` of overworld with no box, someone moving or not. +SimBeat sim_pause(std::string what, Milliseconds length, bool moving); +// `length` of a fade, not the overworld. +SimBeat sim_fade(std::string what, Milliseconds length, WarpFade fade = WarpFade::BLACK); +// A talk or a scene as the screen shows it, beat by beat; the quiet +// overworld after the last beat. +using SimScene = std::vector; +// Plays `scene` against the program's TalkOver with `rule`, a look per +// press, as talk_over() takes them: "" if it is judged over after the last +// beat, else when it was judged over early, or that it never was. +std::string play_scene(const SimScene& scene, const TalkOverRule& rule); + // What the console showed that the plain simulation leaves out, each off // unless set. All of it is deterministic: wanderers walk from `wander_seed`. struct SimWorldKnobs{ @@ -107,6 +133,9 @@ struct SimWorldKnobs{ std::optional wander_seed = std::nullopt; // How long after the A press a talk's first line shows, by step name. std::map first_line = {}; + // The scene a step's talk-over plays, by step name: a scene's or a + // door's settle(), or the speeches after a battle step's battle. + std::map scenes = {}; }; // The walker's RouteIO on the story simulation, with SimWorldKnobs' slides @@ -202,6 +231,7 @@ class SimStoryStepIO : public StoryStepIO{ , m_misses(misses) , m_knobs(knobs) , m_far_side(std::move(far_side)) + , m_step(step) {} virtual RouteIO& route() override{ @@ -231,20 +261,12 @@ class SimStoryStepIO : public StoryStepIO{ m_misses.fade_unseen = true; return {.banner = !banner.empty() && !banner_missed() ? banner : ""}; } - // A scene may take us to another map (Mom walks us out, 00.04): with a - // dialogue open the stub scene plays it. Otherwise only a door fades. // A fade missed on the way in stays missed: it was over before settle() // looked, which then fails as it does on the console after 120 s. The // run before looked for the banner (run_into_door()), so settle() sees - // none here. - virtual void settle(Button, const std::string& label, bool fade, const std::string&) override{ - const bool scene_fades = m_sim.player().dialog && m_far_side(); - if (fade && ((!m_sim.player().warped && !scene_fades) || m_misses.fade_unseen)){ - m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); - } - m_misses.fade_unseen = false; - m_sim.end_dialogue(); - } + // none here. With a scene in SimWorldKnobs::scenes, the program's + // TalkOver plays it instead. + virtual void settle(Button, const std::string& label, bool fade, const std::string&) override; virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) override; private: @@ -275,6 +297,7 @@ class SimStoryStepIO : public StoryStepIO{ SimMisses& m_misses; const SimWorldKnobs& m_knobs; std::function m_far_side; + const std::string& m_step; }; // A scene's trigger the simulation fires from row `row` on, once the step @@ -340,7 +363,7 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ virtual Pokemon::Outcome new_game(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } virtual Pokemon::Outcome options(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } virtual Pokemon::Outcome answer(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } - virtual Pokemon::Outcome battle(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } + virtual Pokemon::Outcome battle(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; virtual Pokemon::Outcome train(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } virtual Pokemon::Outcome shop(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } virtual Pokemon::Outcome save(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 206fe066b2..e548845993 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1732,6 +1732,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.h Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.h + Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.cpp + Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walks.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walks.h Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.cpp From 0d35443b9b5de7f07920b0e9db761e5ab9d16a6a Mon Sep 17 00:00:00 2001 From: Di Fan <26423504+dayfine@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:48:13 -0800 Subject: [PATCH 074/166] AutoStory: shared screen events and judges; BDSP and FRLG adapters (#268) (#290) * AutoStory: shared screen events and the judgements over them A game-agnostic vocabulary of what a story step sees (fades, location banner, dialog and choice boxes, interact prompt, battle start/end, player can move, screen still), an observer interface a game implements with its own detectors, and a run_until watcher form that records events and stops on chosen ones. The warp judgement (WarpSeen, fade_of) and the TalkOver judge from BDSP's #284/#289 move here, expressed over the events. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: read the shared screen events and judges BdspScreenObserver (the talk-over's SceneEyes, made public) reports BDSP's detectors as the shared screen events, and talk_over(), the walks and the story sim use the shared TalkOver judge, WarpSeen and fade_of instead of BDSP's own copies. Behaviour is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * FRLG AutoStory: screen events from FRLG's detectors FrlgScreenObserver maps the white dialog box, the selection box, the battle menu and battle text, and uniform fades to the shared events. Unit tests on synthetic frames; real frames are the detectors' own tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * FRLG AutoStory: screen events test builds an empty snapshot plainly Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * FRLG AutoStory: drop the flat grey frame from the screen-event tests The battle text box detector reads a flat grey frame as its box; that frame is no real screen, so it tests nothing about the adapter. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * AutoStory screen events: fit the code-health limits ScreenEvents keeps its set operations; fades and the log text become free functions (fade_events, fade_in, describe), WarpSeen::see becomes note_warp(), and the tests use the case-table form. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss * BDSP AutoStory: use only the shared names BDSP reads, each documented Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --------- Co-authored-by: Claude Opus 5.5 --- .../ComputerPrograms_UnitTestRunner.cpp | 1 + .../AutoStory/Pokemon_AutoStory_Tests.h | 2 + .../Pokemon/AutoStory/Pokemon_SceneJudges.cpp | 85 ++++++ .../Pokemon/AutoStory/Pokemon_SceneJudges.h | 99 +++++++ .../AutoStory/Pokemon_ScreenEvents.cpp | 132 +++++++++ .../Pokemon/AutoStory/Pokemon_ScreenEvents.h | 168 +++++++++++ .../AutoStory/Pokemon_ScreenEvents_Tests.cpp | 269 ++++++++++++++++++ .../PokemonBDSP_AutoStory_TalkOver.cpp | 101 +------ .../Actions/PokemonBDSP_AutoStory_TalkOver.h | 70 +---- .../PokemonBDSP_AutoStory_ScreenEvents.cpp | 54 ++++ .../PokemonBDSP_AutoStory_ScreenEvents.h | 64 +++++ .../PokemonBDSP_AutoStory_StorySim.cpp | 8 +- .../Utils/PokemonBDSP_AutoStory_Walk.cpp | 30 -- .../Utils/PokemonBDSP_AutoStory_Walk.h | 53 ++-- .../PokemonFRLG/PokemonFRLG_Tests.cpp | 2 + .../PokemonFRLG_AutoStoryScreenEvents.cpp | 52 ++++ .../PokemonFRLG_AutoStoryScreenEvents.h | 53 ++++ ...okemonFRLG_AutoStoryScreenEvents_Tests.cpp | 97 +++++++ SerialPrograms/cmake/SourceFiles.cmake | 10 + 19 files changed, 1120 insertions(+), 230 deletions(-) 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/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 1c698ab707..4ab69e6c79 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -81,6 +81,7 @@ 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_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..237cd643d7 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -15,6 +15,8 @@ namespace PokemonAutomation{ namespace Pokemon{ +// Registers unit tests for the shared screen events and the judgements over them. +void add_tests_ScreenEvents(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_SceneJudges.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp new file mode 100644 index 0000000000..628be668dc --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp @@ -0,0 +1,85 @@ +/* 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; + } + if (fade_in(look) != WarpFade::NONE){ + m_fade = fade_in(look); + } + 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(); + 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_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..704ecf9a86 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h @@ -0,0 +1,99 @@ +/* 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. +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; + WarpFade m_fade = 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..d8ea3b5beb --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.cpp @@ -0,0 +1,132 @@ +/* Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#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"; + } + 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)))); +} + + +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); + if (!events.any_of(m_stop_on)){ + return false; + } + m_stopped_on.store(events.bits(), std::memory_order_release); + return true; +} +void ScreenEventWatcher::reset(){ + m_seen.store(0, std::memory_order_release); + m_stopped_on.store(0, std::memory_order_release); +} + + + +} // 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..1bf6ca6649 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents.h @@ -0,0 +1,168 @@ +/* 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 "Common/Cpp/Time.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.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. +}; +// How many ScreenEvent values there are. +constexpr size_t SCREEN_EVENT_COUNT = 10; +// "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); + + +// 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; +}; + + +// An observer as a run_until callback: it records every event it sees 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)); + } + void reset(); + +private: + ScreenEventObserver& m_observer; + const ScreenEvents m_stop_on; + std::atomic m_seen{0}; + std::atomic m_stopped_on{0}; +}; + + + +} // 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..2d0db31cfd --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp @@ -0,0 +1,269 @@ +/* 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}; + +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}, + }; + 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/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.cpp index 5b51629ff2..4c371b495b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.cpp @@ -7,12 +7,8 @@ #include #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" -#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" -#include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h" -#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" +#include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.h" #include "PokemonBDSP_AutoStory_WildBattle.h" #include "PokemonBDSP_AutoStory_TalkOver.h" @@ -21,105 +17,14 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ -SceneMove TalkOver::look(const SceneLook& look, WallClock now){ - if (look.battle){ - m_quiet_since = WallClock::max(); - m_calm_since = WallClock::max(); - return SceneMove::BATTLE; - } - if (look.fade != WarpFade::NONE){ - m_fade = look.fade; - } - m_banner |= look.banner; - const bool calm = !look.box && look.overworld && warped(); - const bool quiet = calm && look.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 look.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_banner){ - out += out.empty() ? "banner read" : ", banner read"; - } - return out; -} - - -namespace{ - -// The detectors talk_over() looks with. -class SceneEyes{ -public: - SceneEyes(TalkOverWatch watch, const std::string& banner) - : m_watch(watch) - , m_banner(banner) - , m_wild_menu(BattleType::STANDARD) - , m_trainer_menu(BattleType::TRAINER) - {} - - SceneLook look(const VideoSnapshot& frame, WallClock now){ - SceneLook out; - if (!frame){ - m_previous = VideoSnapshot(); - return out; - } - const ImageViewRGB32& screen = *frame.frame; - out.battle = m_wild_menu.detect(screen) || (m_watch == TalkOverWatch::TRAINER && - (m_trainer_menu.detect(screen) || m_black.detect(screen))); - out.box = m_dialog.detect(screen); - out.overworld = m_overworld.detect(screen); - out.still = m_previous && walk_screen_change(*m_previous.frame, screen) < WALK_TAP_BLOCKED_CHANGE; - out.fade = fade_of_screen(screen); - out.banner = !m_banner.empty() && location_banner_matches(m_reads.read(screen, now), m_banner); - m_previous = frame; - return out; - } - -private: - TalkOverWatch m_watch; - const std::string& m_banner; - ShortDialogDetector m_dialog; - OverworldDetector m_overworld; - BattleMenuDetector m_wild_menu; - BattleMenuDetector m_trainer_menu; - BlackScreenDetector m_black; - LocationBannerReads m_reads; - VideoSnapshot m_previous; -}; - -} // namespace - TalkOverEnd talk_over(VideoStream& stream, ProControllerContext& context, const std::string& label, const TalkOverSpec& spec){ const WallClock deadline = current_time() + TALK_OVER_LIMIT; TalkOver judge(spec.rule); - SceneEyes eyes(spec.watch, spec.banner); + BdspScreenObserver eyes(spec.watch == TalkOverWatch::TRAINER ? BattleCue::TRAINER : BattleCue::WILD_MENU, spec.banner); while (current_time() < deadline){ context.wait_for_all_requests(); const WallClock now = current_time(); - switch (judge.look(eyes.look(stream.video().snapshot(), now), now)){ + switch (judge.look(eyes.observe(stream.video().snapshot(), now), now)){ case SceneMove::DONE: stream.log(std::format("[Talk-over] {}: over; {}.", label, judge.describe())); return TalkOverEnd::QUIET; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h index 9961a86d8e..b4e5c6debe 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h @@ -18,6 +18,7 @@ #include "Common/Cpp/Time.h" #include "CommonFramework/Tools/VideoStream.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "Pokemon/AutoStory/Pokemon_SceneJudges.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h" namespace PokemonAutomation{ @@ -25,50 +26,15 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ -// What one look at the screen showed. -struct SceneLook{ - // A dialogue box. - bool box = false; - // The overworld, as OverworldDetector reads it. - bool overworld = false; - // The screen barely changed since the look before (WALK_TAP_BLOCKED_CHANGE). - bool still = false; - // A fade, by fade_of(): uniform, so a dim cave floor is none. - WarpFade fade = WarpFade::NONE; - // The expected map's location banner read. - bool banner = false; - // A battle started (TalkOverWatch says what counts). - bool battle = false; -}; - +// The judgement is shared (Pokemon_SceneJudges.h): it reads the screen +// events BdspScreenObserver reports. // 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. -}; - +using Pokemon::SceneMove; // 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; -}; +using Pokemon::TalkOverRule; +// When a talk or a scene is over, from looks alone. +using Pokemon::TalkOver; -// 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); // One press is held this long, constexpr Milliseconds TALK_OVER_HOLD = Milliseconds(80); // then released this long before the next look. @@ -76,28 +42,6 @@ constexpr Milliseconds TALK_OVER_RELEASE = Milliseconds(1200); // How long a talk-over may take before the step fails. constexpr Milliseconds TALK_OVER_LIMIT = Milliseconds(120000); -// The judgement, from looks alone: tests drive it with scripted scenes. -class TalkOver{ -public: - explicit TalkOver(TalkOverRule rule = {}) - : m_rule(rule) - {} - - SceneMove look(const SceneLook& 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; - WarpFade m_fade = WarpFade::NONE; - bool m_banner = false; - WallClock m_quiet_since = WallClock::max(); - WallClock m_calm_since = WallClock::max(); -}; - // What counts as a battle starting during a talk-over. enum class TalkOverWatch{ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.cpp new file mode 100644 index 0000000000..6473bf3a2b --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.cpp @@ -0,0 +1,54 @@ +/* BDSP AutoStory - Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h" +#include "PokemonBDSP_AutoStory_ScreenEvents.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::ScreenEvent; +using Pokemon::ScreenEvents; + + +BdspScreenObserver::BdspScreenObserver(BattleCue cue, std::string banner) + : m_cue(cue) + , m_banner(std::move(banner)) + , m_wild_menu(BattleType::STANDARD) + , m_trainer_menu(BattleType::TRAINER) +{} + +ScreenEvents BdspScreenObserver::observe(const VideoSnapshot& frame, WallClock now){ + ScreenEvents out; + if (!frame){ + m_previous = VideoSnapshot(); + return out; + } + const ImageViewRGB32& screen = *frame.frame; + out.set(ScreenEvent::BATTLE_STARTED, m_wild_menu.detect(screen) || (m_cue == BattleCue::TRAINER && + (m_trainer_menu.detect(screen) || m_black.detect(screen)))); + out.set(ScreenEvent::DIALOG_BOX, m_dialog.detect(screen)); + out.set(ScreenEvent::PLAYER_CAN_MOVE, m_overworld.detect(screen)); + out.set(ScreenEvent::SCREEN_STILL, m_previous && walk_screen_change(*m_previous.frame, screen) < WALK_TAP_BLOCKED_CHANGE); + out.merge(Pokemon::fade_events(fade_of_screen(screen))); + out.set(ScreenEvent::LOCATION_BANNER, !m_banner.empty() && location_banner_matches(m_reads.read(screen, now), m_banner)); + m_previous = frame; + return out; +} + +void BdspScreenObserver::make_overlays(VideoOverlaySet& items) const{ + m_dialog.make_overlays(items); + m_overworld.make_overlays(items); + m_wild_menu.make_overlays(items); +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.h new file mode 100644 index 0000000000..f5255e5948 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.h @@ -0,0 +1,64 @@ +/* BDSP AutoStory - Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + * BDSP's detectors as the shared screen events (Pokemon_ScreenEvents.h): + * the dialogue box, the overworld, a still screen, a fade, the expected + * map's location banner and a battle's start. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_ScreenEvents_H +#define PokemonAutomation_PokemonBDSP_AutoStory_ScreenEvents_H + +#include +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" +#include "PokemonBDSP_AutoStory_OverworldDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// What BATTLE_STARTED is. +enum class BattleCue{ + // A wild battle's menu. A black screen is a fade. + WILD_MENU, + // Also a trainer's battle: its menu (Roark's read as STANDARD, r210d) + // or the black screen it opens with. + TRAINER, +}; + +// The shared events from BDSP's detectors. Not the choice box, the +// interact prompt or a battle's end: no AutoStory step reads them yet. +class BdspScreenObserver : public Pokemon::ScreenEventObserver{ +public: + // `banner`: the expected map's banner name; LOCATION_BANNER is only it + // ("" for none). + BdspScreenObserver(BattleCue cue, std::string banner); + + virtual Pokemon::ScreenEvents observe(const VideoSnapshot& frame, WallClock now) override; + virtual void make_overlays(VideoOverlaySet& items) const override; + +private: + BattleCue m_cue; + std::string m_banner; + ShortDialogDetector m_dialog; + OverworldDetector m_overworld; + BattleMenuDetector m_wild_menu; + BattleMenuDetector m_trainer_menu; + BlackScreenDetector m_black; + LocationBannerReads m_reads; + VideoSnapshot m_previous; +}; + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index 04ec9ce644..4aca2d5f4a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -58,10 +58,14 @@ std::string play_scene(const SimScene& scene, const TalkOverRule& rule){ beat_start += scene[beat].length; beat++; } - SceneLook look{.overworld = true, .still = true}; + Pokemon::ScreenEvents look{Pokemon::ScreenEvent::PLAYER_CAN_MOVE, Pokemon::ScreenEvent::SCREEN_STILL}; if (beat < scene.size()){ const SimBeat& shown = scene[beat]; - look = {.box = shown.line, .overworld = shown.overworld, .still = !shown.moving, .fade = shown.fade}; + look = {}; + look.set(Pokemon::ScreenEvent::DIALOG_BOX, shown.line); + look.set(Pokemon::ScreenEvent::PLAYER_CAN_MOVE, shown.overworld); + look.set(Pokemon::ScreenEvent::SCREEN_STILL, !shown.moving); + look.merge(Pokemon::fade_events(shown.fade)); } switch (judge.look(look, now)){ case SceneMove::DONE: diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp index f1a18078fb..72fdbbfd50 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.cpp @@ -42,36 +42,6 @@ const char* walk_stop_name(WalkStop stop){ 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 "?"; -} - -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)))); -} - -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; -} double walk_screen_change(const ImageViewRGB32& before, const ImageViewRGB32& after){ // Small copies: only the whole-view scroll matters, not detail. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h index 311e3c784e..d3d61b6743 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h @@ -19,6 +19,7 @@ #include "CommonFramework/Tools/VideoStream.h" #include "Controllers/Joystick.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "Pokemon/AutoStory/Pokemon_SceneJudges.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -50,44 +51,22 @@ using WalkArrived = std::function; // hold where we are. enum class WalkOrigin{ CURRENT_LEG, MAY_PRECEDE_LEG }; -// How a screen's fade looks (#268's design note, slice 3). -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 -}; +// The fade and warp judgements are shared (Pokemon_ScreenEvents.h, +// Pokemon_SceneJudges.h); BDSP's walks and steps fill them. +// How a screen's fade looks. +using Pokemon::WarpFade; // "black fade", for the log. -const char* warp_fade_name(WarpFade fade); - -// 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 (the Oreburgh Gate's, 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); - -// 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(); - } -}; -// How it was seen, for the log: a black fade, banner "Route 203". -std::string describe(const WarpSeen& seen); +using Pokemon::warp_fade_name; +// A fade's most texture (the walk's black-screen watcher uses it too). +using Pokemon::FADE_MAX_STDDEV_SUM; +// A dark fade's brightest rgb sum (likewise). +using Pokemon::FADE_MAX_DARK_SUM; +// The fade a screen's middle shows, from its stats. +using Pokemon::fade_of; +// The fade a screen shows. +using Pokemon::fade_of_screen; +// What a walk or a step saw of a warp: a fade or a banner. +using Pokemon::WarpSeen; // Result metrics and terminal state returned by automated walking execution. struct WalkResult{ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index d734e275f7..68ab2a274b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -8,6 +8,7 @@ #include "Common/Cpp/Filesystem/Filesystem.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "CommonFramework/StaticGlobals.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h" #include "Inference/Box/PokemonFRLG_BoxCellOccupiedDetector.h" #include "Inference/Box/PokemonFRLG_BoxCellReader.h" #include "Inference/Box/PokemonFRLG_BoxGenderReader.h" @@ -288,6 +289,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_BattleMoveSelectionArrow(database); add_tests_BagDetector(database); add_tests_ExitWildBattle(database); + add_tests_AutoStoryScreenEvents(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp new file mode 100644 index 0000000000..85edb74b36 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp @@ -0,0 +1,52 @@ +/* FRLG AutoStory - Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonFRLG_AutoStoryScreenEvents.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::ScreenEvent; +using Pokemon::ScreenEvents; + + +FrlgScreenObserver::FrlgScreenObserver() + : m_dialog(COLOR_RED) + , m_choice(COLOR_RED) + , m_battle_menu(COLOR_RED) + , m_battle_dialog(COLOR_RED) +{} + +ScreenEvents FrlgScreenObserver::observe(const VideoSnapshot& frame, WallClock){ + if (!frame){ + return {}; + } + const ImageViewRGB32& screen = *frame.frame; + 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. + return out; + } + const bool battle = m_battle_menu.detect(screen) || m_battle_dialog.detect(screen); + out.set(ScreenEvent::BATTLE_STARTED, battle); + out.set(ScreenEvent::DIALOG_BOX, !battle && m_dialog.detect(screen)); + out.set(ScreenEvent::CHOICE_BOX, !battle && m_choice.detect(screen)); + return out; +} + +void FrlgScreenObserver::make_overlays(VideoOverlaySet& items) const{ + m_dialog.make_overlays(items); + m_choice.make_overlays(items); + m_battle_menu.make_overlays(items); + m_battle_dialog.make_overlays(items); +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h new file mode 100644 index 0000000000..d6403a765f --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h @@ -0,0 +1,53 @@ +/* FRLG AutoStory - Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + * FRLG's detectors as the shared screen events (Pokemon_ScreenEvents.h), + * so the shared judgements (Pokemon_SceneJudges.h) read FRLG frames too. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryScreenEvents_H +#define PokemonAutomation_PokemonFRLG_AutoStoryScreenEvents_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" +#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_BattleDialogs.h" +#include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_DialogDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The shared events from FRLG's detectors: +// - DIALOG_BOX: the overworld's white text box (WhiteDialogDetector); +// - 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(). +// 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. +class FrlgScreenObserver : public Pokemon::ScreenEventObserver{ +public: + FrlgScreenObserver(); + + virtual Pokemon::ScreenEvents observe(const VideoSnapshot& frame, WallClock now) override; + virtual void make_overlays(VideoOverlaySet& items) const override; + +private: + WhiteDialogDetector m_dialog; + SelectionDialogDetector m_choice; + BattleMenuDetector m_battle_menu; + BattleDialogDetector m_battle_dialog; +}; + +// Registers the adapter's unit tests (synthetic frames). +void add_tests_AutoStoryScreenEvents(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp new file mode 100644 index 0000000000..7f8182bccc --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp @@ -0,0 +1,97 @@ +/* FRLG AutoStory - Screen Events Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The adapter on synthetic frames: a uniform screen is a fade and nothing + * else, and no frame shows nothing. Frames of real boxes and battles are + * the detectors' own image tests (CommandLineTests); a flat grey frame is + * not one of those (the battle text box reads it as a box). + * + */ + +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "PokemonFRLG_AutoStoryScreenEvents.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::ScreenEvent; +using Pokemon::ScreenEvents; + +namespace{ + +struct ScreenEventsInput{ + std::string name; + // The frame's colour; 0 for no frame. + uint32_t color; +}; + +struct ScreenEventsExpectation{ + ScreenEvents events; +}; + +struct ScreenEventsCase{ + ScreenEventsInput input; + ScreenEventsExpectation expectation; +}; + +class Test_AutoStoryScreenEvents : public UnitTest{ +public: + explicit Test_AutoStoryScreenEvents(ScreenEventsCase test_case) + : UnitTest("PokemonFRLG::AutoStoryScreenEvents - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + VideoSnapshot frame; + if (m_case.input.color != 0){ + ImageRGB32 image(1920, 1080); + image.fill(m_case.input.color); + frame = VideoSnapshot(std::move(image), WallClock()); + } + FrlgScreenObserver observer; + const ScreenEvents got = observer.observe(frame, WallClock()); + if (got != m_case.expectation.events){ + return std::format("expected {}, got {}", describe(m_case.expectation.events), describe(got)); + } + return true; + } + +private: + ScreenEventsCase m_case; +}; + +} // namespace + + +const ScreenEventsCase SCREEN_EVENTS_CASES[] = { + { + .input = {"no frame shows nothing", 0}, + .expectation = {{}}, + }, + { + .input = {"a black screen is a black fade only", 0xff000000}, + .expectation = {{ScreenEvent::FADE_BLACK}}, + }, + { + .input = {"a white screen is a white fade only", 0xffffffff}, + .expectation = {{ScreenEvent::FADE_WHITE}}, + }, +}; + +void add_tests_AutoStoryScreenEvents(UnitTestDatabase& database){ + for (const auto& item : SCREEN_EVENTS_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index e548845993..e7c140bbdb 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1495,6 +1495,11 @@ 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_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 @@ -1687,6 +1692,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_MenuCursorDetector.h Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.cpp Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h + Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.cpp + Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.h Source/PokemonBDSP/PokemonBDSP_Tests.cpp Source/PokemonBDSP/PokemonBDSP_Tests.h Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions.cpp @@ -1954,6 +1961,9 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_NuggetBridgeFarmer.h Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_PickupFarmer.cpp Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_PickupFarmer.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryScreenEvents_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_BattleMenuNavigation.cpp Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_BattleMenuNavigation.h Source/VideoGames/PokemonFRLG/Programs/PokemonFRLG_SafariOptimalAction.cpp From 79bb4d16affb22ab7f38122b8de05e837c2ec052 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 01:08:38 -0800 Subject: [PATCH 075/166] BDSP AutoStory sim: build #167 on its own Fix GridSim's include paths, and move the tap-boundary wild encounters (SimEncounterPhase, SimWildTap, GridSimRouteIO's encounter list) down from the Floaroma PR, as the RecoveryWalk and RoutePlanner tests here use them. StorySim_Tests needs the later StoryStepIO (WarpSeen, settle by banner), so it moves up into that PR. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 2 - .../PokemonBDSP_AutoStory_GridSim.cpp | 32 +- .../PokemonBDSP_AutoStory_GridSim.h | 23 +- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 12 +- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 920 ------------------ .../PokemonBDSP_AutoStory_StorySim_Tests.h | 28 - ...onBDSP_AutoStory_StorySimulation_Tests.cpp | 8 +- SerialPrograms/cmake/SourceFiles.cmake | 2 - 8 files changed, 61 insertions(+), 966 deletions(-) delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp delete mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index 72c29a2fa1..bfe634212a 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -14,7 +14,6 @@ #include "Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h" -#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h" @@ -39,7 +38,6 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_PlannedRoute(database); add_tests_AutoStory_GridSim(database); add_tests_AutoStory_RecoveryWalk(database); - add_tests_AutoStory_StorySim(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp index fd90d56444..0673b2577c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -6,7 +6,7 @@ #include #include -#include "PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP_AutoStory_GridSim.h" namespace PokemonAutomation{ @@ -300,14 +300,42 @@ WalkResult GridSimRouteIO::walk_to_wall(const RouteWallWalk& walk){ return {.stop = walk_stop(move.stop), .walked = move.time, .wild_battles = 0, .moved_chunks = (size_t)(move.distance / SIM_TILE)}; } +std::optional GridSimRouteIO::take_encounter(Direction direction, size_t tiles, size_t tap, const std::string& label){ + const auto found = std::find_if(m_encounters.begin(), m_encounters.end(), [&](const SimWildTap& encounter){ + return encounter.direction == direction && encounter.requested_tiles == tiles + && encounter.tap == tap && encounter.label == label; + }); + if (found == m_encounters.end()){ + return std::nullopt; + } + SimWildTap encounter = *found; + m_encounters.erase(found); + return encounter; +} + // A tap a tile, as walk_tiles_dpad() taps: two taps in a row that move // nothing end the walk. WalkResult GridSimRouteIO::walk_taps(Direction direction, size_t tiles, const std::string& label){ WalkResult result{.stop = WalkStop::LIMIT, .walked = 0ms, .wild_battles = 0, .moved_chunks = 0}; size_t still = 0; for (size_t tap = 0; tap < tiles && result.stop == WalkStop::LIMIT; tap++){ - const SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + const auto encounter = take_encounter(direction, tiles, tap + 1, label); + const SimMove move = encounter && encounter->phase == SimEncounterPhase::BEFORE_MOVEMENT + ? SimMove{} : m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); result.walked += 800ms; + if (encounter){ + // Match the production escape_battle() credit, independently + // of actual simulated displacement. Consumers must not infer + // pose solely from this credit after an interrupted input. + result.wild_battles++; + if (tap == 0 || encounter->origin == WalkOrigin::MAY_PRECEDE_LEG){ + result.origin = WalkOrigin::MAY_PRECEDE_LEG; + } + result.moved_chunks++; + still = 0; + m_notes.push_back("[Sim] cleared wild encounter during " + label); + continue; + } still = move.distance > 0 ? 0 : still + 1; result.moved_chunks += move.distance > 0 ? 1 : 0; if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h index 727aac0518..6457abf373 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h @@ -26,12 +26,13 @@ #include #include +#include #include #include "Common/Cpp/Time.h" #include "Pokemon/Navigation/Pokemon_Grid.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" -#include "PokemonBDSP_AutoStory_RouteIO.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -155,13 +156,28 @@ class GridSim{ bool sim_can_step(const GridSim& sim, Pokemon::Direction direction); +// A deterministic, already-cleared encounter at a tap boundary. This is +// normalized movement/escape evidence, not a model of image detectors or +// battle mechanics. BEFORE leaves the tile unchanged; AFTER completes it. +enum class SimEncounterPhase{ BEFORE_MOVEMENT, AFTER_MOVEMENT }; +// Match one tap and supply its cleared encounter phase and origin evidence. +struct SimWildTap{ + std::string label; + Pokemon::Direction direction = Pokemon::Direction::NORTH; + size_t requested_tiles = 0; + size_t tap = 0; // one-based within the matching walk_taps call + SimEncounterPhase phase = SimEncounterPhase::AFTER_MOVEMENT; + WalkOrigin origin = WalkOrigin::CURRENT_LEG; +}; + // The walker's RouteIO on a GridSim. A failure throws GridSimFailure. class GridSimRouteIO : public RouteIO{ public: // Every line noted goes to `notes`, which must outlive this. - GridSimRouteIO(GridSim& sim, std::vector& notes) + GridSimRouteIO(GridSim& sim, std::vector& notes, std::vector encounters = {}) : m_sim(sim) , m_notes(notes) + , m_encounters(std::move(encounters)) {} virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override; @@ -173,8 +189,11 @@ class GridSimRouteIO : public RouteIO{ virtual void note(const std::string& text, RouteNote kind) override; private: + std::optional take_encounter(Pokemon::Direction direction, size_t tiles, size_t tap, const std::string& label); + GridSim& m_sim; std::vector& m_notes; + std::vector m_encounters; }; // What GridSimRouteIO throws for RouteNote::FAILURE. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index ec8db51b68..8030c8d0be 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -18,13 +18,13 @@ #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" -#include "Data/PokemonBDSP_AutoStory_Maps.h" -#include "Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" #include "PokemonBDSP_AutoStory_GridSim.h" -#include "Utils/PokemonBDSP_AutoStory_PlannedRoute.h" -#include "PokemonBDSP_AutoStory_StoryExecutor.h" -#include "PokemonBDSP_AutoStory_StoryPlaces.h" -#include "PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_GridSim_Tests.h" namespace PokemonAutomation{ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp deleted file mode 100644 index 4215dd977e..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ /dev/null @@ -1,920 +0,0 @@ -/* BDSP AutoStory Story Sim Tests - * - * From: https://github.com/PokemonAutomation/ - * - * Rows of the story table run as the program runs them (the segment - * runner, make_story_segment()), with the program's own walking steps - * (StoryWalkSteps: ROUTE, LEGS, STEP, TALK, MASH) on the grid simulation. - * After each walking step the simulated player must stand, on the grid, - * on a tile the table gives; a step through a door must have warped. - * - * Events, battles, shops and saves are stubs: a dialogue they open is - * closed, and the table's pose_after puts the player where they end. A - * heal checks that a walk north from where we stand enters a door. A scene - * starts when the player steps onto one of the maps' coord events while - * its story variable holds (story_vars()). Rooms with no - * map (the Trainers' School) are passed over. Each row must start where - * the row before left the player. - * - * A tap or hold through a door or cave mouth stops on its tile, as the - * console stops at the fade; a hold that does not see the fade goes on - * onto the step's pose_after and on along it, and a location banner reads - * only a few tiles into its map (SIM_BANNER_TILES). The exit tests run - * r75's and r81's old open-ended walks that way. - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" -#include "Pokemon/AutoStory/Pokemon_StorySegments.h" -#include "Pokemon/AutoStory/Pokemon_TilePose.h" -#include "Data/PokemonBDSP_AutoStory_CoordEvents.h" -#include "Data/PokemonBDSP_AutoStory_Maps.h" -#include "PokemonBDSP_AutoStory_GridSim.h" -#include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" -#include "PokemonBDSP_AutoStory_Events.h" -#include "PokemonBDSP_AutoStory_StoryExecutor.h" -#include "PokemonBDSP_AutoStory_StoryPlaces.h" -#include "PokemonBDSP_AutoStory_StoryStepIO.h" -#include "PokemonBDSP_AutoStory_StoryTable.h" -#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" -#include "PokemonBDSP_AutoStory_StorySim_Tests.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -namespace{ - -using namespace std::chrono_literals; -using Pokemon::Direction; -using Pokemon::Outcome; -using Pokemon::Pose; -using Pokemon::RunState; -using Pokemon::StoryStep; -using Pokemon::StoryStepKind; -using Pokemon::TilePos; - - -// Which detections the simulation misses on purpose (#162): the `fade`th -// door fade (run_into_door(), from 0) or the `banner`th map banner -// (run_until_map()) of the run goes unseen, though the player did go -// through. The console missed both (r75, r81). -// The counts and flags below are the run's: how many fades and banners it -// looked for, whether a miss happened since the executor last looked, and -// whether a missed fade is still unseen. -struct SimMisses{ - std::optional fade; - std::optional banner; - size_t fades = 0; - size_t banners = 0; - bool missed = false; - bool fade_unseen = false; -}; - -// How many tiles a held walk goes on into a map before its location -// banner reads: "it shows a tile or a few past the border" (the table's -// route_201_by_the_path(), measured on the console). Standing still, it -// reads at once. Through a cave mouth the fade comes first, and a hold -// whose fade went unseen goes on the same way (r75, r81). -constexpr size_t SIM_BANNER_TILES = 3; - -// What a run on the simulation did. -struct SimRun{ - // The first failure, as "row outcome", or "". - std::string error; - // The rows and steps where an injected miss happened and where the run - // first failed, as "row step": "" if none. - std::string missed_step; - std::string failed_step; - // Walking steps that end where nothing says, as "row step". - std::vector unchecked; - // Each row run, with the fades and banners looked for before it. - struct RowStart{ - std::string row; - size_t fades; - size_t banners; - }; - std::vector rows; - // Where the player stood after the last step, if placed. - const StoryWorld* world = nullptr; - TilePos end; -}; - -// StoryStepIO on the simulation. A walk through a door or a cave mouth -// stops on its tile, as the console stops at the fade; a hold that misses -// the fade carries on, onto `far_side()` (the step's pose_after: the -// sim's maps have no warps' destinations) and on along it. -class SimStoryStepIO : public StoryStepIO{ -public: - SimStoryStepIO(GridSim& sim, std::vector& notes, SimMisses& misses, std::function far_side) - : m_sim(sim) - , m_route(sim, notes) - , m_misses(misses) - , m_far_side(std::move(far_side)) - {} - - virtual RouteIO& route() override{ - return m_route; - } - virtual void fight(const std::string&) override{ - m_sim.end_dialogue(); - } - virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string& label) override; - virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; - virtual bool run_into_door(Direction direction, bool run) override{ - const bool warped = m_sim.hold(direction, 12000ms, run ? SimPace::RUN : SimPace::WALK).stop == SimStop::WARP; - if (warped && fade_missed()){ - m_misses.fade_unseen = true; - return false; - } - return warped; - } - // A scene may take us to another map (Mom walks us out, 00.04): with a - // dialogue open the stub scene plays it. Otherwise only a door fades. - // A fade missed on the way in stays missed: it was over before settle() - // looked, which then fails as it does on the console after 120 s. - virtual void settle(Button, const std::string& label, bool fade) override{ - if (fade && ((!m_sim.player().warped && !m_sim.player().dialog) || m_misses.fade_unseen)){ - m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); - } - m_misses.fade_unseen = false; - m_sim.end_dialogue(); - } - virtual std::optional tap_to_banner(Direction direction, const std::string& map, size_t max_taps) override; - -private: - // Whether the run misses this fade or this banner (SimMisses). - bool fade_missed(){ - const bool miss = m_misses.fade == m_misses.fades++; - m_misses.missed |= miss; - return miss; - } - bool banner_missed(){ - const bool miss = m_misses.banner == m_misses.banners++; - m_misses.missed |= miss; - return miss; - } - bool on_map(const std::string& map) const{ - return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); - } - - GridSim& m_sim; - GridSimRouteIO m_route; - SimMisses& m_misses; - std::function m_far_side; -}; - -// A hold until something stops us. A door stops it at the fade, which -// fails the step; a fade missed lets the hold go on past the mouth (r81's -// timed walk south out of the Ravaged Path, onto Route 204's cliff). -void SimStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ - m_sim.tap(direction, ROUTE_TURN_TAP, false); - Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); - SimMove move = m_sim.hold(direction, limit, SimPace::WALK); - if (move.stop == SimStop::WARP && fade_missed() && m_far_side()){ - limit -= std::min(limit, move.time); - move = m_sim.hold(direction, limit, SimPace::WALK); - } - if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ - m_route.note(label + ": " + sim_stop_name(move.stop) + " instead of a stop.", RouteNote::FAILURE); - } -} - -// The D-pad, a tile at a time, until `map`'s banner reads; through a door -// the walk goes on beyond it (the fade eats no tiles of a hold). -bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&){ - const bool miss = banner_missed(); - size_t on = 0; - for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ - SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); - const bool crossed = move.stop == SimStop::WARP && m_far_side(); - const bool stopped = !crossed && (move.distance == 0 || move.stop != SimStop::DONE); - on = on_map(map) ? on + 1 : 0; - if (on > 0 && (on > SIM_BANNER_TILES || stopped) && !miss){ - return true; - } - if (stopped){ - return false; - } - } - return false; -} - -// D-pad taps, each looked at, until the fade and then the banner (the -// console's ConsoleStoryStepIO::tap_to_banner()). Each look stands still, -// so a banner on the far side reads at once. A fade seen ends the taps, -// banner or not; with the fade missed the next look still sees the banner. -std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ - bool crossed = false; - for (size_t tap = 1; tap <= max_taps; tap++){ - const SimMove move = m_sim.tap(direction, 160ms, false); - if (move.stop == SimStop::DIALOG){ - return std::nullopt; - } - bool faded = false; - if (move.stop == SimStop::WARP){ - faded = !fade_missed(); - crossed = m_far_side(); - } - if (crossed && on_map(map) && !banner_missed()){ - return tap; - } - if (faded){ - return std::nullopt; - } - } - return std::nullopt; -} - - -// A scene's trigger the simulation fires from row `row` on, once the step -// `after` has run ("" from the row's start), on `map`'s `tiles`. -struct RowTrigger{ - std::string row; - std::string after; - std::string map; - SimTrigger trigger; -}; - -// When a story variable holds the value its coord events wait for: from -// row `row` on, once the step `after` has run ("" from the row's start). -struct VarState{ - std::string var; - int value; - std::string row; - std::string after; -}; - -// The story variables whose coord events the table walks onto, from the -// row (and step) the table's reasons give, with the maps' coord events -// (Diamond's zone events; Platinum's for the houses): Barry's doorstep and -// Mom's warning in 00.01, Barry's Route 201 warning, then its pull-back -// row 19 once he has warned us (r14, r16); the lake's entrance in 00.02; -// Rowan's stop and Dawn at Sandgem's edge in 00.03; Dawn's catching -// tutorial on Route 202 from 00.04's start, Mom's call once she has healed -// us; the Poketch president on Jubilife's row 40 in 00.05b; Barry on Route -// 203 in 01.01; the Gate's Hiker and Oreburgh's welcome in 01.02; Barry's -// bump in Oreburgh after Roark in 01.05; and Rowan in Jubilife in 01.07. -// Left out: the Twinleaf guitarist (spent upstairs), Platinum's rival -// steps around our bedroom's start, Dawn at Jubilife's steps (BDSP starts -// her below them: an event), and Floaroma's (10..12, 29) (Diamond only). -std::vector story_vars(){ - return { - {.var = "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", .value = 0, .row = "00.01", .after = ""}, - {.var = "VAR_PLAYER_HOUSE_STATE", .value = 1, .row = "00.01", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 0, .row = "00.01", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 1, .row = "00.01", .after = "barry_warns_us"}, - {.var = "VAR_VERITY_LAKEFRONT_STATE", .value = 0, .row = "00.02", .after = ""}, - {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 2, .row = "00.03", .after = ""}, - {.var = "VAR_SANDGEM_TOWN_STATE", .value = 0, .row = "00.03", .after = ""}, - {.var = "VAR_ROUTE_202_STATE", .value = 0, .row = "00.04", .after = ""}, - {.var = "CONSOLE_MOMS_CALL", .value = 0, .row = "00.04", .after = "mom_heals_us"}, - {.var = "VAR_POKETCH_CAMPAIGN_STATE", .value = 1, .row = "00.05b", .after = ""}, - {.var = "VAR_ROUTE_203_RIVAL_STATE", .value = 0, .row = "01.01", .after = ""}, - {.var = "VAR_OREBURGH_GATE_1F_HIKER_STATE", .value = 1, .row = "01.02", .after = ""}, - {.var = "VAR_OREBURGH_CITY_STATE", .value = 0, .row = "01.02", .after = ""}, - {.var = "VAR_OREBURGH_CITY_STATE", .value = 2, .row = "01.05", .after = ""}, - {.var = "VAR_JUBILIFE_CITY_STATE", .value = 3, .row = "01.07", .after = ""}, - }; -} - -// The maps' coord events (story_coord_events()) whose variable holds. -std::optional var_state(const CoordEvent& event){ - for (const VarState& state : story_vars()){ - if (state.var == event.var && state.value == event.value){ - return state; - } - } - return std::nullopt; -} - -RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ - return {.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; -} - -std::vector story_triggers(){ - std::vector triggers; - for (const auto& [map, json] : bdsp_map_json()){ - for (const CoordEvent& event : story_coord_events(map)){ - const std::optional state = var_state(event); - if (state){ - triggers.push_back(row_trigger(map, event, *state)); - } - } - } - return triggers; -} - - -// Someone the maps do not have, who stands on `tile` of `map` and is -// talked to there or walked round: from row `row` on if `until` is "", -// else in `row` until its step `until` has run. -struct SimPerson{ - std::string name; - std::string map; - TilePos tile; - std::string row; - std::string until; -}; -std::vector sim_people(){ - return { - // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). - {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04", .until = ""}, - // Barry stands in the Center's door until his lines (01.03; Roark - // ignored A until then, r101 and r104). - {.name = "barry", .map = "OreburghCity", .tile = {47, 20}, .row = "01.03", .until = "barrys_lines"}, - }; -} - -// A house's stairs, entered by a step `side` from the map's "stairs" -// point into what the map draws as a wall (the table's 00.01: r8 and r9 -// for ours, r11 for Barry's). -struct SimStairs{ - std::string map; - Direction side; -}; -std::vector sim_stairs(){ - return { - {.map = "PlayerHouse2F", .side = Direction::EAST}, - {.map = "RivalHouse1F", .side = Direction::EAST}, - {.map = "RivalHouse2F", .side = Direction::WEST}, - }; -} - - -// The program's walking steps on the simulation, the rest stubbed. -class SimExecutor : public Pokemon::StoryStepExecutor{ -public: - explicit SimExecutor(Logger& logger, SimMisses misses = {}) - : m_logger(logger) - , m_misses(misses) - , m_sim({}, {0, 0}, Direction::NORTH, false) - , m_io(m_sim, m_notes, m_misses, [this]{ return cross(); }) - , m_walks(m_io) - {} - - const SimMisses& misses() const{ - return m_misses; - } - const SimRun& result() const{ - return m_result; - } - virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ - m_row = data.id; - m_start_mismatch = data.start ? off_pose(*data.start) : ""; - m_ran.clear(); - m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); - m_walks.begin_attempt(data.id); - arm(""); - } - virtual Outcome run(RunState& state, const StoryStep& step) override; - -protected: - virtual Outcome route(RunState& state, const StoryStep& step) override{ return m_walks.route(state, step); } - virtual Outcome legs(RunState& state, const StoryStep& step) override{ return m_walks.legs(state, step); } - virtual Outcome step(RunState& state, const StoryStep& step) override{ return m_walks.step(state, step); } - virtual Outcome talk(RunState& state, const StoryStep& step) override{ return m_walks.talk(state, step); } - virtual Outcome mash(RunState& state, const StoryStep& step) override{ return m_walks.mash(state, step); } - virtual Outcome heal(RunState& state, const StoryStep& step) override; - virtual Outcome new_game(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome options(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome answer(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome battle(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome train(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome shop(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome save(RunState&, const StoryStep&) override{ return stub(); } - virtual Outcome game(RunState&, const StoryStep&) override{ return stub(); } - -private: - // A step the simulation does not play: its dialogue opened and closed. - Outcome stub(){ - m_sim.end_dialogue(); - return Pokemon::outcome_ok(); - } - const StoryWorld* sim_world(const std::string& map) const; - SimWorld setup(const StoryWorld* world) const; - void arm(const std::string& after); - bool sync(const Pose& pose, const StoryWorld* on = nullptr); - bool cross(); - std::string off_pose(const Pose& pose) const; - std::string check(const StoryStep& step, const Outcome& outcome); - Outcome run_step(RunState& state, const StoryStep& step); - - Logger& m_logger; - std::vector m_notes; - SimMisses m_misses; - GridSim m_sim; - SimStoryStepIO m_io; - StoryWalkSteps m_walks; - // The planner's worlds with sim_people() on them, by world and who. - mutable std::map, std::unique_ptr> m_peopled; - // The steps of this row that have run. - std::set m_ran; - std::string m_row; - std::vector m_armed; - // Where the step running now ends, if it says: a door's far side. - std::optional m_far; - // Why the player is not on this row's start, or "". - std::string m_start_mismatch; - // Whether the player has been put on a map yet. - bool m_placed = false; - // Whether the step running now is on a room with no map. - bool m_passed_over = false; - SimRun m_result; -}; - -// The world the player walks on for `map`: the planner's, with what the -// console showed that the maps lack. Nothing for a room with no map. -const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ - const StoryWorld* world = story_plan_world(map, map); - std::vector here; - std::string who; - for (const SimPerson& person : sim_people()){ - const bool now = person.until.empty() ? m_row >= person.row : m_row == person.row && !m_ran.contains(person.until); - if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ - here.push_back(person); - who += person.name + ";"; - } - } - if (here.empty()){ - return world; - } - std::unique_ptr& peopled = m_peopled[{world, who}]; - if (!peopled){ - peopled = std::make_unique(*world); - for (const SimPerson& person : here){ - peopled->block(story_to_world(*world, person.map, person.tile)); - } - } - return peopled.get(); -} - -SimWorld SimExecutor::setup(const StoryWorld* world) const{ - // B runs once the shoes' scene has given them: the scene ends at home. - SimWorld out{.world = world, .trainers = story_trainers(*world), .can_run = m_walks.can_run()}; - for (const SimStairs& stairs : sim_stairs()){ - if (sim_world(stairs.map) == world){ - out.doors.push_back(story_to_world(*world, stairs.map, map_point(stairs.map, "stairs").next(stairs.side))); - } - } - for (const RowTrigger& armed : m_armed){ - if (sim_world(armed.map) != world){ - continue; - } - SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; - for (const TilePos& pos : armed.trigger.tiles){ - trigger.tiles.push_back(story_to_world(*world, armed.map, pos)); - } - out.triggers.push_back(std::move(trigger)); - } - return out; -} - -// Arms the triggers of this row that start after `after`. -void SimExecutor::arm(const std::string& after){ - size_t armed = 0; - for (const RowTrigger& trigger : story_triggers()){ - if (trigger.row == m_row && trigger.after == after){ - m_armed.push_back(trigger); - armed++; - } - } - const SimPlayer& player = m_sim.player(); - if (armed > 0 && m_placed && on_grid(player.pos) && !player.dialog){ - m_sim.place(setup(&m_sim.world()), nearest_tile(player.pos), player.facing); - } -} - -// Puts the player on `pose`, on the world `on` if given, unless they stand -// on one of its tiles already. Returns whether the pose is on a map the -// simulation has. -bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ - const std::vector tiles = Pokemon::tiles_of(pose); - const StoryWorld* world = on != nullptr ? on : pose.map.empty() ? nullptr : sim_world(pose.map); - if (world == nullptr || tiles.empty()){ - return false; - } - const SimPlayer& player = m_sim.player(); - const std::optional local = !m_placed || &m_sim.world() != world - ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); - if (local && on_grid(player.pos) && std::find(tiles.begin(), tiles.end(), *local) != tiles.end()){ - return true; - } - m_sim.place(setup(world), story_to_world(*world, pose.map, tiles.front()), Pokemon::facing_of(pose)); - m_placed = true; - return true; -} - -// Through a door or a cave mouth onto the step's far side, the player's -// facing kept: a hold goes on from there. -bool SimExecutor::cross(){ - const StoryWorld* world = m_far ? sim_world(m_far->map) : nullptr; - const std::vector tiles = m_far ? Pokemon::tiles_of(*m_far) : std::vector{}; - if (world == nullptr || tiles.empty()){ - return false; - } - m_sim.place(setup(world), story_to_world(*world, m_far->map, tiles.front()), std::nullopt); - return true; -} - -// Why the player does not stand on one of `pose`'s tiles, or "" if they -// do or the simulation cannot tell (no map, or not placed yet). -std::string SimExecutor::off_pose(const Pose& pose) const{ - const std::vector tiles = Pokemon::tiles_of(pose); - if (!m_placed || tiles.empty() || sim_world(pose.map) == nullptr){ - return ""; - } - const SimPlayer& player = m_sim.player(); - const TilePos at = nearest_tile(player.pos); - // In world tiles: a pose a leg worked out from the map it started on - // may lie past that map's edge, on the next map (Twinleaf's exit). - // story_to_world() throws for a map not on the player's world. - try{ - const auto there = [&](const TilePos& tile){ return story_to_world(m_sim.world(), pose.map, tile) == at; }; - if (on_grid(player.pos) && std::ranges::any_of(tiles, there)){ - return ""; - } - }catch (const InternalProgramError&){} - return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), at), Pokemon::to_string(pose)); -} - -Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ - if (sync(state.pose) && m_sim.hold(Direction::NORTH, 3000ms, SimPace::RUN).stop != SimStop::WARP){ - return Pokemon::outcome_failed("no_door", step.name + ": no door north of " + to_string(m_sim.player().pos)); - } - return Pokemon::outcome_ok(); -} - -// Why a walking step did not end where the table says, or "". A step -// through a door the simulation did not cross is not checked: the sim's -// maps have no warps' destinations. -std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ - const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP; - const std::optional expected = step.pose_after ? step.pose_after : outcome.pose; - if (!walks || !m_placed){ - return ""; - } - if (!expected || Pokemon::tiles_of(*expected).empty()){ - m_result.unchecked.push_back(m_row + " " + step.name); - return ""; - } - const SimPlayer& player = m_sim.player(); - if (player.warped && !story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos))){ - return ""; - } - return off_pose(*expected); -} - -Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ - if (!m_start_mismatch.empty()){ - return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); - } - m_far = step.pose_after; - if (story_events().contains(step.variant)){ - return stub(); - } - // A scene goes on from where the step before left us. A route walks - // on the world it plans on (Jubilife alone has no Route 204 north of it). - const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || - step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK; - const StoryWorld* on = step.kind == StoryStepKind::ROUTE && step.target && !state.pose.map.empty() - ? story_plan_world(state.pose.map, step.target->map) : nullptr; - // A world of one map is sim_world()'s, with its people. - if (on != nullptr && on == story_plan_world(state.pose.map, state.pose.map)){ - on = nullptr; - } - if (walks && !sync(state.pose, on)){ - m_logger.log(std::format("[{}] {}: no map for {}; passed over.", m_row, step.name, Pokemon::to_string(state.pose))); - m_passed_over = true; - return Pokemon::outcome_ok(); - } - return Pokemon::StoryStepExecutor::run(state, step); -} - -Outcome SimExecutor::run(RunState& state, const StoryStep& step){ - Outcome outcome; - m_passed_over = false; - try{ - outcome = run_step(state, step); - }catch (const GridSimFailure& e){ - outcome = Pokemon::outcome_failed("sim_failure", e.message); - } - const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; - if (!mismatch.empty()){ - outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); - } - // What the simulation does not play (scenes, events, battles) ends - // where the table says it does. - if (outcome.succeeded() && step.pose_after){ - sync(*step.pose_after); - } - m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); - if (std::exchange(m_misses.missed, false) && m_result.missed_step.empty()){ - m_result.missed_step = m_row + " " + step.name; - } - if (!outcome.succeeded() && m_result.error.empty()){ - // The walker's last notes, to see why. - for (size_t i = m_notes.size() - std::min(m_notes.size(), 40); i < m_notes.size(); i++){ - m_logger.log(std::format("[{}] note: {}", m_row, m_notes[i])); - } - m_result.error = m_row + " " + Pokemon::to_string(outcome); - m_result.failed_step = m_row + " " + step.name; - } - m_result.world = m_placed ? &m_sim.world() : nullptr; - m_result.end = nearest_tile(m_sim.player().pos); - m_ran.insert(step.name); - arm(step.name); - return outcome; -} - - -// Runs `range` of `rows` (the table unless given) on `executor`, stopping -// at the first failure. -Pokemon::SegmentReport run_rows_on( - SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, - const std::vector& rows = story_checkpoints() -){ - std::set saved; - Pokemon::Segment segment = make_story_segment(rows, executor, saved); - Pokemon::SegmentPolicy policy; - policy.stop_at_first_failure = true; - Pokemon::SegmentHooks hooks; - hooks.reload = [](RunState&){ return Pokemon::outcome_ok(); }; - hooks.log = [&logger](const std::string& line){ logger.log(line); }; - RunState state; - return Pokemon::run_segment(state, segment, range, policy, hooks); -} - -// Runs `range` of the table on the simulation, stopping at the first failure. -UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ - SimExecutor executor(logger); - const Pokemon::SegmentReport report = run_rows_on(executor, logger, range); - for (const std::string& step : executor.result().unchecked){ - logger.log("No end to check after " + step + "."); - } - if (!report.completed){ - return std::format("stopped at {} {}: {}", report.failed_checkpoint, report.failed_event, executor.result().error); - } - return true; -} - -// The table with row `row`'s step of `step`'s name replaced by `step`. -std::vector table_with(const std::string& row, const StoryStep& step){ - std::vector rows = story_checkpoints(); - for (StoryCheckpoint& checkpoint : rows){ - for (StoryStep& old : checkpoint.steps){ - if (checkpoint.id == row && old.name == step.name){ - old = step; - return rows; - } - } - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + step.name + " in " + row); -} - -bool ends_on(const SimRun& run, const Pose& pose){ - const std::vector tiles = Pokemon::tiles_of(pose); - const std::optional local = run.world ? story_to_local(*run.world, pose.map, run.end) : std::nullopt; - return local && std::find(tiles.begin(), tiles.end(), *local) != tiles.end(); -} -std::string end_of(const SimRun& run){ - return run.world ? describe(*run.world, run.end) : "nowhere"; -} - - -UnitTestResult run_exit_test(Logger& logger, const std::string& row_id, const StoryStep& old_step, const SimMisses& misses, const Pose& overshoot){ - SimExecutor executor(logger, misses); - const std::vector rows = table_with(row_id, old_step); - run_rows_on(executor, logger, {.from = row_id, .to = row_id}, rows); - const SimRun& run = executor.result(); - logger.log(std::format("The old {}: {}, ended on {}.", old_step.name, run.error, end_of(run))); - if (run.failed_step != row_id + " " + old_step.name || !ends_on(run, overshoot)){ - return std::format("the old {} should end on {} and fail there; it ended on {}: {}", - old_step.name, Pokemon::to_string(overshoot), end_of(run), run.error.empty() ? "no failure" : run.error); - } - SimExecutor clean(logger); - if (!run_rows_on(clean, logger, {.from = row_id, .to = row_id}).completed){ - return "the table's row fails without misses: " + clean.result().error; - } - std::vector runs; - for (size_t i = 0; i < clean.misses().fades; i++){ - runs.push_back({.fade = i, .banner = std::nullopt}); - } - for (size_t i = 0; i < clean.misses().banners; i++){ - runs.push_back({.fade = std::nullopt, .banner = i}); - } - for (const SimMisses& m : runs){ - SimExecutor sim(logger, m); - run_rows_on(sim, logger, {.from = row_id, .to = row_id}); - if (ends_on(sim.result(), overshoot)){ - return std::format("the table's {} ended on {} with a miss in {}.", old_step.name, end_of(sim.result()), - sim.result().missed_step); - } - } - return true; -} - -// r75: out of the Oreburgh Gate as a run west until Route 203's banner -// (the old event west_until_transition()). The banner reads a few tiles -// in: the run ends west of the Gate's warp tile (55, 9), in the pocket by -// the pond (Route 203's x 49 to 54, rows 6 to 13). -StoryStep r75_old_gate_exit(){ - StoryStep step; - step.kind = StoryStepKind::LEGS; - step.name = "out_of_oreburgh_gate"; - step.legs = {{.direction = Direction::WEST, .tiles = 8}}; - step.variant = "to_map"; - step.pose_after = Pokemon::tile_pose("Route203", {TilePos{55, 9}}, Direction::WEST); - return step; -} -Pose r75_pond_pocket(){ - std::vector tiles; - for (int y = 6; y <= 13; y++){ - for (int x = 49; x <= 54; x++){ - tiles.push_back({x, y}); - } - } - return Pokemon::tile_pose("Route203", tiles); -} -// r81: out of the Ravaged Path as a timed walk south (the old event's -// 4 s walk_dir()), its fade missed: on past cave_exit (20, 26) to the -// cliff, column 20 down to row 30. -StoryStep r81_old_cave_exit(){ - StoryStep step; - step.kind = StoryStepKind::LEGS; - step.name = "out_of_the_ravaged_path"; - step.legs = {{.direction = Direction::SOUTH, .tiles = 4}}; - step.variant = "to_wall"; - step.pose_after = Pokemon::tile_pose("Route204North", {TilePos{20, 26}}, Direction::SOUTH); - return step; -} -Pose r81_below_the_mouth(){ - return Pokemon::tile_pose("Route204North", {TilePos{20, 27}, TilePos{20, 28}, TilePos{20, 29}, TilePos{20, 30}}); -} - - -UnitTestResult test_coord_events(Logger&){ - for (const auto& [map, json] : bdsp_map_json()){ - const StoryWorld* world = story_plan_world(map, map); - for (const CoordEvent& event : world == nullptr ? std::vector{} : story_coord_events(map)){ - const auto open = [&](const TilePos& pos){ - const TilePos tile = story_to_world(*world, map, pos); - return standable(*world, tile) || world->tile(tile) == Pokemon::TileKind::DOOR; - }; - if (!std::ranges::any_of(event.tiles, open)){ - return std::format("{} {}: no tile is open ground or a door.", map, event.name); - } - } - } - const size_t armed = story_triggers().size(); - return armed == story_vars().size() ? UnitTestResult(true) - : UnitTestResult(std::format("Expected {} coord events armed by the story's variables, found {}.", story_vars().size(), armed)); -} - -std::string miss(Logger& logger, const SimRun& clean, bool fade, size_t index){ - size_t k = 0; - while (k + 1 < clean.rows.size() && (fade ? clean.rows[k + 1].fades : clean.rows[k + 1].banners) <= index){ - k++; - } - const SimRun::RowStart& start = clean.rows[k]; - SimMisses misses; - (fade ? misses.fade : misses.banner) = index - (fade ? start.fades : start.banners); - SimExecutor executor(logger, misses); - const Pokemon::SegmentReport report = run_rows_on(executor, logger, - {.from = start.row, .to = clean.rows[std::min(k + 1, clean.rows.size() - 1)].row}); - const SimRun& run = executor.result(); - const std::string what = std::format("{} {}", fade ? "fade" : "banner", index); - logger.log(std::format("Missed {} in {}: {}.", what, run.missed_step, - report.completed ? "got over it" : "stopped in " + run.failed_step + ": " + run.error)); - if (report.completed || run.failed_step == run.missed_step){ - return ""; - } - return std::format("{} missed in {}, failed later in {}: {}", what, run.missed_step, run.failed_step, run.error); -} - -UnitTestResult test_story_sim_misses(Logger& logger){ - Pokemon::SegmentRange range{.from = "00.00", .to = "01.11"}; - SimExecutor clean(logger); - if (!run_rows_on(clean, logger, range).completed){ - return "the run fails without misses: " + clean.result().error; - } - logger.log(std::format("{} fades and {} banners to miss.", clean.misses().fades, clean.misses().banners)); - std::vector unseen; - for (size_t i = 0; i < clean.misses().fades + clean.misses().banners; i++){ - const std::string line = miss(logger, clean.result(), i < clean.misses().fades, i < clean.misses().fades ? i : i - clean.misses().fades); - if (!line.empty()){ - unseen.push_back(line); - } - } - std::string out = "Misses that went unseen:"; - for (const std::string& line : unseen){ - out += "\n " + line; - } - return unseen.empty() ? UnitTestResult(true) : UnitTestResult(out); -} - -UnitTestResult test_story_sim_whole_table(Logger& logger){ - return run_rows(logger, {.from = "00.00", .to = "01.11"}); -} - -UnitTestResult test_story_sim_each_row(Logger& logger){ - for (const StoryCheckpoint& row : story_checkpoints()){ - const auto res = run_rows(logger, {.from = row.id, .to = row.id}); - if (res.result != UnitTestResult::PASSED){ - return std::format("Row {} failed: {}", row.id, res.message); - } - } - return true; -} - -UnitTestResult test_exit_gate(Logger& logger){ - return run_exit_test(logger, "01.05", r75_old_gate_exit(), SimMisses{}, r75_pond_pocket()); -} - -UnitTestResult test_exit_ravaged_path(Logger& logger){ - return run_exit_test(logger, "01.09", r81_old_cave_exit(), SimMisses{.fade = 0, .banner = std::nullopt}, r81_below_the_mouth()); -} - -struct AutoStoryStorySimInput{ - std::string name; - std::function body; -}; - -struct AutoStoryStorySimExpectation{ -}; - -struct AutoStoryStorySimCase{ - AutoStoryStorySimInput input; - AutoStoryStorySimExpectation expectation; -}; - -class Test_AutoStoryStorySim : public UnitTest{ -public: - explicit Test_AutoStoryStorySim(AutoStoryStorySimCase test_case) - : UnitTest("PokemonBDSP::AutoStory - Story sim: " + test_case.input.name) - , m_case(std::move(test_case)) - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - try{ - return m_case.input.body(logger); - }catch (Exception& e){ - return std::string(e.name()) + ": " + e.message(); - } - } - -private: - AutoStoryStorySimCase m_case; -}; - -} // namespace - - -const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { - { - .input = {"the maps' coord events are on open ground or doors", test_coord_events}, - .expectation = {}, - }, - { - .input = {"detector misses from 00.00 to 01.11", test_story_sim_misses}, - .expectation = {}, - }, - { - .input = {"00.00 to 01.11: the whole table, from the new game to Floaroma", test_story_sim_whole_table}, - .expectation = {}, - }, - { - .input = {"each row from 00.00 to 01.11 in isolation", test_story_sim_each_row}, - .expectation = {}, - }, - { - .input = {"r75, out of the Oreburgh Gate", test_exit_gate}, - .expectation = {}, - }, - { - .input = {"r81, out of the Ravaged Path", test_exit_ravaged_path}, - .expectation = {}, - }, -}; - -void add_tests_AutoStory_StorySim(UnitTestDatabase& database){ - for (const auto& item : AUTO_STORY_STORY_SIM_CASES){ - database.add(item); - } -} - - -} // namespace PokemonBDSP -} // namespace NintendoSwitch -} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h deleted file mode 100644 index bc1ed57d3a..0000000000 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h +++ /dev/null @@ -1,28 +0,0 @@ -/* BDSP AutoStory Story Sim Tests - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StorySim_Tests_H -#define PokemonAutomation_PokemonBDSP_AutoStory_StorySim_Tests_H - -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -// The story table's rows run by the program's own walking steps -// (StoryWalkSteps) on the grid simulation: each walk must end where the -// table says the player is. -void add_tests_AutoStory_StorySim(UnitTestDatabase& database); - - - -} // namespace PokemonBDSP -} // namespace NintendoSwitch -} // namespace PokemonAutomation -#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index a9918401a3..27c100db13 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -24,10 +24,10 @@ #include "Pokemon/AutoStory/Pokemon_StorySegments.h" #include "Pokemon/AutoStory/Pokemon_StorySteps.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" -#include "Utils/PokemonBDSP_AutoStory_Location.h" -#include "Data/PokemonBDSP_AutoStory_PlanCosts.h" -#include "PokemonBDSP_AutoStory_StoryPlaces.h" -#include "PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_StorySimulation_Tests.h" namespace PokemonAutomation{ diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index d7c86c665d..321a6dd343 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1715,8 +1715,6 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h - Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp - Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.h Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp From 55101c3b0af671c94264b1f51161e789e2dc1c39 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 01:12:34 -0800 Subject: [PATCH 076/166] CI: pin PokemonSimulation to 913a5e3 (mine walk to (46,57)) PokemonSimulation #79 updates the mine pilot cases for the (46,57) target, so the authoritative mine plan replay expects a 36-tile walk. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .github/workflows/cpp-ci-serial-programs-base.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cpp-ci-serial-programs-base.yml b/.github/workflows/cpp-ci-serial-programs-base.yml index 40452d1067..ec01bd3f85 100644 --- a/.github/workflows/cpp-ci-serial-programs-base.yml +++ b/.github/workflows/cpp-ci-serial-programs-base.yml @@ -101,7 +101,7 @@ jobs: uses: actions/checkout@v7 with: repository: dayfine/PokemonSimulation - ref: cf365e1722dea03fcf40c322b910332fcc864ea4 + ref: 913a5e3eaa22865e1aeab52f23c9e23ea7141ced path: AuthoredStorySource - name: Replay the authoritative Arduino mine plan From 7102b94557944d3957bca5d7405d373c86fe3192 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 01:13:43 -0800 Subject: [PATCH 077/166] BDSP AutoStory sim: the recovery walk test builds its own mine step At this PR 01.03's below_roark is a route row, not counted legs, so the test read an empty leg list. Build the legs in the test, as the Floaroma PR does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index e7436bcfe4..63feb8bdcf 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -58,14 +58,24 @@ class RecoveryStepIO : public StoryStepIO{ }; const Pokemon::StoryStep& mine_step(){ - for (const auto& row : story_checkpoints()){ - for (const auto& step : row.steps){ - if (row.id == "01.03" && step.name == "below_roark"){ - return step; - } - } - } - throw GridSimFailure{"missing native mine step"}; + static const Pokemon::StoryStep step = []{ + Pokemon::StoryStep step; + step.kind = Pokemon::StoryStepKind::LEGS; + step.name = "below_roark"; + step.legs = { + {.direction = Direction::EAST, .tiles = 1}, + {.direction = Direction::SOUTH, .tiles = 2}, + {.direction = Direction::WEST, .tiles = 1}, + {.direction = Direction::SOUTH, .tiles = 5}, + {.direction = Direction::EAST, .tiles = 14}, + {.direction = Direction::SOUTH, .tiles = 10}, + {.direction = Direction::WEST, .tiles = 2}, + {.direction = Direction::SOUTH, .tiles = 3}, + {.direction = Direction::WEST, .tiles = 9}, + }; + return step; + }(); + return step; } struct RecoveryInput{ From d00f00a42482397cb9252b39f36b2fbe09cdeeb5 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 01:38:53 -0800 Subject: [PATCH 078/166] BDSP AutoStory: console and sim executors bind one story action table story_action_table() holds BDSP's story steps as one Pokemon::StoryActionTable: the walking kinds run StoryWalkSteps on the binding's StoryStepIO, and the kinds that need the console, plus every story event (by variant name), are the binding's own (StoryBoundActions). StoryExecutor is a TableExecutor with ConsoleStepGuard (the old run() guard: log line, reattempt line, screenshot, stop rows); SimExecutor is a TableExecutor over the same table with its stand-ins. Behavior is unchanged. The sim records each row's stubbed steps (stub_report()). New tests: every row's steps have an action, each (kind, variant) the story uses runs what the old dispatch ran, and every step the sim stubs needs the console. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 2 + .../PokemonBDSP_AutoStory_StoryActions.cpp | 58 ++++ .../PokemonBDSP_AutoStory_StoryActions.h | 54 ++++ .../PokemonBDSP_AutoStory_StoryExecutor.cpp | 91 ++++--- .../PokemonBDSP_AutoStory_StoryExecutor.h | 89 ++++--- ...kemonBDSP_AutoStory_StoryActions_Tests.cpp | 247 ++++++++++++++++++ ...PokemonBDSP_AutoStory_StoryActions_Tests.h | 28 ++ .../PokemonBDSP_AutoStory_StorySim.cpp | 56 +++- .../PokemonBDSP_AutoStory_StorySim.h | 48 +++- SerialPrograms/cmake/SourceFiles.cmake | 4 + 10 files changed, 579 insertions(+), 98 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.h diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index f51fe909fb..37aa4bf5ec 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -15,6 +15,7 @@ #include "Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h" +#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.h" @@ -48,6 +49,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_RecoveryWalk(database); add_tests_AutoStory_StorySim(database); add_tests_AutoStory_SimFailureCases(database); + add_tests_AutoStory_StoryActions(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.cpp new file mode 100644 index 0000000000..c8db7e9338 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.cpp @@ -0,0 +1,58 @@ +/* BDSP AutoStory - Story actions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Actions/PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP_AutoStory_StoryActions.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::Outcome; +using Pokemon::RunState; +using Pokemon::StoryAction; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; + + +Pokemon::StoryActionTable story_action_table(StoryWalkSteps& walks, const StoryBoundActions& bound){ + Pokemon::StoryActionTable table; + using WalkMethod = Outcome (StoryWalkSteps::*)(RunState&, const StoryStep&); + const auto walk = [&](StoryStepKind kind, WalkMethod method){ + table.add(kind, "", StoryAction{ + .act = [&walks, method](RunState& state, const StoryStep& step){ + return (walks.*method)(state, step); + }, + }); + }; + walk(StoryStepKind::ROUTE, &StoryWalkSteps::route); + walk(StoryStepKind::LEGS, &StoryWalkSteps::legs); + walk(StoryStepKind::STEP, &StoryWalkSteps::step); + walk(StoryStepKind::TALK, &StoryWalkSteps::talk); + walk(StoryStepKind::MASH, &StoryWalkSteps::mash); + + const auto console = [&](StoryStepKind kind, const Pokemon::StoryActionFunction& act){ + table.add(kind, "", StoryAction{.act = act, .needs_console = true}); + }; + console(StoryStepKind::NEW_GAME, bound.new_game); + console(StoryStepKind::OPTIONS, bound.options); + console(StoryStepKind::ANSWER, bound.answer); + console(StoryStepKind::BATTLE, bound.battle); + console(StoryStepKind::TRAIN, bound.train); + console(StoryStepKind::HEAL, bound.heal); + console(StoryStepKind::SAVE, bound.save); + + for (const auto& item : story_events()){ + table.add_any_kind(item.first, StoryAction{.act = bound.event(item.first), .needs_console = true}); + } + return table; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h new file mode 100644 index 0000000000..6204f74751 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h @@ -0,0 +1,54 @@ +/* BDSP AutoStory - Story actions + * + * From: https://github.com/PokemonAutomation/ + * + * BDSP's story steps as one action table (Pokemon_StoryActions.h), which + * the console (StoryExecutor) and the simulation (SimExecutor) each bind. + * The walking steps (ROUTE, LEGS, STEP, TALK, MASH) are the same code on + * both: StoryWalkSteps on the binding's StoryStepIO. The steps that need + * the console (the intro, the options, answers, battles, training, the + * Center, saves, and the story's events, story_events()) are the + * binding's own: played on the console, stood in for on the simulation. + * + * A GAME step runs only the event its variant names, and BDSP has no SHOP + * or READY step: lint_story_checkpoint() reports a step with neither. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryActions_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryActions_H + +#include +#include +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// The actions a binding does its own way, one per kind that needs the +// console. +struct StoryBoundActions{ + Pokemon::StoryActionFunction new_game = {}; + Pokemon::StoryActionFunction options = {}; + Pokemon::StoryActionFunction answer = {}; + Pokemon::StoryActionFunction battle = {}; + Pokemon::StoryActionFunction train = {}; + Pokemon::StoryActionFunction heal = {}; + Pokemon::StoryActionFunction save = {}; + // The action for the story event named `name` (story_events()). + std::function event = {}; +}; + +// BDSP's story actions: the walking steps on `walks`, the rest `bound`'s. +// `walks` must outlive the table. +Pokemon::StoryActionTable story_action_table(StoryWalkSteps& walks, const StoryBoundActions& bound); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp index 47c25de07f..1c30b3c111 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp @@ -98,42 +98,61 @@ void save_failure_screenshot(VideoStream& stream, size_t attempt){ } // namespace +void ConsoleStepGuard::before_step(const StoryStep& step){ + m_stream.log(std::format("[{}] {} {}: {}", m_checkpoint, Pokemon::story_step_kind_name(step.kind), step.name, step.why), COLOR_BLUE); +} + +bool ConsoleStepGuard::stops_on_failure(const StoryStep&) const{ + return m_stop_rows.contains(m_checkpoint); +} + +void ConsoleStepGuard::on_failure(const StoryStep&, const OperationFailedException& error){ + // Attempts are the segment's policy; this only counts them for the + // log line the lab's run watcher reads. + const size_t attempt = m_failures[m_checkpoint]++; + m_stream.log(std::format("checkpoint_reattempt_loop: attempt {} failed: {}: {}", attempt, m_checkpoint, error.message()), COLOR_RED); + save_failure_screenshot(m_stream, attempt); +} + + +// The table and the guard are members, built after the base: it only +// keeps references to them until a step runs. StoryExecutor::StoryExecutor(StoryEnv& env) - : m_env(env) + : Pokemon::TableExecutor(m_table, m_guard) + , m_env(env) , m_io(env.env.console, env.context) , m_walks(m_io) + , m_guard(env.env.console, m_checkpoint) + , m_table(story_action_table(m_walks, console_actions())) {} +StoryBoundActions StoryExecutor::console_actions(){ + const auto method = [this](Outcome (StoryExecutor::*action)(RunState&, const StoryStep&)){ + return [this, action](RunState& state, const StoryStep& step){ + return (this->*action)(state, step); + }; + }; + return StoryBoundActions{ + .new_game = method(&StoryExecutor::new_game), + .options = method(&StoryExecutor::options), + .answer = method(&StoryExecutor::answer), + .battle = method(&StoryExecutor::battle), + .train = method(&StoryExecutor::train), + .heal = method(&StoryExecutor::heal), + .save = method(&StoryExecutor::save), + .event = [this](const std::string& name) -> Pokemon::StoryActionFunction{ + return [this, event = story_events().at(name)](RunState& state, const StoryStep& step){ + return event(*this, state, step); + }; + }, + }; +} + void StoryExecutor::begin_attempt(const Pokemon::StoryCheckpoint& data){ m_checkpoint = data.id; m_walks.begin_attempt(data.id); } -Outcome StoryExecutor::run(RunState& state, const StoryStep& step){ - stream().log(std::format("[{}] {} {}: {}", m_checkpoint, Pokemon::story_step_kind_name(step.kind), step.name, step.why), COLOR_BLUE); - try{ - return run_guarded(state, step); - }catch (OperationFailedException& e){ - if (m_stop_rows.contains(m_checkpoint)){ - throw; - } - // Attempts are the segment's policy; this only counts them for the - // log line the lab's run watcher reads. - const size_t attempt = m_failures[m_checkpoint]++; - stream().log(std::format("checkpoint_reattempt_loop: attempt {} failed: {}: {}", attempt, m_checkpoint, e.message()), COLOR_RED); - save_failure_screenshot(stream(), attempt); - return Pokemon::outcome_failed("operation_failed", e.message()); - } -} - -Outcome StoryExecutor::run_guarded(RunState& state, const StoryStep& step){ - const StoryEvents& events = story_events(); - if (auto event = events.find(step.variant); event != events.end()){ - return event->second(*this, state, step); - } - return Pokemon::StoryStepExecutor::run(state, step); -} - Outcome StoryExecutor::new_game(RunState&, const StoryStep&){ play_new_game_intro(m_env.env, context(), m_env.player_name); return Pokemon::outcome_ok(); @@ -145,22 +164,6 @@ Outcome StoryExecutor::options(RunState&, const StoryStep&){ return Pokemon::outcome_ok(); } -Outcome StoryExecutor::route(RunState& state, const StoryStep& step){ - return m_walks.route(state, step); -} - -Outcome StoryExecutor::legs(RunState& state, const StoryStep& step){ - return m_walks.legs(state, step); -} - -Outcome StoryExecutor::step(RunState& state, const StoryStep& step){ - return m_walks.step(state, step); -} - -Outcome StoryExecutor::talk(RunState& state, const StoryStep& step){ - return m_walks.talk(state, step); -} - Outcome StoryExecutor::answer(RunState&, const StoryStep& step){ wait_for_dialogue(stream(), context(), label_of(step)); pbf_press_button(context(), step.yes ? BUTTON_A : BUTTON_B, 80ms, 1000ms); @@ -168,10 +171,6 @@ Outcome StoryExecutor::answer(RunState&, const StoryStep& step){ return Pokemon::outcome_ok(); } -Outcome StoryExecutor::mash(RunState& state, const StoryStep& step){ - return m_walks.mash(state, step); -} - Outcome StoryExecutor::battle(RunState&, const StoryStep& step){ // "starter": the Starly battle at the lake (00.02). It opens on its own, // with no talk, and the starter has no Poke Balls to throw; the scene diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h index ca78ffe2e2..0ce3924058 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h @@ -10,12 +10,13 @@ * battles. A step whose variant names one of the story's events * (story_events(), PokemonBDSP_AutoStory_Events.h) runs that event, * whatever its kind: the scripted scenes and the console-measured walks - * of segment 01. + * of segment 01. It is the console's binding of the story's action table + * (story_action_table()); the simulation binds the same table. * - * Every step runs inside a guard that turns a failed console step into a - * failed Outcome, with a screenshot and the "checkpoint_reattempt_loop: - * attempt N failed" line the lab's run watcher reads; the segment then - * reloads the row's save and runs it again. + * Every step runs inside a guard (ConsoleStepGuard) that turns a failed + * console step into a failed Outcome, with a screenshot and the + * "checkpoint_reattempt_loop: attempt N failed" line the lab's run watcher + * reads; the segment then reloads the row's save and runs it again. * */ @@ -31,9 +32,11 @@ #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" #include "Pokemon/AutoStory/Pokemon_StorySegments.h" #include "Pokemon/AutoStory/Pokemon_StorySteps.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP_AutoStory_StoryActions.h" #include "PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP_AutoStory_StoryWalkSteps.h" @@ -85,8 +88,35 @@ struct StoryEnv{ std::optional story_route_costs(const std::string& variant); -// Does BDSP's kinds of story step on the console. -class StoryExecutor : public Pokemon::StoryStepExecutor{ +// What the console does around each story step: the step's log line, and +// a failed step's "checkpoint_reattempt_loop" line and screenshot. +class ConsoleStepGuard : public Pokemon::StepGuard{ +public: + // `checkpoint` names the row running now; both must outlive the guard. + ConsoleStepGuard(VideoStream& stream, const std::string& checkpoint) + : m_stream(stream) + , m_checkpoint(checkpoint) + {} + // The rows whose failure ends the program (StoryFailure::STOP). + void set_stop_rows(std::set rows){ + m_stop_rows = std::move(rows); + } + + virtual void before_step(const Pokemon::StoryStep& step) override; + virtual bool stops_on_failure(const Pokemon::StoryStep& step) const override; + virtual void on_failure(const Pokemon::StoryStep& step, const OperationFailedException& error) override; + +private: + VideoStream& m_stream; + const std::string& m_checkpoint; + std::map m_failures; + std::set m_stop_rows; +}; + + +// Does BDSP's kinds of story step on the console: the story's action +// table, its rows that need the console bound to the methods below. +class StoryExecutor : public Pokemon::TableExecutor{ public: explicit StoryExecutor(StoryEnv& env); @@ -102,11 +132,10 @@ class StoryExecutor : public Pokemon::StoryStepExecutor{ // The rows whose failure ends the program (StoryFailure::STOP): a // failed step there throws on instead of failing the step. void set_stop_rows(std::set rows){ - m_stop_rows = std::move(rows); + m_guard.set_stop_rows(std::move(rows)); } // A new attempt of a row: every trainer can see us again. virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override; - virtual Pokemon::Outcome run(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; protected: // The row running now. @@ -117,27 +146,8 @@ class StoryExecutor : public Pokemon::StoryStepExecutor{ virtual Pokemon::Outcome new_game(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; // verify_tutorial_settings(): fast text, Autosave off. virtual Pokemon::Outcome options(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; - // Variant: the plan's costs ("" route, "town", "robust", "line"). - virtual Pokemon::Outcome route(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; - // Each leg in D-pad taps, turning first. Variant "one_short_ok": a leg - // may end a tile short (a door lined up by sight after). Variant - // "to_wall": each leg walks until something stops it, for at most its - // tiles' time, as measured on the console; the pose is then unknown - // unless the step gives one. Variant "counted_wall": its one leg walks - // to the wall, waiting out anyone walking about in the way, and fails - // when the tiles walked are far off the map's from the step's start. - virtual Pokemon::Outcome legs(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; - // One D-pad step `direction`, turning first: onto a scene's trigger or - // into a door. Variant "to_banner": one tap into a cave mouth, then - // wait for pose_after's map's location banner. - virtual Pokemon::Outcome step(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; - // A at what we face; a dialogue must open. - virtual Pokemon::Outcome talk(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; // A for YES, B for NO, once the question's box shows. virtual Pokemon::Outcome answer(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; - // A dialogue opens (or has), then B through it to the overworld; - // variant "a": A through it, for lines that give an item. - virtual Pokemon::Outcome mash(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; // A trainer's text opens (or has) and ends in a battle, fought with the // best move; one lost fails the step unless `may_lose`. Variant // "doubles" for a tag battle. @@ -152,16 +162,31 @@ class StoryExecutor : public Pokemon::StoryStepExecutor{ virtual Pokemon::Outcome game(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; private: - Pokemon::Outcome run_guarded(Pokemon::RunState& state, const Pokemon::StoryStep& step); + StoryBoundActions console_actions(); StoryEnv& m_env; ConsoleStoryStepIO m_io; - // The steps that walk and talk (ROUTE, LEGS, STEP, TALK, MASH). + // The steps that walk and talk, the table's rows for them: + // - ROUTE. Variant: the plan's costs ("" route, "town", "robust", "line"). + // - LEGS: each leg in D-pad taps, turning first. Variant "one_short_ok": + // a leg may end a tile short (a door lined up by sight after). Variant + // "to_wall": each leg walks until something stops it, for at most its + // tiles' time, as measured on the console; the pose is then unknown + // unless the step gives one. Variant "counted_wall": its one leg walks + // to the wall, waiting out anyone walking about in the way, and fails + // when the tiles walked are far off the map's from the step's start. + // - STEP: one D-pad step `direction`, turning first: onto a scene's + // trigger or into a door. Variant "to_banner": one tap into a cave + // mouth, then wait for pose_after's map's location banner. + // - TALK: A at what we face; a dialogue must open. + // - MASH: a dialogue opens (or has), then B through it to the overworld; + // variant "a": A through it, for lines that give an item. StoryWalkSteps m_walks; std::string m_checkpoint; - std::map m_failures; std::map m_run_counts; - std::set m_stop_rows; + ConsoleStepGuard m_guard; + // The story's actions, its console rows bound to this executor. + Pokemon::StoryActionTable m_table; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.cpp new file mode 100644 index 0000000000..e79404048f --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.cpp @@ -0,0 +1,247 @@ +/* BDSP AutoStory - Story actions Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_StorySim.h" +#include "PokemonBDSP_AutoStory_StoryActions_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using Pokemon::RunState; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; + + +// Every step the story runs: the table's, and each row's save at its start. +std::vector> story_steps(){ + std::vector> out; + for (const StoryCheckpoint& row : story_checkpoints()){ + for (const StoryStep& step : row.steps){ + out.emplace_back(row.id, step); + } + StoryStep save; + save.kind = StoryStepKind::SAVE; + save.name = "save"; + save.variant = row.saves_in; + out.emplace_back(row.id, std::move(save)); + } + return out; +} + +// What ran a step before the table: the executors' own dispatch. An event +// named by the whole variant, whatever the kind; else the kind's method, +// which StoryWalkSteps does for the walking kinds, and the console (or +// the simulation's stand-in) for the others; else the base class's. +std::string old_dispatch(const StoryStep& step){ + const std::string kind = Pokemon::story_step_kind_name(step.kind); + if (story_events().contains(step.variant)){ + return "event " + step.variant; + } + switch (step.kind){ + case StoryStepKind::ROUTE: + case StoryStepKind::LEGS: + case StoryStepKind::STEP: + case StoryStepKind::TALK: + case StoryStepKind::MASH: + return "walk " + kind; + case StoryStepKind::NEW_GAME: + case StoryStepKind::OPTIONS: + case StoryStepKind::ANSWER: + case StoryStepKind::BATTLE: + case StoryStepKind::TRAIN: + case StoryStepKind::HEAL: + case StoryStepKind::SAVE: + return "console " + kind; + default: + return "executor " + kind; + } +} + +// The table's binding that names what it would run, as a failure. +StoryBoundActions naming_actions(){ + const auto named = [](StoryStepKind kind){ + return [kind](RunState&, const StoryStep&){ + return Pokemon::outcome_failed("console", Pokemon::story_step_kind_name(kind)); + }; + }; + return StoryBoundActions{ + .new_game = named(StoryStepKind::NEW_GAME), + .options = named(StoryStepKind::OPTIONS), + .answer = named(StoryStepKind::ANSWER), + .battle = named(StoryStepKind::BATTLE), + .train = named(StoryStepKind::TRAIN), + .heal = named(StoryStepKind::HEAL), + .save = named(StoryStepKind::SAVE), + .event = [](const std::string& name) -> Pokemon::StoryActionFunction{ + return [name](RunState&, const StoryStep&){ + return Pokemon::outcome_failed("event", name); + }; + }, + }; +} + +// What `table` runs for `step`, in old_dispatch()'s words. A walking row +// is not run: it would walk. +std::string table_dispatch(const Pokemon::StoryActionTable& table, const StoryStep& step){ + const Pokemon::StoryAction* action = table.find(step); + if (action == nullptr){ + return std::string("executor ") + Pokemon::story_step_kind_name(step.kind); + } + if (!action->needs_console){ + return std::string("walk ") + Pokemon::story_step_kind_name(step.kind); + } + RunState state; + const Pokemon::Outcome outcome = action->act(state, step); + return outcome.failure + " " + outcome.detail; +} + + +UnitTestResult test_every_step_has_an_action(Logger& logger){ + SimExecutor sim(logger); + size_t steps = 0; + for (const StoryCheckpoint& row : story_checkpoints()){ + const std::vector unbound = Pokemon::lint_story_checkpoint(row, sim.actions()); + if (!unbound.empty()){ + return unbound.front(); + } + steps += row.steps.size(); + } + logger.log(std::format("{} rows, {} steps, each with an action.", story_checkpoints().size(), steps)); + return true; +} + +UnitTestResult test_table_runs_what_the_old_dispatch_ran(Logger& logger){ + GridSim sim({}, {0, 0}, Pokemon::Direction::NORTH, false); + std::vector notes; + SimMisses misses; + const SimWorldKnobs knobs; + const std::string step_name; + SimStoryStepIO io(sim, notes, misses, knobs, step_name, []{ return false; }, [](const Pokemon::Pose&){}); + StoryWalkSteps walks(io); + const Pokemon::StoryActionTable table = story_action_table(walks, naming_actions()); + + std::set> seen; + for (const auto& [row, step] : story_steps()){ + if (!seen.emplace(step.kind, step.variant).second){ + continue; + } + const std::string expected = old_dispatch(step); + const std::string actual = table_dispatch(table, step); + if (actual != expected){ + return std::format("{} {} ({} \"{}\"): the table runs \"{}\", the old dispatch ran \"{}\".", + row, step.name, Pokemon::story_step_kind_name(step.kind), step.variant, actual, expected); + } + } + logger.log(std::format("{} (kind, variant) pairs run as before.", seen.size())); + return true; +} + +UnitTestResult test_stubbed_steps_need_the_console(Logger& logger){ + SimExecutor sim(logger); + run_rows_on(sim, logger, {.from = "00.00", .to = "01.11"}); + logger.log("Steps the simulation does not play, by row:\n" + stub_report(sim.result())); + for (const auto& [row, step] : story_steps()){ + const Pokemon::StoryAction* action = sim.actions().find(step); + if (action != nullptr && action->needs_console){ + continue; + } + for (const SimRun::RowStart& start : sim.result().rows){ + if (start.row != row){ + continue; + } + for (const std::string& stubbed : start.stubbed){ + if (stubbed == step.name){ + return std::format("{} {}: stubbed, but the simulation plays its kind.", row, step.name); + } + } + } + } + if (!sim.result().error.empty()){ + return "The run failed: " + sim.result().error; + } + return true; +} + + + +struct AutoStoryStoryActionsInput{ + std::string name; + std::function body; +}; + +struct AutoStoryStoryActionsExpectation{ +}; + +struct AutoStoryStoryActionsCase{ + AutoStoryStoryActionsInput input; + AutoStoryStoryActionsExpectation expectation; +}; + +class Test_AutoStoryStoryActions : public UnitTest{ +public: + explicit Test_AutoStoryStoryActions(AutoStoryStoryActionsCase test_case) + : UnitTest("PokemonBDSP::AutoStory - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + AutoStoryStoryActionsCase m_case; +}; + +} // namespace + + +const AutoStoryStoryActionsCase AUTO_STORY_STORY_ACTIONS_CASES[] = { + { + .input = {"Story actions: every step of every row has an action", test_every_step_has_an_action}, + .expectation = {}, + }, + { + .input = {"Story actions: each (kind, variant) runs what the executors' own dispatch ran", test_table_runs_what_the_old_dispatch_ran}, + .expectation = {}, + }, + { + .input = {"Story actions: the steps the sim stubs from 00.00 to 01.11 all need the console", test_stubbed_steps_need_the_console}, + .expectation = {}, + }, +}; + +void add_tests_AutoStory_StoryActions(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_STORY_ACTIONS_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.h new file mode 100644 index 0000000000..ee24d30c9a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.h @@ -0,0 +1,28 @@ +/* BDSP AutoStory - Story actions Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryActions_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryActions_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// The story's action table (story_action_table()): every step of the +// story has an action, each runs what the executors' own dispatch ran +// before the table, and the steps the simulation stubs need the console. +void add_tests_AutoStory_StoryActions(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index 4aca2d5f4a..da430422c5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -11,7 +11,6 @@ #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" -#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_StorySim.h" @@ -560,18 +559,50 @@ std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ return off_pose(*expected); } +Outcome SimExecutor::stub(){ + if (!m_result.rows.empty()){ + m_result.rows.back().stubbed.push_back(m_step); + } + m_sim.end_dialogue(); + return Pokemon::outcome_ok(); +} + +// The steps that need the console: stubbed, but for the Center's door and +// the speeches after a battle. +StoryBoundActions SimExecutor::sim_actions(){ + const auto stubbed = [this](RunState&, const StoryStep&){ + return stub(); + }; + return StoryBoundActions{ + .new_game = stubbed, + .options = stubbed, + .answer = stubbed, + .battle = [this](RunState& state, const StoryStep& step){ + return battle(state, step); + }, + .train = stubbed, + .heal = [this](RunState& state, const StoryStep& step){ + return heal(state, step); + }, + .save = stubbed, + .event = [stubbed](const std::string&) -> Pokemon::StoryActionFunction{ + return stubbed; + }, + }; +} + Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ if (!m_start_mismatch.empty()){ return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); } m_far = step.pose_after; - if (story_events().contains(step.variant)){ - return stub(); - } // A scene goes on from where the step before left us. A route walks // on the world it plans on (Jubilife alone has no Route 204 north of it). - const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || - step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK; + // An event of a walking kind (talk_to_wanderer) is the console's. + const Pokemon::StoryAction* action = m_table.find(step); + const bool walks = (step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || + step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK) && + action != nullptr && !action->needs_console; const StoryWorld* on = step.kind == StoryStepKind::ROUTE && step.target && !state.pose.map.empty() ? story_plan_world(state.pose.map, step.target->map) : nullptr; // A world of one map is sim_world()'s, with its people. @@ -583,7 +614,7 @@ Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ m_passed_over = true; return Pokemon::outcome_ok(); } - return Pokemon::StoryStepExecutor::run(state, step); + return Pokemon::TableExecutor::run(state, step); } Outcome SimExecutor::run(RunState& state, const StoryStep& step){ @@ -677,6 +708,17 @@ bool ends_on(const SimRun& run, const Pose& pose){ std::string end_of(const SimRun& run){ return run.world ? describe(*run.world, run.end) : "nowhere"; } +std::string stub_report(const SimRun& run){ + std::string out; + for (const SimRun::RowStart& row : run.rows){ + out += std::format("{}: {} stubbed", row.row, row.stubbed.size()); + for (size_t i = 0; i < row.stubbed.size(); i++){ + out += (i == 0 ? ": " : ", ") + row.stubbed[i]; + } + out += "\n"; + } + return out; +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index de8a781481..2e58b66fff 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -24,9 +24,12 @@ #include "Common/Cpp/Logging/AbstractLogger.h" #include "Common/Cpp/TestRunners/UnitTest.h" #include "CommonFramework/ImageTools/ImageStats.h" +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" #include "Pokemon/AutoStory/Pokemon_StorySegments.h" #include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" @@ -204,11 +207,13 @@ struct SimRun{ std::string failed_step; // Walking steps that end where nothing says, as "row step". std::vector unchecked; - // Each row run, with the fades and banners looked for before it. + // Each row run, with the fades and banners looked for before it, and + // its steps the simulation did not play (stub()), in order. struct RowStart{ std::string row; size_t fades; size_t banners; + std::vector stubbed = {}; }; std::vector rows; // Where the player stood after the last step, if placed. @@ -324,16 +329,22 @@ std::vector story_vars(); // The maps' coord events whose story variable holds, as triggers. std::vector story_triggers(); -// The program's walking steps on the simulation, the rest stubbed. -class SimExecutor : public Pokemon::StoryStepExecutor{ +// The program's walking steps on the simulation, the rest stubbed: the +// story's action table (story_action_table()), its rows that need the +// console bound to the stand-ins below. +class SimExecutor : public Pokemon::TableExecutor{ public: + // The table and the guard are members, built after the base: it only + // keeps references to them until a step runs. explicit SimExecutor(Logger& logger, SimMisses misses = {}, SimWorldKnobs knobs = {}) - : m_logger(logger) + : Pokemon::TableExecutor(m_table, m_guard) + , m_logger(logger) , m_misses(misses) , m_knobs(std::move(knobs)) , m_sim({}, {0, 0}, Pokemon::Direction::NORTH, false) , m_io(m_sim, m_notes, m_misses, m_knobs, m_step, [this]{ return cross(); }, [this](const Pokemon::Pose& far){ cross_to(far); }) , m_walks(m_io) + , m_table(story_action_table(m_walks, sim_actions())) {} const SimMisses& misses() const{ @@ -342,6 +353,10 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ const SimRun& result() const{ return m_result; } + // The story's actions as the simulation binds them. + const Pokemon::StoryActionTable& actions() const{ + return m_table; + } virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ m_row = data.id; m_start_mismatch = data.start ? off_pose(*data.start) : ""; @@ -354,11 +369,6 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ virtual Pokemon::Outcome run(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; protected: - virtual Pokemon::Outcome route(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.route(state, step); } - virtual Pokemon::Outcome legs(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.legs(state, step); } - virtual Pokemon::Outcome step(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.step(state, step); } - virtual Pokemon::Outcome talk(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.talk(state, step); } - virtual Pokemon::Outcome mash(Pokemon::RunState& state, const Pokemon::StoryStep& step) override{ return m_walks.mash(state, step); } virtual Pokemon::Outcome heal(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; virtual Pokemon::Outcome new_game(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } virtual Pokemon::Outcome options(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } @@ -370,11 +380,18 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ virtual Pokemon::Outcome game(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } private: + // A failed step fails the run as it threw: the simulation has no save + // to reload. + class SimStepGuard : public Pokemon::StepGuard{ + public: + virtual bool stops_on_failure(const Pokemon::StoryStep&) const override{ + return true; + } + }; + // A step the simulation does not play: its dialogue opened and closed. - Pokemon::Outcome stub(){ - m_sim.end_dialogue(); - return Pokemon::outcome_ok(); - } + Pokemon::Outcome stub(); + StoryBoundActions sim_actions(); const StoryWorld* sim_world(const std::string& map) const; SimWorld setup(const StoryWorld* world) const; void arm(const std::string& after); @@ -395,6 +412,8 @@ class SimExecutor : public Pokemon::StoryStepExecutor{ GridSim m_sim; SimStoryStepIO m_io; StoryWalkSteps m_walks; + SimStepGuard m_guard; + Pokemon::StoryActionTable m_table; // The planner's worlds with sim_people() on them, by world and who. mutable std::map, std::unique_ptr> m_peopled; // The steps of this row that have run. @@ -429,6 +448,9 @@ std::vector table_with(const std::string& row, const Pokemon::S bool ends_on(const SimRun& run, const Pokemon::Pose& pose); // Where the run ended, described; "nowhere" if never placed. std::string end_of(const SimRun& run); +// Each row's steps the simulation did not play, a line a row: +// "01.03: 2 stubbed: save, gym_until_roark_beaten". +std::string stub_report(const SimRun& run); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 93963cd18c..3c571301d7 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1724,6 +1724,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_NewGame.h Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Settings.cpp Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Settings.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -1736,6 +1738,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp From 56ecb7421b9b7c60898f9a001a60448596400bc2 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 02:29:56 -0800 Subject: [PATCH 079/166] BDSP AutoStory: door runs and tap steps take a fade's hold unseen, on the sim too run_into_door() and tap_to_banner() judge a warp's fade with WarpFadeWatch (DOOR_FADE_RULE, TAP_FADE_RULE: the same thresholds as their old watchers, now from BDSP_FADE_PROFILE), so a fade whose hold fell between two frames still shows, at the scene after the fall. The simulation emits a fade's frames (sim_fade_frames()) through the same watches, and SimMisses::hold drops one fade's hold: every row from 00.00 to 01.11 still passes with any one of them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryStepIO.cpp | 98 +-- .../PokemonBDSP_AutoStory_StoryStepIO.h | 17 +- ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 64 +- .../PokemonBDSP_AutoStory_StorySim.cpp | 79 +- .../PokemonBDSP_AutoStory_StorySim.h | 40 +- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 683 +++++++++--------- 6 files changed, 574 insertions(+), 407 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index ea04347f31..f0aca3b10e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -12,6 +12,7 @@ #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" #include "CommonFramework/GlobalAutoPaths.h" #include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" #include "CommonTools/Async/InferenceRoutines.h" #include "CommonTools/VisualDetectors/BlackScreenDetector.h" @@ -40,10 +41,6 @@ using Pokemon::Direction; namespace{ -// A door run's dark screen, a channel's mean brightness 0 to 255: cave -// fades reach ~45..64, r24's dim fade goes darker. -constexpr double FADE_DARKNESS = 75; - DpadPosition dpad_toward(Direction direction){ return direction == Direction::NORTH ? DPAD_UP : @@ -51,55 +48,54 @@ DpadPosition dpad_toward(Direction direction){ direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; } -// A dark-screen watcher that fires only from `from` on, and keeps when the -// screen last went dark: where a wild battle's fade began. -class DarkFrom : public VisualInferenceCallback{ +// A door run's fade watch (DOOR_FADE_RULE) that fires only from `from` on. +// It keeps a small copy of each frame for the scene comparison, and the +// fade it saw. +class DoorFadeFrom : public VisualInferenceCallback{ public: - DarkFrom(BlackScreenWatcher& dark, WallClock from) - : VisualInferenceCallback("DarkFrom") - , m_dark(dark) + explicit DoorFadeFrom(WallClock from) + : VisualInferenceCallback("DoorFadeFrom") + , m_watch(DOOR_FADE_RULE) , m_from(from) {} virtual void make_overlays(VideoOverlaySet& items) const override{ - m_dark.make_overlays(items); + items.add(COLOR_RED, {0.1, 0.1, 0.8, 0.8}); } virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ - const bool dark = m_dark.process_frame(frame, timestamp); - if (dark && !m_was_dark){ - m_went_dark = timestamp; - } - m_was_dark = dark; - return dark && timestamp >= m_from; + const Pokemon::TransitionSample sample = Pokemon::transition_sample(VideoSnapshot(frame.scale_to(192, 108), timestamp)); + m_fade = m_watch.push(sample); + return m_fade != WarpFade::NONE && timestamp >= m_from; } - // When the screen last went dark; WallClock::max() if it has not. - WallClock went_dark() const{ - return m_went_dark; + WarpFade fade() const{ + return m_fade; + } + const WarpFadeWatch& watch() const{ + return m_watch; } private: - BlackScreenWatcher& m_dark; + WarpFadeWatch m_watch; WallClock m_from; - bool m_was_dark = false; - WallClock m_went_dark = WallClock::max(); + WarpFade m_fade = WarpFade::NONE; }; -// How one hold toward a door ended: run_until()'s index (0 dark, 1 white, -// 2 a line, 3 a wild battle, 4 the far map's banner; -1 time up), when the -// screen last went dark, and the banner read. +// How one hold toward a door ended: run_until()'s index (0 the fade, 1 a +// line, 2 a wild battle, 3 the far map's banner; -1 time up), the fade +// and how it showed, when the screen last went dark, and the banner read. struct DoorHoldEnd{ int ret; + WarpFade fade; + std::string how; WallClock went_dark; std::string banner; }; DoorHoldEnd hold_into_door(VideoStream& stream, ProControllerContext& context, DpadPosition dpad, bool run, Milliseconds hold, Milliseconds dark_from, const std::string& banner){ - BlackScreenWatcher dark(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, 3 * FADE_DARKNESS, 60, BlackScreenWatcher::FinderType::PRESENT, 50ms); - DarkFrom late_dark(dark, current_time() + dark_from); - WhiteScreenWatcher white(COLOR_BLUE, {0.1, 0.1, 0.8, 0.8}, WhiteScreenWatcher::FinderType::PRESENT, 60ms); + DoorFadeFrom fade(current_time() + dark_from); ShortDialogWatcher dialog(COLOR_YELLOW); BattleMenuWatcher battle(BattleType::STANDARD, COLOR_YELLOW); LocationBannerWatcher far_banner(banner); - std::vector watchers{{late_dark}, {white}, {dialog}, {battle}}; + std::vector watchers{{fade}, {dialog}, {battle}}; if (!banner.empty()){ watchers.emplace_back(far_banner); } @@ -109,14 +105,22 @@ DoorHoldEnd hold_into_door(VideoStream& stream, ProControllerContext& context, D } pbf_press_dpad(context, dpad, hold, 0ms); }, watchers); - return {.ret = ret, .went_dark = late_dark.went_dark(), .banner = ret == 4 ? far_banner.seen() : ""}; + return { + .ret = ret, + .fade = ret == 0 ? fade.fade() : WarpFade::NONE, + .how = fade.watch().how(), + .went_dark = fade.watch().went_dark().value_or(WallClock::max()), + .banner = ret == 3 ? far_banner.seen() : "", + }; } // Wild battles a run into a door flees and runs on after. constexpr size_t DOOR_RUN_BATTLES = 3; // Holds the D-pad toward a door (with B after the shoes) for `timeout` -// until the screen goes dark or a line shows. Returns whether it went dark. +// until its fade (DOOR_FADE_RULE) or a line shows. Returns what it saw. +// A fade whose hold fell between two frames shows at the scene after it, +// so a missed 50 ms fade no longer runs the whole timeout. // A line stops it: holding on under Mom's "Oh, Kosmos!" wasted 12 s (r45). // Dark in the first `dark_from` of running is not the door (lab-B // 2026-11-08: dark at 1.8 s, halfway down the mine's entrance hall). A wild @@ -129,7 +133,7 @@ WarpSeen run_into_door(VideoStream& stream, ProControllerContext& context, Direc for (size_t battles = 0;; battles++){ const WallClock start = current_time(); const DoorHoldEnd end = hold_into_door(stream, context, dpad_toward(direction), run, left, dark_from, banner); - if (end.ret == 3){ + if (end.ret == 2){ const WallClock stopped = std::min(end.went_dark, current_time()); const Milliseconds ran = std::chrono::duration_cast(stopped - start) - ROUTE_START_DELAY; const Milliseconds counted = std::clamp(ran, 0ms, left); @@ -143,12 +147,10 @@ WarpSeen run_into_door(VideoStream& stream, ProControllerContext& context, Direc return {}; } if (end.ret == 0){ - stream.log("[Story] run_into_door: black screen fade detected."); + stream.log(std::format("[Story] run_into_door: {} detected ({}).", warp_fade_name(end.fade), end.how)); }else if (end.ret == 1){ - stream.log("[Story] run_into_door: white screen fade detected."); - }else if (end.ret == 2){ stream.log("[Story] run_into_door: dialog detected."); - }else if (end.ret == 4){ + }else if (end.ret == 3){ stream.log("[Story] run_into_door: no fade seen, but the banner \"" + end.banner + "\" read."); }else if (end.went_dark != WallClock::max()){ // Dark only before dark_from: early, or the door's fade itself. @@ -157,10 +159,7 @@ WarpSeen run_into_door(VideoStream& stream, ProControllerContext& context, Direc }else{ stream.log("[Story] run_into_door: timed out without detecting fade."); } - return { - .fade = end.ret == 0 ? WarpFade::BLACK : end.ret == 1 ? WarpFade::WHITE : WarpFade::NONE, - .banner = end.banner, - }; + return {.fade = end.fade, .banner = end.banner}; } } @@ -190,11 +189,12 @@ void log_new_banner_read(VideoStream& stream, const std::string& read, std::stri } // Looks for the location banner `banner` for up to `wait`, and with -// `fade` for the fade (fade_of_screen()). Logs each distinct banner read +// `fade` for the fade, each frame to `fade`'s watch (TAP_FADE_RULE), which +// follows the taps from before the first. Logs each distinct banner read // and how the wait ended: the Oreburgh Gate's entry missed its banner twice // (lab-B, 2026-11-08 15:31 and 15:39) though a hand probe saw it 1.5 s // after the fade, and nothing said why. -TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const std::string& banner, Milliseconds wait, bool fade){ +TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const std::string& banner, Milliseconds wait, WarpFadeWatch* fade){ const WallClock start = current_time(); const WallClock deadline = start + wait; std::string last_read; @@ -217,7 +217,7 @@ TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const return TapLook::BANNER; } darkest = std::min(darkest, brightness_of(screen)); - if (fade && screen && fade_of_screen(*screen.frame) != WarpFade::NONE){ + if (fade != nullptr && screen && fade->push(Pokemon::transition_sample(screen)) != WarpFade::NONE){ return TapLook::DARK; } if (current_time() >= deadline){ @@ -275,14 +275,18 @@ WarpSeen ConsoleStoryStepIO::run_into_door(Direction direction, bool run, Millis std::optional ConsoleStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ const std::string& banner = story_banner_name(map); m_context.wait_for_all_requests(); - if (look_after_tap(m_stream, m_context, banner, 0ms, true) == TapLook::BANNER){ + WarpFadeWatch watch(TAP_FADE_RULE); + if (look_after_tap(m_stream, m_context, banner, 0ms, &watch) == TapLook::BANNER){ m_stream.log("[Banner] \"" + banner + "\" shows before the first tap: through already."); return 0; } for (size_t tap = 1; tap <= max_taps; tap++){ pbf_press_dpad(m_context, dpad_toward(direction), 160ms, 0ms); - const TapLook look = look_after_tap(m_stream, m_context, banner, 1500ms, true); - if (look == TapLook::DARK && look_after_tap(m_stream, m_context, banner, 8000ms, false) != TapLook::BANNER){ + const TapLook look = look_after_tap(m_stream, m_context, banner, 1500ms, &watch); + if (look == TapLook::DARK){ + m_stream.log("[Banner] the fade: " + watch.how() + "."); + } + if (look == TapLook::DARK && look_after_tap(m_stream, m_context, banner, 8000ms, nullptr) != TapLook::BANNER){ m_stream.log("[Banner] a fade, no \"" + banner + "\" banner after it: counting the fade.", COLOR_ORANGE); } if (look != TapLook::NOTHING){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h index 6aa734d890..73c0d79a3c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h @@ -27,6 +27,17 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ +// How a door run and a tap step take a warp's fade (WarpFadeWatch), the +// console's and the simulation's alike. A door run counts the partial +// tier's dark (a doorway's dim fade frames) held 50 ms and white held +// 60 ms, as its black and white watchers did (lab-B to 2026-11-08); a tap +// step, looking every 100 ms, the uniform tier at once, as fade_of() did. +// Either also takes a fade whose hold it did not see, at the other scene +// after the fall. +constexpr WarpFadeRule DOOR_FADE_RULE{.partial_dark = true, .dark_for = Milliseconds(50), .white_for = Milliseconds(60)}; +constexpr WarpFadeRule TAP_FADE_RULE{}; + + // Abstract interface for story step input/output operations. class StoryStepIO{ public: @@ -44,7 +55,7 @@ class StoryStepIO{ // JSON map's name) shows, for at most `limit`. Returns whether it showed. virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string& label) = 0; // Holds the D-pad toward a door (running with `run`) for `timeout` until - // the screen goes dark or white, `banner` (a map's banner name, "" for + // its fade (DOOR_FADE_RULE), `banner` (a map's banner name, "" for // none) reads, or a line shows. A dark screen in the first `dark_from` // of running is not the door's fade, and a wild battle on the way is // fled, the run going on for the time left. Returns what it saw of the @@ -52,8 +63,8 @@ class StoryStepIO{ virtual WarpSeen run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), Milliseconds dark_from = Milliseconds(0), const std::string& banner = "") = 0; // D-pad taps `direction` one at a time, each looked at, toward a door - // or cave mouth, until its fade (fade_of(): uniform, so a dim cave floor - // is none) or the location banner of `map` (a JSON map's name), for at + // or cave mouth, until its fade (TAP_FADE_RULE: uniform, so a dim cave + // floor is none) or the location banner of `map` (a JSON map's name), for at // most `max_taps`; after a fade, no more taps. Either one alone is the // way through. The watch starts before the first tap: a banner up then // is 0 taps. Returns the taps it took, or nothing if neither showed. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp index 97f98b9c59..e401c39aaa 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -125,6 +126,31 @@ UnitTestResult gate_plan_one_run(Logger& logger){ return plan->size() <= 2 ? UnitTestResult(true) : UnitTestResult(std::format("{} legs: {}", plan->size(), legs)); } +// What a single miss leaves out: a fade whole, a fade's hold, or a banner. +enum class SingleMiss{ + FADE, + HOLD, + BANNER, +}; + +// The run of the row the clean run's `index`th fade or banner (`rows`' +// counts) falls in, with that one missed as `kind` says; none if it passes. +std::optional run_single_miss(Logger& logger, const std::vector& rows, SingleMiss kind, size_t index){ + const bool fade = kind != SingleMiss::BANNER; + size_t k = 0; + while (k + 1 < rows.size() && (fade ? rows[k + 1].fades : rows[k + 1].banners) <= index){ + k++; + } + const size_t in_row = index - (fade ? rows[k].fades : rows[k].banners); + SimMisses misses{.fade = {}, .banner = {}}; + (kind == SingleMiss::FADE ? misses.fade : kind == SingleMiss::HOLD ? misses.hold : misses.banner) = in_row; + SimExecutor executor(logger, misses); + if (run_rows_on(executor, logger, {.from = rows[k].row, .to = rows[k].row}).completed){ + return std::nullopt; + } + return executor.result(); +} + // Each fade and each banner the clean run looks for, missed alone: the // row it falls in must still pass, but for a miss in one of `skip`'s steps. // A door step once accepted only its fade, so a missed fade there failed a @@ -137,18 +163,10 @@ UnitTestResult every_single_miss(Logger& logger, const std::set& sk const std::vector& rows = clean.result().rows; std::vector failed; const auto miss = [&](bool fade, size_t index){ - size_t k = 0; - while (k + 1 < rows.size() && (fade ? rows[k + 1].fades : rows[k + 1].banners) <= index){ - k++; - } - SimMisses misses{.fade = {}, .banner = {}}; - (fade ? misses.fade : misses.banner) = index - (fade ? rows[k].fades : rows[k].banners); - SimExecutor executor(logger, misses); - if (!run_rows_on(executor, logger, {.from = rows[k].row, .to = rows[k].row}).completed - && !skip.contains(executor.result().failed_step) - ){ + const std::optional run = run_single_miss(logger, rows, fade ? SingleMiss::FADE : SingleMiss::BANNER, index); + if (run && !skip.contains(run->failed_step)){ failed.push_back(std::format("{} {} missed: stopped in {}: {}", fade ? "fade" : "banner", index, - executor.result().failed_step, executor.result().error)); + run->failed_step, run->error)); } }; for (size_t i = 0; i < clean.misses().fades; i++){ @@ -164,6 +182,29 @@ UnitTestResult every_single_miss(Logger& logger, const std::set& sk return failed.empty() ? UnitTestResult(true) : UnitTestResult(out); } +// Each fade the clean run looks for with only its hold unseen, a short +// fade between two frames (the door's watcher missed 13 of 35 fades on +// lab-B, 2026-11-08): the program's fade watch takes the scene after the +// fall, so every row passes, at every warp, ONE_SIGNAL_STEPS' too. +UnitTestResult every_single_hold_miss(Logger& logger){ + SimExecutor clean(logger); + if (!run_rows_on(clean, logger, {.from = "00.00", .to = "01.11"}).completed){ + return "the run fails without misses: " + clean.result().error; + } + std::vector failed; + for (size_t i = 0; i < clean.misses().fades; i++){ + const std::optional run = run_single_miss(logger, clean.result().rows, SingleMiss::HOLD, i); + if (run){ + failed.push_back(std::format("fade {}'s hold unseen: stopped in {}: {}", i, run->failed_step, run->error)); + } + } + std::string out = std::format("{} of {} fades with their hold unseen fail their row:", failed.size(), clean.misses().fades); + for (const std::string& line : failed){ + out += "\n " + line; + } + return failed.empty() ? UnitTestResult(true) : UnitTestResult(out); +} + // Oreburgh's street at night (88, game clock 00:25; 104 by day, r74), the // Gate's dim floor (46) and a cave mouth's dim fade (45 to 64): the tap // steps judge their fades with fade_of(): uniform, so a textured floor @@ -341,6 +382,7 @@ const FailureCase AUTO_STORY_FAILURE_CASES[] = { {.input = {"any one missed fade or banner at a warp that shows both: its row still passes", [](Logger& logger){ return every_single_miss(logger, ONE_SIGNAL_STEPS); }}, .expectation = {}}, + {.input = {"any one fade with its hold unseen from 00.00 to 01.11: every row still passes", every_single_hold_miss}, .expectation = {}}, {.input = {"01.02 to 01.05 at night, the Gate's dim floor", night_and_dim_floors}, .expectation = {}}, {.input = {"01.03 Roark's first line 7 s after the A press", roark_speaks_late}, .expectation = {}}, {.input = {"01.03 with Oreburgh's people wandering (the pokefan on 45, 37..39)", [](Logger& logger){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index da430422c5..4cf78510f5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -6,6 +6,7 @@ #include #include +#include #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h" @@ -32,6 +33,38 @@ ImageStats sim_screen(double brightness, double stddev){ return ImageStats(FloatPixel(brightness, brightness, brightness), FloatPixel(stddev, stddev, stddev), 1); } +std::vector sim_fade_frames(double floor, double fade, bool hold_seen){ + constexpr Milliseconds FRAME = 33ms; + // The fall and the rise: halfway, in brightness and in texture. + const ImageStats between = sim_screen((floor + fade) / 2, (SIM_FLOOR_STDDEV + SIM_FADE_STDDEV) / 2); + std::vector looks{sim_screen(floor, SIM_FLOOR_STDDEV), between}; + if (hold_seen){ + for (size_t i = 0; i < 3; i++){ + looks.push_back(sim_screen(fade, SIM_FADE_STDDEV)); + } + looks.push_back(between); + } + looks.push_back(sim_screen(floor, SIM_FLOOR_STDDEV)); + std::vector frames; + for (size_t i = 0; i < looks.size(); i++){ + frames.push_back({.time = WallClock() + FRAME * (int64_t)i, .middle = looks[i]}); + } + return frames; +} + +WarpFade sim_watch_fade(const WarpFadeRule& rule, double floor, double fade, bool hold_seen){ + WarpFadeWatch watch(rule, [](const Pokemon::TransitionSample&, const Pokemon::TransitionSample&){ + return Pokemon::SceneChange::DIFFERENT; + }); + for (const Pokemon::TransitionSample& frame : sim_fade_frames(floor, fade, hold_seen)){ + const WarpFade seen = watch.push(frame); + if (seen != WarpFade::NONE){ + return seen; + } + } + return WarpFade::NONE; +} + SimBeat sim_line(std::string what){ return {.what = std::move(what), .line = true}; } @@ -107,14 +140,40 @@ void SimStoryStepIO::settle(Button, const std::string& label, bool fade, const s m_sim.end_dialogue(); } +SimStoryStepIO::FadeShown SimStoryStepIO::next_fade(){ + const size_t fade = m_misses.fades++; + const FadeShown shown = m_misses.fade == fade ? FadeShown::UNSEEN : m_misses.hold == fade ? FadeShown::HOLD_UNSEEN : FadeShown::SEEN; + m_misses.missed |= shown != FadeShown::SEEN; + return shown; +} + +WarpFade SimStoryStepIO::watched_fade(const WarpFadeRule& rule, double fade){ + const FadeShown shown = next_fade(); + return shown == FadeShown::UNSEEN ? WarpFade::NONE : sim_watch_fade(rule, floor_here(), fade, shown == FadeShown::SEEN); +} + +// A door's fade through the program's door watch: a hold missed shows at +// the scene after it. A fade missed whole, the run goes on holding and +// sees the far map's `banner` show after it, if it has one. +WarpSeen SimStoryStepIO::door_fade(const std::string& banner){ + const WarpFade fade = watched_fade(DOOR_FADE_RULE, SIM_DOOR_FADE); + if (fade != WarpFade::NONE){ + return {.fade = fade}; + } + m_misses.fade_unseen = true; + return {.banner = !banner.empty() && !banner_missed() ? banner : ""}; +} + // A hold until something stops us. A door stops it at the fade, which // fails the step; a fade missed lets the hold go on past the mouth (r81's -// timed walk south out of the Ravaged Path, onto Route 204's cliff). +// timed walk south out of the Ravaged Path, onto Route 204's cliff). The +// walk's watchers take uniform frames only, so a fade whose hold they +// did not see is missed too. void SimStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ m_sim.tap(direction, ROUTE_TURN_TAP, false); Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); SimMove move = m_sim.hold(direction, limit, SimPace::WALK); - if (move.stop == SimStop::WARP && fade_missed() && m_far_side()){ + if (move.stop == SimStop::WARP && next_fade() != FadeShown::SEEN && m_far_side()){ limit -= std::min(limit, move.time); move = m_sim.hold(direction, limit, SimPace::WALK); } @@ -155,9 +214,9 @@ double SimStoryStepIO::floor_here() const{ // D-pad taps, each looked at, until the fade or the banner (the console's // ConsoleStoryStepIO::tap_to_banner()): none if the banner shows before // the first. Each look stands still, so a banner on the far side reads at -// once. A look the program's fade_of() takes for a fade ends the taps: a -// warp's fade, or a floor read as one; with the fade missed the look still -// sees the banner. +// once. A fade the program's tap watch (TAP_FADE_RULE) sees ends the taps, +// its hold seen or not; with the fade missed whole the look still sees the +// banner. std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ if (m_misses.through == m_misses.tap_steps++){ m_misses.missed = true; @@ -174,16 +233,14 @@ std::optional SimStoryStepIO::tap_to_banner(Direction direction, const s if (move.stop == SimStop::DIALOG){ return std::nullopt; } - ImageStats look = sim_screen(floor_here(), SIM_FLOOR_STDDEV); + WarpFade fade = WarpFade::NONE; if (move.stop == SimStop::WARP){ - const auto fade = m_knobs.fade_into.find(map); - if (!fade_missed()){ - look = sim_screen(fade == m_knobs.fade_into.end() ? SIM_DOOR_FADE : fade->second, SIM_FADE_STDDEV); - } + const auto into = m_knobs.fade_into.find(map); + fade = watched_fade(TAP_FADE_RULE, into == m_knobs.fade_into.end() ? SIM_DOOR_FADE : into->second); crossed = m_far_side(); } const bool banner = crossed && on_map(map) && !banner_missed(); - if (banner || fade_of(look) != WarpFade::NONE){ + if (banner || fade != WarpFade::NONE){ return tap; } } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index 2e58b66fff..a5fdb851df 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -43,7 +43,9 @@ namespace PokemonBDSP{ // Which detections the simulation misses on purpose (#162): the `fade`th // door fade (run_into_door(), from 0) or the `banner`th map banner // (run_until_map()) of the run goes unseen, though the player did go -// through. The console missed both (r75, r81). The `dark`th door run reads +// through. The console missed both (r75, r81). The `hold`th fade (counted +// with `fade`'s) shows its fall and the scene after but not its hold: a +// short fade's hold between two frames. The `dark`th door run reads // dark SIM_FALSE_DARK in, short of the door, as lab-B's did on 2026-11-08. // The `through`th tap step (tap_to_banner(), from 0) starts on its far side, // its banner gone unless `through_banner`: the walk before it slid onto the @@ -55,6 +57,7 @@ namespace PokemonBDSP{ struct SimMisses{ std::optional fade; std::optional banner; + std::optional hold = {}; std::optional dark = {}; std::optional through = {}; bool through_banner = false; @@ -196,6 +199,14 @@ constexpr double SIM_FADE_STDDEV = 1; constexpr double SIM_FLOOR_STDDEV = 20; // The screen's middle as fade_of() reads it: `brightness` a channel, `stddev` a channel. ImageStats sim_screen(double brightness, double stddev); +// The frames a warp's fade shows, 33 ms apart (the console's 30 fps): the +// floor (`floor`, textured), the fall, the hold of `fade` (uniform) and the +// rise, and the floor on the far side. Without `hold_seen` only the fall +// shows between the floors: a short fade's hold fell between two frames. +std::vector sim_fade_frames(double floor, double fade, bool hold_seen); +// The fade the program's WarpFadeWatch with `rule` sees in those frames; +// each scene after a fall is another (the far side's). +WarpFade sim_watch_fade(const WarpFadeRule& rule, double floor, double fade, bool hold_seen); // What a run on the simulation did. struct SimRun{ @@ -260,11 +271,7 @@ class SimStoryStepIO : public StoryStepIO{ if (m_sim.hold(direction, timeout, pace).stop != SimStop::WARP){ return {}; } - if (!fade_missed()){ - return {.fade = WarpFade::BLACK}; - } - m_misses.fade_unseen = true; - return {.banner = !banner.empty() && !banner_missed() ? banner : ""}; + return door_fade(banner); } // A fade missed on the way in stays missed: it was over before settle() // looked, which then fails as it does on the console after 120 s. The @@ -275,12 +282,21 @@ class SimStoryStepIO : public StoryStepIO{ virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) override; private: - // Whether the run misses this fade or this banner (SimMisses). - bool fade_missed(){ - const bool miss = m_misses.fade == m_misses.fades++; - m_misses.missed |= miss; - return miss; - } + // How the run shows its next fade (SimMisses): whole, its hold unseen, + // or not at all. + enum class FadeShown{ + SEEN, + HOLD_UNSEEN, + UNSEEN, + }; + FadeShown next_fade(); + // The next fade, of brightness `fade` from the floor here, as the + // program's watch with `rule` sees it. + WarpFade watched_fade(const WarpFadeRule& rule, double fade); + // What a door run that reached its warp saw (run_into_door()). + WarpSeen door_fade(const std::string& banner); + // Whether this door run reads dark short of the door, or the run + // misses this banner (SimMisses). bool false_dark(){ const bool dark = m_misses.dark == m_misses.doors++; m_misses.missed |= dark; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 181e4da95c..a5ff1525d6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -1,323 +1,360 @@ -/* BDSP AutoStory Story Sim Tests - * - * From: https://github.com/PokemonAutomation/ - * - * Rows of the story table run as the program runs them (the segment - * runner, make_story_segment()), with the program's own walking steps - * (StoryWalkSteps: ROUTE, LEGS, STEP, TALK, MASH) on the grid simulation. - * After each walking step the simulated player must stand, on the grid, - * on a tile the table gives; a step through a door must have warped. - * - * Events, battles, shops and saves are stubs: a dialogue they open is - * closed, and the table's pose_after puts the player where they end. A - * heal checks that a walk north from where we stand enters a door. A scene - * starts when the player steps onto one of the maps' coord events while - * its story variable holds (story_vars()). Rooms with no - * map (the Trainers' School) are passed over. Each row must start where - * the row before left the player. - * - * A tap or hold through a door or cave mouth stops on its tile, as the - * console stops at the fade; a hold that does not see the fade goes on - * onto the step's pose_after and on along it, and a location banner reads - * only a few tiles into its map (SIM_BANNER_TILES). The exit tests run - * r75's and r81's old open-ended walks that way. - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/TestRunners/UnitTestDatabase.h" -#include "Pokemon/AutoStory/Pokemon_StorySegments.h" -#include "Pokemon/AutoStory/Pokemon_TilePose.h" -#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h" -#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" -#include "PokemonBDSP_AutoStory_GridSim.h" -#include "PokemonBDSP_AutoStory_OldStorySteps.h" -#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" -#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" -#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" -#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" -#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" -#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" -#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" -#include "PokemonBDSP_AutoStory_StorySim.h" -#include "PokemonBDSP_AutoStory_StorySim_Tests.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -namespace{ - -using namespace std::chrono_literals; -using Pokemon::Direction; -using Pokemon::Outcome; -using Pokemon::Pose; -using Pokemon::RunState; -using Pokemon::StoryStep; -using Pokemon::StoryStepKind; -using Pokemon::TilePos; - -UnitTestResult run_exit_test(Logger& logger, const std::string& row_id, const StoryStep& old_step, const SimMisses& misses, const Pose& overshoot){ - SimExecutor executor(logger, misses); - const std::vector rows = table_with(row_id, old_step); - run_rows_on(executor, logger, {.from = row_id, .to = row_id}, rows); - const SimRun& run = executor.result(); - logger.log(std::format("The old {}: {}, ended on {}.", old_step.name, run.error, end_of(run))); - if (run.failed_step != row_id + " " + old_step.name || !ends_on(run, overshoot)){ - return std::format("the old {} should end on {} and fail there; it ended on {}: {}", - old_step.name, Pokemon::to_string(overshoot), end_of(run), run.error.empty() ? "no failure" : run.error); - } - SimExecutor clean(logger); - if (!run_rows_on(clean, logger, {.from = row_id, .to = row_id}).completed){ - return "the table's row fails without misses: " + clean.result().error; - } - std::vector runs; - for (size_t i = 0; i < clean.misses().fades; i++){ - runs.push_back({.fade = i, .banner = std::nullopt}); - } - for (size_t i = 0; i < clean.misses().banners; i++){ - runs.push_back({.fade = std::nullopt, .banner = i}); - } - for (const SimMisses& m : runs){ - SimExecutor sim(logger, m); - run_rows_on(sim, logger, {.from = row_id, .to = row_id}); - if (ends_on(sim.result(), overshoot)){ - return std::format("the table's {} ended on {} with a miss in {}.", old_step.name, end_of(sim.result()), - sim.result().missed_step); - } - } - return true; -} - -UnitTestResult test_coord_events(Logger&){ - for (const auto& [map, json] : bdsp_map_json()){ - const StoryWorld* world = story_plan_world(map, map); - for (const CoordEvent& event : world == nullptr ? std::vector{} : story_coord_events(map)){ - const auto open = [&](const TilePos& pos){ - const TilePos tile = story_to_world(*world, map, pos); - return standable(*world, tile) || world->tile(tile) == Pokemon::TileKind::DOOR; - }; - if (!std::ranges::any_of(event.tiles, open)){ - return std::format("{} {}: no tile is open ground or a door.", map, event.name); - } - } - } - const size_t armed = story_triggers().size(); - return armed == story_vars().size() ? UnitTestResult(true) - : UnitTestResult(std::format("Expected {} coord events armed by the story's variables, found {}.", story_vars().size(), armed)); -} - -std::string miss(Logger& logger, const SimRun& clean, bool fade, size_t index){ - size_t k = 0; - while (k + 1 < clean.rows.size() && (fade ? clean.rows[k + 1].fades : clean.rows[k + 1].banners) <= index){ - k++; - } - const SimRun::RowStart& start = clean.rows[k]; - SimMisses misses; - (fade ? misses.fade : misses.banner) = index - (fade ? start.fades : start.banners); - SimExecutor executor(logger, misses); - const Pokemon::SegmentReport report = run_rows_on(executor, logger, - {.from = start.row, .to = clean.rows[std::min(k + 1, clean.rows.size() - 1)].row}); - const SimRun& run = executor.result(); - const std::string what = std::format("{} {}", fade ? "fade" : "banner", index); - logger.log(std::format("Missed {} in {}: {}.", what, run.missed_step, - report.completed ? "got over it" : "stopped in " + run.failed_step + ": " + run.error)); - if (report.completed || run.failed_step == run.missed_step){ - return ""; - } - return std::format("{} missed in {}, failed later in {}: {}", what, run.missed_step, run.failed_step, run.error); -} - -UnitTestResult test_story_sim_misses(Logger& logger){ - Pokemon::SegmentRange range{.from = "00.00", .to = "01.11"}; - SimExecutor clean(logger); - if (!run_rows_on(clean, logger, range).completed){ - return "the run fails without misses: " + clean.result().error; - } - logger.log(std::format("{} fades and {} banners to miss.", clean.misses().fades, clean.misses().banners)); - std::vector unseen; - for (size_t i = 0; i < clean.misses().fades + clean.misses().banners; i++){ - const std::string line = miss(logger, clean.result(), i < clean.misses().fades, i < clean.misses().fades ? i : i - clean.misses().fades); - if (!line.empty()){ - unseen.push_back(line); - } - } - std::string out = "Misses that went unseen:"; - for (const std::string& line : unseen){ - out += "\n " + line; - } - return unseen.empty() ? UnitTestResult(true) : UnitTestResult(out); -} - -UnitTestResult test_story_sim_whole_table(Logger& logger){ - return run_rows(logger, {.from = "00.00", .to = "01.11"}); -} - -UnitTestResult test_story_sim_each_row(Logger& logger){ - for (const StoryCheckpoint& row : story_checkpoints()){ - const auto res = run_rows(logger, {.from = row.id, .to = row.id}); - if (res.result != UnitTestResult::PASSED){ - return std::format("Row {} failed: {}", row.id, res.message); - } - } - return true; -} - -UnitTestResult test_exit_gate(Logger& logger){ - return run_exit_test(logger, "01.05", r75_old_gate_exit(), SimMisses{}, r75_pond_pocket()); -} - -UnitTestResult test_exit_ravaged_path(Logger& logger){ - return run_exit_test(logger, "01.09", r81_old_cave_exit(), SimMisses{.fade = 0, .banner = std::nullopt}, r81_below_the_mouth()); -} - -// lab-B 2026-11-08 15:31 to 15:54: 01.05's walk to the tile beside the -// Oreburgh Gate's mouth slid onto the warp, and the tap step after it began -// inside the Gate. With its banner up, the step ends there with no tap and -// no fade (the clean run's fade into the Gate is not seen); with it gone, -// it fails a few taps on, not across the Gate. -UnitTestResult test_tap_through_already(Logger& logger, bool banner){ - const std::vector rows = table_with("01.05", old_tap_into_the_gate()); - SimExecutor clean(logger); - run_rows_on(clean, logger, {.from = "01.05", .to = "01.05"}, rows); - SimExecutor through(logger, {.fade = {}, .banner = {}, .through = 1, .through_banner = banner}); - run_rows_on(through, logger, {.from = "01.05", .to = "01.05"}, rows); - const SimRun& run = through.result(); - const std::optional at = run.world ? story_to_local(*run.world, "OreburghGate", run.end) : std::nullopt; - const bool passed = banner - ? run.error.empty() && through.misses().fades + 1 == clean.misses().fades - : run.failed_step == "01.05 into_oreburgh_gate" && at && at->y == 22 && at->x >= 21; - return passed ? UnitTestResult(true) : UnitTestResult(std::format("failed in '{}' on {} after {} fades (clean {}): {}", - run.failed_step, end_of(run), through.misses().fades, clean.misses().fades, run.error.empty() ? "no failure" : run.error)); -} - -UnitTestResult test_story_sim_step_failure(Logger& logger, const std::string& row, const StoryStep& old_step, const std::string& expected_failed_step, const std::string& expected_error){ - SimExecutor executor(logger); - const std::vector rows = table_with(row, old_step); - run_rows_on(executor, logger, {.from = row, .to = row}, rows); - const SimRun& run = executor.result(); - if (run.failed_step != expected_failed_step || run.error.find(expected_error) == std::string::npos){ - return std::format("expected old {} to fail at '{}' with '{}', but got failed_step='{}', error='{}'.", - old_step.name, expected_failed_step, expected_error, run.failed_step, run.error); - } - return true; -} - -// lab-B 2026-11-08: 01.03's run into Oreburgh's Center saw no fade and went -// on to the nurse's counter. The heal must find it is inside and go on. -UnitTestResult test_heal_fade_unseen(Logger& logger){ - SimExecutor clean(logger); - run_rows_on(clean, logger, {.from = "01.03", .to = "01.03"}); - for (size_t i = 0; i < clean.misses().fades; i++){ - SimExecutor sim(logger, {.fade = i, .banner = {}}); - run_rows_on(sim, logger, {.from = "01.03", .to = "01.03"}); - const SimRun& run = sim.result(); - if (run.missed_step == "01.03 heal_oreburgh"){ - return run.error.empty() ? UnitTestResult(true) : UnitTestResult(std::format("failed in '{}': {}", run.failed_step, run.error)); - } - } - return "no fade in 01.03 heal_oreburgh to miss: the heal never ran into its door."; -} - -struct AutoStoryStorySimInput{ - std::string name; - std::function body; -}; - -struct AutoStoryStorySimExpectation{ -}; - -struct AutoStoryStorySimCase{ - AutoStoryStorySimInput input; - AutoStoryStorySimExpectation expectation; -}; - -class Test_AutoStoryStorySim : public UnitTest{ -public: - explicit Test_AutoStoryStorySim(AutoStoryStorySimCase test_case) - : UnitTest("PokemonBDSP::AutoStory - Story sim: " + test_case.input.name) - , m_case(std::move(test_case)) - {} - virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ - try{ - return m_case.input.body(logger); - }catch (Exception& e){ - return std::string(e.name()) + ": " + e.message(); - } - } - -private: - AutoStoryStorySimCase m_case; -}; - -} // namespace - -const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { - {.input = {"the maps' coord events are on open ground or doors", test_coord_events}, .expectation = {}}, - {.input = {"detector misses from 00.00 to 01.11", test_story_sim_misses}, .expectation = {}}, - {.input = {"00.00 to 01.11: the whole table, from the new game to Floaroma", test_story_sim_whole_table}, .expectation = {}}, - {.input = {"each row from 00.00 to 01.11 in isolation", test_story_sim_each_row}, .expectation = {}}, - {.input = {"01.02b, Barry's lines, then the Center past his doorstep (lab-B, 2026-11-08)", [](Logger& logger){ - return run_rows(logger, {.from = "01.02b", .to = "01.02b"}); - }}, .expectation = {}}, - {.input = {"r75, out of the Oreburgh Gate", test_exit_gate}, .expectation = {}}, - {.input = {"r81, out of the Ravaged Path", test_exit_ravaged_path}, .expectation = {}}, - {.input = {"01.05, a tap step begun through the Gate's mouth, its banner up (lab-B, 2026-11-08)", [](Logger& logger){ - return test_tap_through_already(logger, true); - }}, .expectation = {}}, - {.input = {"01.05, a tap step begun through the Gate's mouth, its banner gone (lab-B, 2026-11-08)", [](Logger& logger){ - return test_tap_through_already(logger, false); - }}, .expectation = {}}, - { - .input = {"01.03, a dark frame 1.8 s down the mine's entrance hall is not its mouth (lab-B, 2026-11-08)", [](Logger& logger){ - SimExecutor executor(logger, {.fade = {}, .banner = {}, .dark = 1}); - run_rows_on(executor, logger, {.from = "01.03", .to = "01.03"}); - const SimRun& run = executor.result(); - return run.missed_step == "01.03 into_the_coal_room" && run.error.empty() ? UnitTestResult(true) - : UnitTestResult(std::format("dark in '{}', failed in '{}': {}", run.missed_step, run.failed_step, run.error)); - }}, - .expectation = {}, - }, - { - .input = {"01.03, the Center's fade unseen, the heal goes on from the counter (lab-B, 2026-11-08)", test_heal_fade_unseen}, - .expectation = {}, - }, - { - .input = {"01.03, counted 19 taps south leaves player in hall", [](Logger& logger){ - return test_story_sim_step_failure(logger, "01.03", old_mine_hall_19("into_the_coal_room", Direction::SOUTH), "01.03 south_to_the_rock", "warp instead of a stop."); - }}, - .expectation = {}, - }, - { - .input = {"01.03, counted 19 taps north leaves player in hall", [](Logger& logger){ - return test_story_sim_step_failure(logger, "01.03", old_mine_hall_19("out_of_the_mine", Direction::NORTH), "01.03 north_to_the_centers_wall", "map_mismatch"); - }}, - .expectation = {}, - }, - { - .input = {"01.03, cut corner through coal room crate at col 29", [](Logger& logger){ - return test_story_sim_step_failure(logger, "01.03", old_coal_room_crate_cut(), "01.03 to_roarks_corner", "short_leg: south 2 moved 1"); - }}, - .expectation = {}, - }, -}; - -void add_tests_AutoStory_StorySim(UnitTestDatabase& database){ - for (const auto& item : AUTO_STORY_STORY_SIM_CASES){ - database.add(item); - } -} - -} // namespace PokemonBDSP -} // namespace NintendoSwitch -} // namespace PokemonAutomation +/* BDSP AutoStory Story Sim Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Rows of the story table run as the program runs them (the segment + * runner, make_story_segment()), with the program's own walking steps + * (StoryWalkSteps: ROUTE, LEGS, STEP, TALK, MASH) on the grid simulation. + * After each walking step the simulated player must stand, on the grid, + * on a tile the table gives; a step through a door must have warped. + * + * Events, battles, shops and saves are stubs: a dialogue they open is + * closed, and the table's pose_after puts the player where they end. A + * heal checks that a walk north from where we stand enters a door. A scene + * starts when the player steps onto one of the maps' coord events while + * its story variable holds (story_vars()). Rooms with no + * map (the Trainers' School) are passed over. Each row must start where + * the row before left the player. + * + * A tap or hold through a door or cave mouth stops on its tile, as the + * console stops at the fade; a hold that does not see the fade goes on + * onto the step's pose_after and on along it, and a location banner reads + * only a few tiles into its map (SIM_BANNER_TILES). The exit tests run + * r75's and r81's old open-ended walks that way. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_OldStorySteps.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_StorySim.h" +#include "PokemonBDSP_AutoStory_StorySim_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +namespace{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::Outcome; +using Pokemon::Pose; +using Pokemon::RunState; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + +UnitTestResult run_exit_test(Logger& logger, const std::string& row_id, const StoryStep& old_step, const SimMisses& misses, const Pose& overshoot){ + SimExecutor executor(logger, misses); + const std::vector rows = table_with(row_id, old_step); + run_rows_on(executor, logger, {.from = row_id, .to = row_id}, rows); + const SimRun& run = executor.result(); + logger.log(std::format("The old {}: {}, ended on {}.", old_step.name, run.error, end_of(run))); + if (run.failed_step != row_id + " " + old_step.name || !ends_on(run, overshoot)){ + return std::format("the old {} should end on {} and fail there; it ended on {}: {}", + old_step.name, Pokemon::to_string(overshoot), end_of(run), run.error.empty() ? "no failure" : run.error); + } + SimExecutor clean(logger); + if (!run_rows_on(clean, logger, {.from = row_id, .to = row_id}).completed){ + return "the table's row fails without misses: " + clean.result().error; + } + std::vector runs; + for (size_t i = 0; i < clean.misses().fades; i++){ + runs.push_back({.fade = i, .banner = std::nullopt}); + } + for (size_t i = 0; i < clean.misses().banners; i++){ + runs.push_back({.fade = std::nullopt, .banner = i}); + } + for (const SimMisses& m : runs){ + SimExecutor sim(logger, m); + run_rows_on(sim, logger, {.from = row_id, .to = row_id}); + if (ends_on(sim.result(), overshoot)){ + return std::format("the table's {} ended on {} with a miss in {}.", old_step.name, end_of(sim.result()), + sim.result().missed_step); + } + } + return true; +} + +UnitTestResult test_coord_events(Logger&){ + for (const auto& [map, json] : bdsp_map_json()){ + const StoryWorld* world = story_plan_world(map, map); + for (const CoordEvent& event : world == nullptr ? std::vector{} : story_coord_events(map)){ + const auto open = [&](const TilePos& pos){ + const TilePos tile = story_to_world(*world, map, pos); + return standable(*world, tile) || world->tile(tile) == Pokemon::TileKind::DOOR; + }; + if (!std::ranges::any_of(event.tiles, open)){ + return std::format("{} {}: no tile is open ground or a door.", map, event.name); + } + } + } + const size_t armed = story_triggers().size(); + return armed == story_vars().size() ? UnitTestResult(true) + : UnitTestResult(std::format("Expected {} coord events armed by the story's variables, found {}.", story_vars().size(), armed)); +} + +std::string miss(Logger& logger, const SimRun& clean, bool fade, size_t index){ + size_t k = 0; + while (k + 1 < clean.rows.size() && (fade ? clean.rows[k + 1].fades : clean.rows[k + 1].banners) <= index){ + k++; + } + const SimRun::RowStart& start = clean.rows[k]; + SimMisses misses; + (fade ? misses.fade : misses.banner) = index - (fade ? start.fades : start.banners); + SimExecutor executor(logger, misses); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, + {.from = start.row, .to = clean.rows[std::min(k + 1, clean.rows.size() - 1)].row}); + const SimRun& run = executor.result(); + const std::string what = std::format("{} {}", fade ? "fade" : "banner", index); + logger.log(std::format("Missed {} in {}: {}.", what, run.missed_step, + report.completed ? "got over it" : "stopped in " + run.failed_step + ": " + run.error)); + if (report.completed || run.failed_step == run.missed_step){ + return ""; + } + return std::format("{} missed in {}, failed later in {}: {}", what, run.missed_step, run.failed_step, run.error); +} + +UnitTestResult test_story_sim_misses(Logger& logger){ + Pokemon::SegmentRange range{.from = "00.00", .to = "01.11"}; + SimExecutor clean(logger); + if (!run_rows_on(clean, logger, range).completed){ + return "the run fails without misses: " + clean.result().error; + } + logger.log(std::format("{} fades and {} banners to miss.", clean.misses().fades, clean.misses().banners)); + std::vector unseen; + for (size_t i = 0; i < clean.misses().fades + clean.misses().banners; i++){ + const std::string line = miss(logger, clean.result(), i < clean.misses().fades, i < clean.misses().fades ? i : i - clean.misses().fades); + if (!line.empty()){ + unseen.push_back(line); + } + } + std::string out = "Misses that went unseen:"; + for (const std::string& line : unseen){ + out += "\n " + line; + } + return unseen.empty() ? UnitTestResult(true) : UnitTestResult(out); +} + +UnitTestResult test_story_sim_whole_table(Logger& logger){ + return run_rows(logger, {.from = "00.00", .to = "01.11"}); +} + +UnitTestResult test_story_sim_each_row(Logger& logger){ + for (const StoryCheckpoint& row : story_checkpoints()){ + const auto res = run_rows(logger, {.from = row.id, .to = row.id}); + if (res.result != UnitTestResult::PASSED){ + return std::format("Row {} failed: {}", row.id, res.message); + } + } + return true; +} + +UnitTestResult test_exit_gate(Logger& logger){ + return run_exit_test(logger, "01.05", r75_old_gate_exit(), SimMisses{}, r75_pond_pocket()); +} + +UnitTestResult test_exit_ravaged_path(Logger& logger){ + return run_exit_test(logger, "01.09", r81_old_cave_exit(), SimMisses{.fade = 0, .banner = std::nullopt}, r81_below_the_mouth()); +} + +// lab-B 2026-11-08 15:31 to 15:54: 01.05's walk to the tile beside the +// Oreburgh Gate's mouth slid onto the warp, and the tap step after it began +// inside the Gate. With its banner up, the step ends there with no tap and +// no fade (the clean run's fade into the Gate is not seen); with it gone, +// it fails a few taps on, not across the Gate. +UnitTestResult test_tap_through_already(Logger& logger, bool banner){ + const std::vector rows = table_with("01.05", old_tap_into_the_gate()); + SimExecutor clean(logger); + run_rows_on(clean, logger, {.from = "01.05", .to = "01.05"}, rows); + SimExecutor through(logger, {.fade = {}, .banner = {}, .through = 1, .through_banner = banner}); + run_rows_on(through, logger, {.from = "01.05", .to = "01.05"}, rows); + const SimRun& run = through.result(); + const std::optional at = run.world ? story_to_local(*run.world, "OreburghGate", run.end) : std::nullopt; + const bool passed = banner + ? run.error.empty() && through.misses().fades + 1 == clean.misses().fades + : run.failed_step == "01.05 into_oreburgh_gate" && at && at->y == 22 && at->x >= 21; + return passed ? UnitTestResult(true) : UnitTestResult(std::format("failed in '{}' on {} after {} fades (clean {}): {}", + run.failed_step, end_of(run), through.misses().fades, clean.misses().fades, run.error.empty() ? "no failure" : run.error)); +} + +UnitTestResult test_story_sim_step_failure(Logger& logger, const std::string& row, const StoryStep& old_step, const std::string& expected_failed_step, const std::string& expected_error){ + SimExecutor executor(logger); + const std::vector rows = table_with(row, old_step); + run_rows_on(executor, logger, {.from = row, .to = row}, rows); + const SimRun& run = executor.result(); + if (run.failed_step != expected_failed_step || run.error.find(expected_error) == std::string::npos){ + return std::format("expected old {} to fail at '{}' with '{}', but got failed_step='{}', error='{}'.", + old_step.name, expected_failed_step, expected_error, run.failed_step, run.error); + } + return true; +} + +// lab-B 2026-11-08: 01.03's run into Oreburgh's Center saw no fade and went +// on to the nurse's counter. The heal must find it is inside and go on. +UnitTestResult test_heal_fade_unseen(Logger& logger){ + SimExecutor clean(logger); + run_rows_on(clean, logger, {.from = "01.03", .to = "01.03"}); + for (size_t i = 0; i < clean.misses().fades; i++){ + SimExecutor sim(logger, {.fade = i, .banner = {}}); + run_rows_on(sim, logger, {.from = "01.03", .to = "01.03"}); + const SimRun& run = sim.result(); + if (run.missed_step == "01.03 heal_oreburgh"){ + return run.error.empty() ? UnitTestResult(true) : UnitTestResult(std::format("failed in '{}': {}", run.failed_step, run.error)); + } + } + return "no fade in 01.03 heal_oreburgh to miss: the heal never ran into its door."; +} + +// The sim's frames of a warp's fade through the program's own watches +// (sim_watch_fade()): a door's black, a cave mouth's dim fade and a cave +// exit's white, each with its hold seen and unseen. Only on a floor as +// dark as the fall (a street at night, 88) is a fade whose hold went unseen +// still missed: no frame shows the scene before it. +UnitTestResult test_sim_fade_frames(Logger&){ + struct FadeCase{ + const char* name; + bool door; + double floor; + double fade; + bool hold_seen; + WarpFade seen; + }; + const std::vector cases{ + {"a door's black", true, SIM_FLOOR, SIM_DOOR_FADE, true, WarpFade::BLACK}, + {"a door's black, its hold unseen", true, SIM_FLOOR, SIM_DOOR_FADE, false, WarpFade::BLACK}, + {"a tap into a door's black", false, SIM_FLOOR, SIM_DOOR_FADE, true, WarpFade::BLACK}, + {"a tap into a door's black, its hold unseen", false, SIM_FLOOR, SIM_DOOR_FADE, false, WarpFade::BLACK}, + {"a tap into a cave mouth's dim fade", false, SIM_FLOOR, SIM_DIM_FADE, true, WarpFade::BLACK}, + {"a tap into a cave mouth's dim fade, its hold unseen", false, SIM_FLOOR, SIM_DIM_FADE, false, WarpFade::BLACK}, + {"a tap into a cave exit's white", false, SIM_FLOOR, SIM_WHITE_FADE, true, WarpFade::WHITE}, + {"a tap into a cave exit's white, its hold unseen", false, SIM_FLOOR, SIM_WHITE_FADE, false, WarpFade::WHITE}, + {"a door's black from the Gate's dim floor (46), its hold unseen", true, 46, SIM_DOOR_FADE, false, WarpFade::BLACK}, + {"a tap from a street at night (88)", false, 88, SIM_DOOR_FADE, true, WarpFade::BLACK}, + {"a tap from a street at night (88), its hold unseen", false, 88, SIM_DOOR_FADE, false, WarpFade::NONE}, + }; + for (const FadeCase& item : cases){ + const WarpFade seen = sim_watch_fade(item.door ? DOOR_FADE_RULE : TAP_FADE_RULE, item.floor, item.fade, item.hold_seen); + if (seen != item.seen){ + return std::format("{}: saw {}, expected {}.", item.name, warp_fade_name(seen), warp_fade_name(item.seen)); + } + } + return true; +} + +struct AutoStoryStorySimInput{ + std::string name; + std::function body; +}; + +struct AutoStoryStorySimExpectation{ +}; + +struct AutoStoryStorySimCase{ + AutoStoryStorySimInput input; + AutoStoryStorySimExpectation expectation; +}; + +class Test_AutoStoryStorySim : public UnitTest{ +public: + explicit Test_AutoStoryStorySim(AutoStoryStorySimCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Story sim: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + AutoStoryStorySimCase m_case; +}; + +} // namespace + +const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { + {.input = {"the maps' coord events are on open ground or doors", test_coord_events}, .expectation = {}}, + {.input = {"detector misses from 00.00 to 01.11", test_story_sim_misses}, .expectation = {}}, + {.input = {"a warp's fade on the sim's frames, through the door's and the taps' watches", test_sim_fade_frames}, .expectation = {}}, + {.input = {"00.00 to 01.11: the whole table, from the new game to Floaroma", test_story_sim_whole_table}, .expectation = {}}, + {.input = {"each row from 00.00 to 01.11 in isolation", test_story_sim_each_row}, .expectation = {}}, + {.input = {"01.02b, Barry's lines, then the Center past his doorstep (lab-B, 2026-11-08)", [](Logger& logger){ + return run_rows(logger, {.from = "01.02b", .to = "01.02b"}); + }}, .expectation = {}}, + {.input = {"r75, out of the Oreburgh Gate", test_exit_gate}, .expectation = {}}, + {.input = {"r81, out of the Ravaged Path", test_exit_ravaged_path}, .expectation = {}}, + {.input = {"01.05, a tap step begun through the Gate's mouth, its banner up (lab-B, 2026-11-08)", [](Logger& logger){ + return test_tap_through_already(logger, true); + }}, .expectation = {}}, + {.input = {"01.05, a tap step begun through the Gate's mouth, its banner gone (lab-B, 2026-11-08)", [](Logger& logger){ + return test_tap_through_already(logger, false); + }}, .expectation = {}}, + { + .input = {"01.03, a dark frame 1.8 s down the mine's entrance hall is not its mouth (lab-B, 2026-11-08)", [](Logger& logger){ + SimExecutor executor(logger, {.fade = {}, .banner = {}, .dark = 1}); + run_rows_on(executor, logger, {.from = "01.03", .to = "01.03"}); + const SimRun& run = executor.result(); + return run.missed_step == "01.03 into_the_coal_room" && run.error.empty() ? UnitTestResult(true) + : UnitTestResult(std::format("dark in '{}', failed in '{}': {}", run.missed_step, run.failed_step, run.error)); + }}, + .expectation = {}, + }, + { + .input = {"01.03, the Center's fade unseen, the heal goes on from the counter (lab-B, 2026-11-08)", test_heal_fade_unseen}, + .expectation = {}, + }, + { + .input = {"01.03, counted 19 taps south leaves player in hall", [](Logger& logger){ + return test_story_sim_step_failure(logger, "01.03", old_mine_hall_19("into_the_coal_room", Direction::SOUTH), "01.03 south_to_the_rock", "warp instead of a stop."); + }}, + .expectation = {}, + }, + { + .input = {"01.03, counted 19 taps north leaves player in hall", [](Logger& logger){ + return test_story_sim_step_failure(logger, "01.03", old_mine_hall_19("out_of_the_mine", Direction::NORTH), "01.03 north_to_the_centers_wall", "map_mismatch"); + }}, + .expectation = {}, + }, + { + .input = {"01.03, cut corner through coal room crate at col 29", [](Logger& logger){ + return test_story_sim_step_failure(logger, "01.03", old_coal_room_crate_cut(), "01.03 to_roarks_corner", "short_leg: south 2 moved 1"); + }}, + .expectation = {}, + }, +}; + +void add_tests_AutoStory_StorySim(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_STORY_SIM_CASES){ + database.add(item); + } +} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation From 126630ff33e670aac4e0706bfeed039a8757cf0a Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 02:43:09 -0800 Subject: [PATCH 080/166] BDSP AutoStory: a comment for each fade rule Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h index 73c0d79a3c..ffd55a755a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h @@ -27,14 +27,14 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ -// How a door run and a tap step take a warp's fade (WarpFadeWatch), the -// console's and the simulation's alike. A door run counts the partial -// tier's dark (a doorway's dim fade frames) held 50 ms and white held -// 60 ms, as its black and white watchers did (lab-B to 2026-11-08); a tap -// step, looking every 100 ms, the uniform tier at once, as fade_of() did. -// Either also takes a fade whose hold it did not see, at the other scene -// after the fall. +// How a door run takes a warp's fade (WarpFadeWatch), on the console and +// the simulation alike: the partial tier's dark (a doorway's dim fade +// frames) held 50 ms, white held 60 ms, as its black and white watchers +// did (lab-B to 2026-11-08), or a fade whose hold it did not see, at the +// other scene after the fall. constexpr WarpFadeRule DOOR_FADE_RULE{.partial_dark = true, .dark_for = Milliseconds(50), .white_for = Milliseconds(60)}; +// How a tap step, looking every 100 ms, takes one: the uniform tier at +// once, as fade_of() did, or a fade whose hold it did not see. constexpr WarpFadeRule TAP_FADE_RULE{}; From cd85c946f3253459389fa6f67c59e9ef7be7f90d Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 03:24:44 -0800 Subject: [PATCH 081/166] BDSP sim: record a tap battle's screen events as the console's walk does GridSimRouteIO's taps now fill WalkResult::events from the leg's first tap: an encounter is recorded with record_tap_battle() at the tap that set it off (the one before, for a battle before its tap moved), and the taps that moved after it are counted, as the console's walk counts them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Simulation/PokemonBDSP_AutoStory_GridSim.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp index 0673b2577c..689d630410 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -6,6 +6,7 @@ #include #include +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegBattle.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP_AutoStory_GridSim.h" @@ -317,7 +318,9 @@ std::optional GridSimRouteIO::take_encounter(Direction direction, si // nothing end the walk. WalkResult GridSimRouteIO::walk_taps(Direction direction, size_t tiles, const std::string& label){ WalkResult result{.stop = WalkStop::LIMIT, .walked = 0ms, .wild_battles = 0, .moved_chunks = 0}; + result.events.record({}, result.started); size_t still = 0; + size_t moved_at_battle = 0; for (size_t tap = 0; tap < tiles && result.stop == WalkStop::LIMIT; tap++){ const auto encounter = take_encounter(direction, tiles, tap + 1, label); const SimMove move = encounter && encounter->phase == SimEncounterPhase::BEFORE_MOVEMENT @@ -332,6 +335,11 @@ WalkResult GridSimRouteIO::walk_taps(Direction direction, size_t tiles, const st result.origin = WalkOrigin::MAY_PRECEDE_LEG; } result.moved_chunks++; + // The console's watchers time the battle from the tap that set + // it off: this one, or for a battle before this tap moved, the + // one before (0: a step before the walk). + record_tap_battle(result, encounter->phase == SimEncounterPhase::BEFORE_MOVEMENT ? tap : tap + 1); + moved_at_battle = result.moved_chunks; still = 0; m_notes.push_back("[Sim] cleared wild encounter during " + label); continue; @@ -344,6 +352,9 @@ WalkResult GridSimRouteIO::walk_taps(Direction direction, size_t tiles, const st result.stop = WalkStop::BLOCKED; } } + if (result.wild_battles > 0){ + result.moved_after_battle = result.moved_chunks - moved_at_battle; + } m_notes.push_back(std::format("[Sim] {}: {} taps {}, {} moved, {} at {}.", label, tiles, direction_name(direction), result.moved_chunks, walk_stop_name(result.stop), to_string(m_sim.player().pos))); return result; From 78e859f2db3c4aed4aa258dbd48743557bc5e74d Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 03:25:18 -0800 Subject: [PATCH 082/166] BDSP: sim test for a wild battle on an open leg's taps, placed by its screen events On below_roark's open leg east 14, a battle on tap 3, on tap 7 before it moved, and on the last tap: the leg's screen events must place the player within a tile or so of where the taps left them, and the step must still end below Roark. Red: the story's taps keep every tile of the leg after a battle, with no placement. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...kemonBDSP_AutoStory_RecoveryWalk_Tests.cpp | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index 64f2ec71dc..dff5e7213b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" @@ -184,6 +185,83 @@ class Test_RecoveryWalk : public UnitTest{ RecoveryCase m_case; }; +// A wild battle on below_roark's open leg east 14, on the input's tap: the +// leg's screen events must place the player a tile or so from where the +// taps left them, not anywhere along the 14 tiles. The taps go on after +// the battle, as the console's do: the player ends at the leg's end, a +// tile short when the battle came before its tap moved. Red until the +// story's taps read their events: the leg kept all 15 of its tiles. +struct PlacedBattleInput{ + std::string name; + size_t tap; + SimEncounterPhase phase; +}; +struct PlacedBattleExpectation{ + size_t tiles_in; // how far along east 14 the taps left the player +}; +struct PlacedBattleCase{ + PlacedBattleInput input; + PlacedBattleExpectation expectation; +}; + +// "4 to 6 tiles in." in a placement line, if any. +std::optional> placed_span(const std::vector& notes){ + for (const std::string& note : notes){ + const size_t line = note.find("battle on the leg:"); + const size_t in = note.find(" tiles in."); + if (line == std::string::npos || in == std::string::npos){ + continue; + } + const size_t to = note.rfind(" to ", in); + const size_t from = note.rfind(' ', to - 1); + return std::pair{std::stoul(note.substr(from + 1, to - from - 1)), std::stoul(note.substr(to + 4, in - to - 4))}; + } + return std::nullopt; +} + +class Test_PlacedLegBattle : public UnitTest{ +public: + explicit Test_PlacedLegBattle(PlacedBattleCase data) + : UnitTest("PokemonBDSP::AutoStory - Recovery walk: a battle on an open leg's taps, placed by its screen events: " + data.input.name) + , m_case(std::move(data)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const StoryWorld* world = story_plan_world("OreburghMine", "OreburghMine"); + GridSim sim({.world = world}, world->to_world("OreburghMine", {15, 9}), Direction::SOUTH, true); + std::vector notes; + InterruptingRouteIO route(sim, notes, {{.label = "below_roark", .direction = Direction::EAST, + .requested_tiles = 14, .tap = m_case.input.tap, .phase = m_case.input.phase}}, 0, RecoveryBattle::NONE); + RecoveryStepIO io(route); + StoryWalkSteps walks(io); + walks.begin_attempt("01.03"); + Pokemon::RunState state{.pose = Pokemon::tile_pose("OreburghMine", {{15, 9}}, Direction::SOUTH), .flags = {}}; + std::string failure; + try{ + failure = walks.legs(state, mine_step()).failure; + }catch (const GridSimFailure& error){ + failure = error.message; + } + for (const std::string& note : notes){ + logger.log(note); + } + const auto end = story_to_local(*world, "OreburghMine", nearest_tile(sim.player().pos)); + if (!failure.empty() || !end || *end != TilePos{18, 29}){ + return "Expected below Roark (18, 29), got " + to_string(sim.player().pos) + ": " + failure; + } + const auto span = placed_span(notes); + const size_t tiles_in = m_case.expectation.tiles_in; + if (!span){ + return "The battle was not placed: the leg kept every one of its tiles."; + } + if (span->first > tiles_in || tiles_in > span->second || span->second - span->first > 2){ + return std::format("Placed {} to {} tiles in; the taps left the player {} in.", span->first, span->second, tiles_in); + } + return true; + } +private: + PlacedBattleCase m_case; +}; + // The route walker's open legs as lab-B 2026-11-08 11:55 saw one: a leg of // more than a tile that ends on open ground, not at a wall, goes a tile // past where it was planned to stop (there, south 5 went 6). The walker is @@ -824,6 +902,14 @@ void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ for (const RecoveryCase& scenario : CASES){ database.add(scenario); } + const PlacedBattleCase PLACED_CASES[] = { + {.input = {.name = "tap 3", .tap = 3, .phase = SimEncounterPhase::AFTER_MOVEMENT}, .expectation = {.tiles_in = 14}}, + {.input = {.name = "tap 7, before it moved", .tap = 7, .phase = SimEncounterPhase::BEFORE_MOVEMENT}, .expectation = {.tiles_in = 13}}, + {.input = {.name = "the last tap", .tap = 14, .phase = SimEncounterPhase::AFTER_MOVEMENT}, .expectation = {.tiles_in = 14}}, + }; + for (const PlacedBattleCase& scenario : PLACED_CASES){ + database.add(scenario); + } for (const CornerCase& scenario : CORNER_CASES){ database.add(scenario); } From 1c8b6305ed54534995a3a40d7b713149167bc48a Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 03:26:48 -0800 Subject: [PATCH 083/166] BDSP: a story leg's battle is placed by its screen events tap_legs() now reads the interrupted leg's timed events with place_leg_battle() and logs the verdict; a wild battle it places bounds the recovery's start to a tile or so from where the taps left the player (tiles_moved()) instead of every tile of the leg. Anything it cannot place (two battles, an UNSETTLED fade, no events) keeps the whole leg. Green: the open-leg battle sim test, on taps 3, 7 and 14 of east 14. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 14 +++++++++++--- .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 5 ++++- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index f79162b485..bfc1f6a9a5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -282,7 +282,8 @@ std::vector counted_ends(const std::vector& starts, const Poke } // namespace Pose StoryWalkSteps::recover_tapped_leg(const Pose& from, const std::vector& starts, - const std::vector& goals, Direction facing, const Pokemon::StoryLeg& leg, const StoryStep& step){ + const std::vector& goals, Direction facing, const Pokemon::StoryLeg& leg, const StoryStep& step, + const std::optional& moved){ const StoryWorld* world = story_plan_world(from.map, from.map); if (world == nullptr){ fail(m_io.route(), "interrupted leg has no recovery world: " + from.map); @@ -292,7 +293,12 @@ Pose StoryWalkSteps::recover_tapped_leg(const Pose& from, const std::vector possible; - for (const TilePos& at : interrupted_leg_positions(*world, global, leg.direction, (size_t)leg.tiles)){ + // Placed by the leg's screen events: a tile or so from where the taps + // left us. Else anywhere along the leg. + const std::vector along = moved + ? tiles_moved(*world, global, leg.direction, *moved) + : interrupted_leg_positions(*world, global, leg.direction, (size_t)leg.tiles); + for (const TilePos& at : along){ const auto local = story_to_local(*world, from.map, at); if (!local){ fail(m_io.route(), "interrupted leg crossed an unconfirmed map transition"); @@ -332,11 +338,13 @@ Outcome StoryWalkSteps::tap_legs(const Pose& from, const StoryStep& step){ if (walk.stop != WalkStop::LIMIT && walk.stop != WalkStop::BLOCKED){ return Pokemon::outcome_failed("interrupted_leg_unconfirmed", step.name); } + const LegBattlePlace place = place_leg_battle(walk, tiles); + m_io.route().note(std::format("[{}] {}", m_row, leg_battle_line(step.name, walk, place)), RouteNote::LOG); std::vector ends = next; for (auto rest = std::next(leg); rest != step.legs.end(); ++rest){ ends = counted_ends(ends, *rest, policy); } - return Pokemon::outcome_ok(recover_tapped_leg(from, at, ends, step.legs.back().direction, *leg, step)); + return Pokemon::outcome_ok(recover_tapped_leg(from, at, ends, step.legs.back().direction, *leg, step, place.moved)); } if (walk.moved_chunks + (one_short_ok ? 1 : 0) < tiles){ return Pokemon::outcome_failed("short_leg", std::format("{} {} moved {}", direction_name(leg->direction), tiles, walk.moved_chunks)); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index c284f97065..aa3990e645 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -13,10 +13,12 @@ #include #include +#include #include #include #include "Pokemon/AutoStory/Pokemon_StorySteps.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegBattle.h" #include "PokemonBDSP_AutoStory_StoryStepIO.h" namespace PokemonAutomation{ @@ -70,7 +72,8 @@ class StoryWalkSteps{ // `goals` from wherever the leg could have left us, then faces `facing`. Pokemon::Pose recover_tapped_leg(const Pokemon::Pose& from, const std::vector& starts, const std::vector& goals, - Pokemon::Direction facing, const Pokemon::StoryLeg& leg, const Pokemon::StoryStep& step); + Pokemon::Direction facing, const Pokemon::StoryLeg& leg, const Pokemon::StoryStep& step, + const std::optional& moved); Pokemon::Outcome tap_legs(const Pokemon::Pose& from, const Pokemon::StoryStep& step); Pokemon::Outcome counted_wall(const Pokemon::Pose& from, const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_dialogue(const Pokemon::StoryStep& step); From b77c91787c7f2a862bc4165fd5e35f8170a1ee2b Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 04:02:25 -0800 Subject: [PATCH 084/166] BDSP AutoStory: clear interrupts between story steps Binds the shared between-step interrupts (Pokemon_StoryInterrupts.h) for BDSP: the console looks at the screen for 300 ms before each step and runs from a wild battle, fights a trainer who saw us, presses through a dialog, or presses through a warp's scene and loses the pose. The steps that press through text start on a dialog and are not interrupted by one. The simulation binds the same table to the dialogs it pops up (SimWorldKnobs::dialog_before); a dialog left up stops a walk or a talk as on the console. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryExecutor.cpp | 37 ++++++++- .../PokemonBDSP_AutoStory_StoryExecutor.h | 8 ++ .../PokemonBDSP_AutoStory_StoryInterrupts.cpp | 75 ++++++++++++++++++ .../PokemonBDSP_AutoStory_StoryInterrupts.h | 76 +++++++++++++++++++ .../PokemonBDSP_AutoStory_StorySim.cpp | 44 +++++++++++ .../PokemonBDSP_AutoStory_StorySim.h | 26 ++++++- .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 21 +++++ SerialPrograms/cmake/SourceFiles.cmake | 2 + 8 files changed, 287 insertions(+), 2 deletions(-) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp index 1c30b3c111..756a377fbc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp @@ -114,6 +114,14 @@ void ConsoleStepGuard::on_failure(const StoryStep&, const OperationFailedExcepti save_failure_screenshot(m_stream, attempt); } +void ConsoleStepGuard::on_interrupt(const StoryStep& step, const Pokemon::InterruptCheck& check){ + const bool cleared = check.outcome.succeeded(); + m_stream.log(std::format( + "[{}] {}: before it, {}: {}", m_checkpoint, step.name, + Pokemon::interrupt_kind_name(check.verdict.kind), cleared ? "cleared" : Pokemon::to_string(check.outcome) + ), cleared ? COLOR_ORANGE : COLOR_RED); +} + // The table and the guard are members, built after the base: it only // keeps references to them until a step runs. @@ -124,7 +132,11 @@ StoryExecutor::StoryExecutor(StoryEnv& env) , m_walks(m_io) , m_guard(env.env.console, m_checkpoint) , m_table(story_action_table(m_walks, console_actions())) -{} + , m_look(env.env.console, env.context) + , m_interrupts(story_interrupts([this](bool fresh){ return m_look.look(fresh); }, console_interrupt_actions())) +{ + set_interrupts(&m_interrupts); +} StoryBoundActions StoryExecutor::console_actions(){ const auto method = [this](Outcome (StoryExecutor::*action)(RunState&, const StoryStep&)){ @@ -148,6 +160,29 @@ StoryBoundActions StoryExecutor::console_actions(){ }; } +// A wild battle is run from, a trainer who saw us fought, a dialog or a +// warp's scene pressed through to the quiet overworld. +StoryInterruptActions StoryExecutor::console_interrupt_actions(){ + const auto settle = [this](const char* label){ + return [this, label](RunState&, const Pokemon::InterruptVerdict&){ + m_io.settle(BUTTON_B, label, false, ""); + return Pokemon::outcome_ok(); + }; + }; + return StoryInterruptActions{ + .wild = [this](RunState&, const Pokemon::InterruptVerdict&){ + run_from_wild_battle(stream(), context()); + return Pokemon::outcome_ok(); + }, + .trainer = [this](RunState&, const Pokemon::InterruptVerdict&){ + m_io.fight(""); + return Pokemon::outcome_ok(); + }, + .dialog = settle("a dialog between steps"), + .warp = settle("a warp between steps"), + }; +} + void StoryExecutor::begin_attempt(const Pokemon::StoryCheckpoint& data){ m_checkpoint = data.id; m_walks.begin_attempt(data.id); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h index 0ce3924058..178719d044 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h @@ -17,6 +17,8 @@ * console step into a failed Outcome, with a screenshot and the * "checkpoint_reattempt_loop: attempt N failed" line the lab's run watcher * reads; the segment then reloads the row's save and runs it again. + * Before each step it clears what came up since the step before + * (story_interrupts(), PokemonBDSP_AutoStory_StoryInterrupts.h). * */ @@ -37,6 +39,7 @@ #include "Pokemon/AutoStory/Pokemon_StorySteps.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "PokemonBDSP_AutoStory_StoryActions.h" +#include "PokemonBDSP_AutoStory_StoryInterrupts.h" #include "PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP_AutoStory_StoryWalkSteps.h" @@ -105,6 +108,7 @@ class ConsoleStepGuard : public Pokemon::StepGuard{ virtual void before_step(const Pokemon::StoryStep& step) override; virtual bool stops_on_failure(const Pokemon::StoryStep& step) const override; virtual void on_failure(const Pokemon::StoryStep& step, const OperationFailedException& error) override; + virtual void on_interrupt(const Pokemon::StoryStep& step, const Pokemon::InterruptCheck& check) override; private: VideoStream& m_stream; @@ -163,6 +167,7 @@ class StoryExecutor : public Pokemon::TableExecutor{ private: StoryBoundActions console_actions(); + StoryInterruptActions console_interrupt_actions(); StoryEnv& m_env; ConsoleStoryStepIO m_io; @@ -187,6 +192,9 @@ class StoryExecutor : public Pokemon::TableExecutor{ ConsoleStepGuard m_guard; // The story's actions, its console rows bound to this executor. Pokemon::StoryActionTable m_table; + // What is cleared between steps, looked for on the screen. + ConsoleScreenLook m_look; + Pokemon::StoryInterrupts m_interrupts; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp new file mode 100644 index 0000000000..fc94f12f17 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp @@ -0,0 +1,75 @@ +/* BDSP AutoStory - Story interrupts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonTools/Async/InferenceRoutines.h" +#include "PokemonBDSP_AutoStory_StoryInterrupts.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::InterruptKind; +using Pokemon::InterruptPose; +using Pokemon::StoryStepKind; + + +bool presses_through_text(StoryStepKind kind){ + switch (kind){ + case StoryStepKind::MASH: + case StoryStepKind::ANSWER: + case StoryStepKind::BATTLE: + case StoryStepKind::GAME: + case StoryStepKind::NEW_GAME: + return true; + default: + return false; + } +} + +Pokemon::StoryInterrupts story_interrupts(Pokemon::ScreenLookFunction look, const StoryInterruptActions& actions){ + Pokemon::StoryInterrupts out; + out.look = std::move(look); + out.handlers.add(InterruptKind::WILD_ENCOUNTER, {.handle = actions.wild, .pose = InterruptPose::UNCHANGED}); + out.handlers.add(InterruptKind::TRAINER_SIGHT, {.handle = actions.trainer, .pose = InterruptPose::UNCHANGED}); + out.handlers.add(InterruptKind::DIALOG, {.handle = actions.dialog, .pose = InterruptPose::UNCHANGED}); + out.handlers.add(InterruptKind::WARP, {.handle = actions.warp, .pose = InterruptPose::LOST}); + for (StoryStepKind step : {StoryStepKind::MASH, StoryStepKind::ANSWER, StoryStepKind::BATTLE, StoryStepKind::GAME, StoryStepKind::NEW_GAME}){ + out.handlers.starts_on(step, InterruptKind::DIALOG); + } + out.handlers.starts_on(StoryStepKind::BATTLE, InterruptKind::TRAINER_SIGHT); + out.handlers.starts_on(StoryStepKind::TRAIN, InterruptKind::WILD_ENCOUNTER); + for (StoryStepKind step : {StoryStepKind::GAME, StoryStepKind::NEW_GAME}){ + for (InterruptKind kind : {InterruptKind::WILD_ENCOUNTER, InterruptKind::TRAINER_SIGHT, InterruptKind::WARP}){ + out.handlers.starts_on(step, kind); + } + } + return out; +} + + +ConsoleScreenLook::ConsoleScreenLook(VideoStream& stream, ProControllerContext& context) + : m_stream(stream) + , m_context(context) + , m_observer(BattleCue::WILD_MENU, "") + , m_watcher(m_observer) + , m_start(current_time()) +{} + +Pokemon::ScreenLook ConsoleScreenLook::look(bool fresh){ + if (fresh){ + m_watcher.reset(); + m_start = current_time(); + } + wait_until(m_stream, m_context, BETWEEN_STEPS_LOOK, {m_watcher}); + return {.log = m_watcher.log(), .window = {.start = m_start, .end = current_time()}}; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h new file mode 100644 index 0000000000..542512f855 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h @@ -0,0 +1,76 @@ +/* BDSP AutoStory - Story interrupts + * + * From: https://github.com/PokemonAutomation/ + * + * BDSP's interrupts between story steps (Pokemon_StoryInterrupts.h): a + * wild battle is run from, a trainer who saw us is fought, a dialog is + * pressed through, and a warp is waited out, the pose then lost. The + * console (ConsoleScreenLook and the executor's console actions) and the + * simulation bind the same table. + * + * The steps that press through text (MASH, ANSWER, BATTLE, GAME, + * NEW_GAME) start on a dialog: one showing before them is theirs. A + * BATTLE and a GAME step start on a trainer's lines too, TRAIN on a wild + * battle, and a GAME step (a measured script) and NEW_GAME (the title + * screen) on anything. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryInterrupts_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryInterrupts_H + +#include "Common/Cpp/Time.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" +#include "Pokemon/AutoStory/Pokemon_StoryInterrupts.h" +#include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// What clears each kind of interrupt, as a binding does it. +struct StoryInterruptActions{ + Pokemon::InterruptAction wild = {}; + Pokemon::InterruptAction trainer = {}; + Pokemon::InterruptAction dialog = {}; + Pokemon::InterruptAction warp = {}; +}; + +// BDSP's interrupts: `look` judged with the shared knobs, `actions` for +// each kind, and the steps that start on one. +Pokemon::StoryInterrupts story_interrupts(Pokemon::ScreenLookFunction look, const StoryInterruptActions& actions); + +// Whether a step of `kind` presses through any text showing when it +// starts; a step of another kind is stopped by it (a walk, a talk). +bool presses_through_text(Pokemon::StoryStepKind kind); + + +// How long the console looks at the screen before a step: a few frames, +// for what came up after the step before had settled. +constexpr Milliseconds BETWEEN_STEPS_LOOK = Milliseconds(300); + +// The console's look between steps: BDSP's screen events for +// BETWEEN_STEPS_LOOK, everything showing in it judged. +class ConsoleScreenLook{ +public: + ConsoleScreenLook(VideoStream& stream, ProControllerContext& context); + + Pokemon::ScreenLook look(bool fresh); + +private: + VideoStream& m_stream; + ProControllerContext& m_context; + BdspScreenObserver m_observer; + Pokemon::ScreenEventWatcher m_watcher; + WallClock m_start; +}; + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index 4cf78510f5..37000440d1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -648,6 +648,46 @@ StoryBoundActions SimExecutor::sim_actions(){ }; } +Pokemon::ScreenLook SimExecutor::look(){ + const WallClock start = WallClock() + std::chrono::hours(1); + Pokemon::ScreenLook out; + out.log.record({Pokemon::ScreenEvent::PLAYER_CAN_MOVE}, start); + if (std::exchange(m_dialog_rose, false)){ + out.log.record({Pokemon::ScreenEvent::DIALOG_BOX, Pokemon::ScreenEvent::PLAYER_CAN_MOVE}, start + 33ms); + } + out.window = {.start = start, .end = start + BETWEEN_STEPS_LOOK}; + return out; +} + +// Every kind closes what is up and logs it: the simulation shows only +// the dialogs it pops up. +StoryInterruptActions SimExecutor::sim_interrupt_actions(){ + const auto cleared = [this](const char* what){ + return [this, what](RunState&, const Pokemon::InterruptVerdict&){ + m_logger.log(std::format("[{}] {}: {} cleared before it.", m_row, m_step, what)); + m_dialog_up = false; + m_sim.end_dialogue(); + return Pokemon::outcome_ok(); + }; + }; + return StoryInterruptActions{ + .wild = cleared("a wild battle"), + .trainer = cleared("a trainer's battle"), + .dialog = cleared("a dialog"), + .warp = cleared("a warp"), + }; +} + +Outcome SimExecutor::run_action(RunState& state, const StoryStep& step){ + if (m_dialog_up){ + if (!presses_through_text(step.kind)){ + return Pokemon::outcome_failed("dialog", step.name + ": a dialog that popped up before it is still up"); + } + m_dialog_up = false; + } + return Pokemon::TableExecutor::run_action(state, step); +} + Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ if (!m_start_mismatch.empty()){ return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); @@ -678,6 +718,10 @@ Outcome SimExecutor::run(RunState& state, const StoryStep& step){ Outcome outcome; m_passed_over = false; m_step = step.name; + if (m_knobs.dialog_before && m_knobs.dialog_before(m_row, step.name)){ + m_dialog_up = m_dialog_rose = true; + m_logger.log(std::format("[{}] {}: a dialog pops up before it.", m_row, step.name)); + } try{ outcome = run_step(state, step); }catch (const GridSimFailure& e){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index a5fdb851df..ccc6901b63 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -29,6 +29,7 @@ #include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" @@ -142,6 +143,13 @@ struct SimWorldKnobs{ // The scene a step's talk-over plays, by step name: a scene's or a // door's settle(), or the speeches after a battle step's battle. std::map scenes = {}; + // Whether a dialog pops up right before row `row`'s step `step`: + // someone walks up and talks between two steps. Until it is pressed + // through, it stops a step that walks or talks, as on the console. + std::function dialog_before = nullptr; + // Whether the executor clears what came up between steps + // (story_interrupts()), as the console does; off, as before it did. + bool clear_interrupts = true; }; // The walker's RouteIO on the story simulation, with SimWorldKnobs' slides @@ -361,7 +369,12 @@ class SimExecutor : public Pokemon::TableExecutor{ , m_io(m_sim, m_notes, m_misses, m_knobs, m_step, [this]{ return cross(); }, [this](const Pokemon::Pose& far){ cross_to(far); }) , m_walks(m_io) , m_table(story_action_table(m_walks, sim_actions())) - {} + , m_interrupts(story_interrupts([this](bool){ return look(); }, sim_interrupt_actions())) + { + if (m_knobs.clear_interrupts){ + set_interrupts(&m_interrupts); + } + } const SimMisses& misses() const{ return m_misses; @@ -385,6 +398,9 @@ class SimExecutor : public Pokemon::TableExecutor{ virtual Pokemon::Outcome run(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; protected: + // A dialog that popped up and is still up stops a step that walks or + // talks; a step that presses through text closes it. + virtual Pokemon::Outcome run_action(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; virtual Pokemon::Outcome heal(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; virtual Pokemon::Outcome new_game(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } virtual Pokemon::Outcome options(Pokemon::RunState&, const Pokemon::StoryStep&) override{ return stub(); } @@ -408,6 +424,9 @@ class SimExecutor : public Pokemon::TableExecutor{ // A step the simulation does not play: its dialogue opened and closed. Pokemon::Outcome stub(); StoryBoundActions sim_actions(); + // The screen between steps: the dialog that popped up, if one did. + Pokemon::ScreenLook look(); + StoryInterruptActions sim_interrupt_actions(); const StoryWorld* sim_world(const std::string& map) const; SimWorld setup(const StoryWorld* world) const; void arm(const std::string& after); @@ -430,6 +449,11 @@ class SimExecutor : public Pokemon::TableExecutor{ StoryWalkSteps m_walks; SimStepGuard m_guard; Pokemon::StoryActionTable m_table; + Pokemon::StoryInterrupts m_interrupts; + // A dialog popped up (SimWorldKnobs::dialog_before) and is still up; + // it rose since the last look. + bool m_dialog_up = false; + bool m_dialog_rose = false; // The planner's worlds with sim_people() on them, by world and who. mutable std::map, std::unique_ptr> m_peopled; // The steps of this row that have run. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index a5ff1525d6..c565ad7ef1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -159,6 +159,26 @@ UnitTestResult test_story_sim_misses(Logger& logger){ return unseen.empty() ? UnitTestResult(true) : UnitTestResult(out); } +// Someone talks to the player before every step (SimWorldKnobs:: +// dialog_before): cleared between steps, the whole table still passes; +// left up, as before the executor looked, the first walk fails on it. +UnitTestResult test_dialog_between_steps(Logger& logger){ + const Pokemon::SegmentRange range{.from = "00.00", .to = "01.11"}; + const auto always = [](const std::string&, const std::string&){ + return true; + }; + SimExecutor cleared(logger, {}, {.dialog_before = always}); + if (!run_rows_on(cleared, logger, range).completed){ + return "A dialog before every step, cleared: " + cleared.result().error; + } + SimExecutor left(logger, {}, {.dialog_before = always, .clear_interrupts = false}); + run_rows_on(left, logger, range); + if (left.result().error.find(" dialog: ") == std::string::npos){ + return "Expected a dialog left up to stop a walk, got: " + left.result().error; + } + return true; +} + UnitTestResult test_story_sim_whole_table(Logger& logger){ return run_rows(logger, {.from = "00.00", .to = "01.11"}); } @@ -304,6 +324,7 @@ const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { {.input = {"a warp's fade on the sim's frames, through the door's and the taps' watches", test_sim_fade_frames}, .expectation = {}}, {.input = {"00.00 to 01.11: the whole table, from the new game to Floaroma", test_story_sim_whole_table}, .expectation = {}}, {.input = {"each row from 00.00 to 01.11 in isolation", test_story_sim_each_row}, .expectation = {}}, + {.input = {"a dialog pops up before every step from 00.00 to 01.11", test_dialog_between_steps}, .expectation = {}}, {.input = {"01.02b, Barry's lines, then the Center past his doorstep (lab-B, 2026-11-08)", [](Logger& logger){ return run_rows(logger, {.from = "01.02b", .to = "01.02b"}); }}, .expectation = {}}, diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 322f510493..aebd01e09d 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1739,6 +1739,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp From 48bbe8d4abf4fcd468596555cde1f399a087e993 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 09:48:40 -0800 Subject: [PATCH 085/166] BDSP AutoStory sim: a leg that ends on another map ends at an unknown pose walk_legs() dereferenced story_to_local() for the leg's end tiles; 00.03's into_sandgem runs from Route 201 into Sandgem, so the lookup was empty (libstdc++ assertion on Ubuntu CI, silent UB on macOS libc++). A walk that ends off its start map now ends where nothing is known, like a walk to a wall. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StorySimulation_Tests.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index 27c100db13..4f9284dfab 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -158,7 +158,8 @@ std::string walk_leg_from( } // A LEGS step from `from`, walked tile by tile on its map, a tile short too -// where the step allows it. Walks to walls end where nothing is known. +// where the step allows it. Walks to walls, and walks that end on another +// map (into Sandgem until Dawn's scene starts), end where nothing is known. Walked walk_legs(const Pose& from, const StoryStep& step){ if (step.variant == "to_wall"){ return {std::nullopt, "", ""}; @@ -183,7 +184,11 @@ Walked walk_legs(const Pose& from, const StoryStep& step){ } std::vector local; for (const TilePos& pos : at){ - local.push_back(*story_to_local(*world, from.map, pos)); + const std::optional tile = story_to_local(*world, from.map, pos); + if (!tile){ + return {std::nullopt, "", ""}; + } + local.push_back(*tile); } return {Pokemon::tile_pose(from.map, local, step.legs.back().direction), "", ""}; } From 963e7431afb49d9cd3c870b0f8ded6e38e282c15 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 12:18:01 -0800 Subject: [PATCH 086/166] BDSP AutoStory: the Starly battle's opening is the battle step's Lab-B run 3 failed 00.02 at the starly BATTLE step: the battle's opening was still playing after choose_starter and the check between steps called it interrupt_unsettled. Adds the sim knob battle_opening_before and a console-failure case for it, and has BATTLE steps start on a wild encounter too, so the Starly battle is never fled as an interrupt. The engine side is nav/story-steps (#122). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryInterrupts.cpp | 2 ++ ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 12 +++++++++++ .../PokemonBDSP_AutoStory_StorySim.cpp | 20 +++++++++++++++---- .../PokemonBDSP_AutoStory_StorySim.h | 10 ++++++++++ 4 files changed, 40 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp index fc94f12f17..81d6efa36f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp @@ -41,6 +41,8 @@ Pokemon::StoryInterrupts story_interrupts(Pokemon::ScreenLookFunction look, cons out.handlers.starts_on(step, InterruptKind::DIALOG); } out.handlers.starts_on(StoryStepKind::BATTLE, InterruptKind::TRAINER_SIGHT); + // The story's wild battles (the Starly at the lake) are the step's. + out.handlers.starts_on(StoryStepKind::BATTLE, InterruptKind::WILD_ENCOUNTER); out.handlers.starts_on(StoryStepKind::TRAIN, InterruptKind::WILD_ENCOUNTER); for (StoryStepKind step : {StoryStepKind::GAME, StoryStepKind::NEW_GAME}){ for (InterruptKind kind : {InterruptKind::WILD_ENCOUNTER, InterruptKind::TRAINER_SIGHT, InterruptKind::WARP}){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp index e401c39aaa..c07e671197 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -317,6 +317,17 @@ UnitTestResult rowans_scene_opens_with_no_box(Logger& logger){ return passes(run_case(logger, "00.03", "00.03", {.fade = {}, .banner = {}}, knobs)); } +// 00.02: the Starly battle's opening is still playing when the battle +// step starts, right after choose_starter (lab-B 2026-11-09 run 3, event +// 7): the battle step's, not interrupt_unsettled before it. +UnitTestResult starly_opening_after_the_starter(Logger& logger){ + SimWorldKnobs knobs; + knobs.battle_opening_before = [](const std::string& row, const std::string& step){ + return row == "00.02" && step == "starly"; + }; + return passes(run_case(logger, "00.02", "00.02", {.fade = {}, .banner = {}}, knobs)); +} + struct FailureCaseInput{ std::string name; std::function body; @@ -394,6 +405,7 @@ const FailureCase AUTO_STORY_FAILURE_CASES[] = { {.input = {"01.04 Roark's badge speech: the fanfare's pause, then a scene", roark_badge_speech}, .expectation = {}}, {.input = {"01.07 after the tag battle the grunts run off before anyone speaks", grunts_run_off_before_rowan}, .expectation = {}}, {.input = {"00.03 Rowan's scene opens with no box and fades home", rowans_scene_opens_with_no_box}, .expectation = {}}, + {.input = {"00.02 the Starly battle's opening still plays after the starter (lab-B 2026-11-09)", starly_opening_after_the_starter}, .expectation = {}}, }; void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index 37000440d1..5c81cd0a82 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -655,6 +655,9 @@ Pokemon::ScreenLook SimExecutor::look(){ if (std::exchange(m_dialog_rose, false)){ out.log.record({Pokemon::ScreenEvent::DIALOG_BOX, Pokemon::ScreenEvent::PLAYER_CAN_MOVE}, start + 33ms); } + if (m_battle_opening){ + out.log.record({Pokemon::ScreenEvent::FADE_WHITE}, start + 33ms); + } out.window = {.start = start, .end = start + BETWEEN_STEPS_LOOK}; return out; } @@ -714,19 +717,28 @@ Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ return Pokemon::TableExecutor::run(state, step); } -Outcome SimExecutor::run(RunState& state, const StoryStep& step){ - Outcome outcome; - m_passed_over = false; - m_step = step.name; +void SimExecutor::show_before(const StoryStep& step){ if (m_knobs.dialog_before && m_knobs.dialog_before(m_row, step.name)){ m_dialog_up = m_dialog_rose = true; m_logger.log(std::format("[{}] {}: a dialog pops up before it.", m_row, step.name)); } + m_battle_opening = m_knobs.battle_opening_before && m_knobs.battle_opening_before(m_row, step.name); + if (m_battle_opening){ + m_logger.log(std::format("[{}] {}: a battle's opening is still playing before it.", m_row, step.name)); + } +} + +Outcome SimExecutor::run(RunState& state, const StoryStep& step){ + Outcome outcome; + m_passed_over = false; + m_step = step.name; + show_before(step); try{ outcome = run_step(state, step); }catch (const GridSimFailure& e){ outcome = Pokemon::outcome_failed("sim_failure", e.message); } + m_battle_opening = false; m_astray |= std::exchange(m_misses.slid, false); const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; if (!mismatch.empty()){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index ccc6901b63..f822610d2d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -147,6 +147,10 @@ struct SimWorldKnobs{ // someone walks up and talks between two steps. Until it is pressed // through, it stops a step that walks or talks, as on the console. std::function dialog_before = nullptr; + // Whether a battle's opening is still playing when row `row`'s step + // `step` starts: the encounter's white, no battle yet (00.02's Starly + // battle right after the starter is picked, lab-B 2026-11-09). + std::function battle_opening_before = nullptr; // Whether the executor clears what came up between steps // (story_interrupts()), as the console does; off, as before it did. bool clear_interrupts = true; @@ -426,6 +430,9 @@ class SimExecutor : public Pokemon::TableExecutor{ StoryBoundActions sim_actions(); // The screen between steps: the dialog that popped up, if one did. Pokemon::ScreenLook look(); + // What the knobs put on the screen before `step`: a dialog that pops + // up, a battle's opening still playing. + void show_before(const Pokemon::StoryStep& step); StoryInterruptActions sim_interrupt_actions(); const StoryWorld* sim_world(const std::string& map) const; SimWorld setup(const StoryWorld* world) const; @@ -454,6 +461,9 @@ class SimExecutor : public Pokemon::TableExecutor{ // it rose since the last look. bool m_dialog_up = false; bool m_dialog_rose = false; + // A battle's opening is playing before this step + // (SimWorldKnobs::battle_opening_before). + bool m_battle_opening = false; // The planner's worlds with sim_people() on them, by world and who. mutable std::map, std::unique_ptr> m_peopled; // The steps of this row that have run. From 9f174fa669a5de1662c328e96c208ed27b84f146 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 13:03:30 -0800 Subject: [PATCH 087/166] BDSP AutoStory sim: 00.03 from each tile Rowan's scene ends on lab-B 2026-11-09 12:49: the scene ended a row low, on row 9, and the way to the door missed it. SimWorldKnobs::lands puts the player off a scene's pose_after; the new case runs 00.03 from (5, 8), (6, 8), (5, 9) and (6, 9). It fails from row 9 today, so it starts on KNOWN_FAILING. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 20 +++++++++++++++++++ .../PokemonBDSP_AutoStory_StorySim.cpp | 18 ++++++++++++++++- .../PokemonBDSP_AutoStory_StorySim.h | 11 ++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp index c07e671197..4ab3b410de 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -49,6 +49,8 @@ const std::map KNOWN_FAILING{ {"01.05 through_the_gate is one run west", "planner: goal kinds and ms costs (PLANNER_DESIGN.md)"}, {"any one missed fade or banner from 00.00 to 01.11: every row still passes", "a third signal where a warp gives one (ONE_SIGNAL_STEPS): position (PLANNER_DESIGN.md 2, 4)"}, + {"00.03 out of the house from each tile Rowan's scene ends on, rows 8 and 9 (lab-B 2026-11-09)", + "00.03: the way to the door localized from each tile the scene ends on"}, {"01.08 with Route 204's youngster wandering (12..14, 2)", "planner: one recovery rule, a sidestep round a wanderer (PLANNER_DESIGN.md 4, 7)"}, }; @@ -328,6 +330,23 @@ UnitTestResult starly_opening_after_the_starter(Logger& logger){ return passes(run_case(logger, "00.02", "00.02", {.fade = {}, .banner = {}}, knobs)); } +// 00.03: Rowan's scene ends at home beside Mom, on the rug's row (r24, +// r27, r28) or a row lower (lab-B 2026-11-09 12:49: the walk west to the +// table's corner stopped on (5, 9) against the wall (4, 9), and the taps +// after crossed the door's mat to (7, 10)). The way out goes from each. +UnitTestResult home_from_each_scene_end(Logger& logger){ + std::string failures; + for (const TilePos& tile : {TilePos{5, 8}, TilePos{6, 8}, TilePos{5, 9}, TilePos{6, 9}}){ + SimWorldKnobs knobs; + knobs.lands["rowan_and_dawn"] = Pokemon::tile_pose("PlayerHouse1F", {tile}, Direction::EAST); + const std::string stopped = run_case(logger, "00.03", "00.03", {.fade = {}, .banner = {}}, std::move(knobs)); + if (!stopped.empty()){ + failures += std::format("\nfrom ({}, {}): {}", tile.x, tile.y, stopped); + } + } + return passes(failures); +} + struct FailureCaseInput{ std::string name; std::function body; @@ -406,6 +425,7 @@ const FailureCase AUTO_STORY_FAILURE_CASES[] = { {.input = {"01.07 after the tag battle the grunts run off before anyone speaks", grunts_run_off_before_rowan}, .expectation = {}}, {.input = {"00.03 Rowan's scene opens with no box and fades home", rowans_scene_opens_with_no_box}, .expectation = {}}, {.input = {"00.02 the Starly battle's opening still plays after the starter (lab-B 2026-11-09)", starly_opening_after_the_starter}, .expectation = {}}, + {.input = {"00.03 out of the house from each tile Rowan's scene ends on, rows 8 and 9 (lab-B 2026-11-09)", home_from_each_scene_end}, .expectation = {}}, }; void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index 5c81cd0a82..ce0c89cbe6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -514,7 +514,7 @@ bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ return false; } // The program thinks we are on `pose`; we walk on from where the slide left us. - if (m_astray && m_placed){ + if ((m_astray || m_misplaced) && m_placed){ return true; } const SimPlayer& player = m_sim.player(); @@ -528,6 +528,20 @@ bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ return true; } +void SimExecutor::land(const std::string& step){ + const auto lands = m_knobs.lands.find(step); + if (lands == m_knobs.lands.end()){ + return; + } + m_misplaced = false; + const SimPlayer& player = m_sim.player(); + const Pose& pose = lands->second; + if (sync(pose)){ + m_misplaced = true; + m_logger.log(std::format("[{}] {}: the player lands on {}, off the table's pose.", m_row, step, to_string(player.pos))); + } +} + // Through a door or a cave mouth onto the step's far side, the player's // facing kept: a hold goes on from there. bool SimExecutor::cross(){ @@ -748,7 +762,9 @@ Outcome SimExecutor::run(RunState& state, const StoryStep& step){ // where the table says it does. if (outcome.succeeded() && step.pose_after){ m_astray = false; + m_misplaced = false; sync(*step.pose_after); + land(step.name); } m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); if (std::exchange(m_misses.missed, false) && m_result.missed_step.empty()){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index f822610d2d..6fb9563bb8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -154,6 +154,11 @@ struct SimWorldKnobs{ // Whether the executor clears what came up between steps // (story_interrupts()), as the console does; off, as before it did. bool clear_interrupts = true; + // Where a step the simulation does not play (a scene) really leaves + // the player, by step name, when that is not the table's pose_after: + // the program goes on from the table's pose, the player from here + // (00.03's scene a row low, lab-B 2026-11-09). + std::map lands = {}; }; // The walker's RouteIO on the story simulation, with SimWorldKnobs' slides @@ -438,6 +443,8 @@ class SimExecutor : public Pokemon::TableExecutor{ SimWorld setup(const StoryWorld* world) const; void arm(const std::string& after); bool sync(const Pokemon::Pose& pose, const StoryWorld* on = nullptr); + // Puts the player where SimWorldKnobs::lands says `step` leaves them, if it says. + void land(const std::string& step); bool cross(); bool cross_to(const Pokemon::Pose& far); std::vector wanderers(const StoryWorld& world) const; @@ -481,6 +488,10 @@ class SimExecutor : public Pokemon::TableExecutor{ // Whether a walk slid on (SimSlide), so the player is not where the // program thinks, until a step's pose_after puts them right. bool m_astray = false; + // Whether a step left the player off its pose_after (SimWorldKnobs::lands), + // so the walks go on from there, checked, until a step's pose_after + // puts them right. + bool m_misplaced = false; SimRun m_result; }; From ddb6fd0c9222cfb25c45c6973d17cea3ab5d57db Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 13:18:56 -0800 Subject: [PATCH 088/166] BDSP AutoStory: 00.03 measures which row Rowan's scene left us on The scene ends beside Mom on the rug's row (r24, r27, r28) or a row lower (lab-B 2026-11-09). West to the wall then stops on (4, 8) or (5, 9); a new LEGS variant "measured" taps south and keeps the start tiles whose taps the map lets move as many as moved: the wall (4, 9) stops it under (4, 8), from (5, 9) it steps to (5, 10). A route goes from that tile to (5, 9), then a tap east to above the door. No leg walks east into Mom at (7, 8). The static walk model and the route-plan golden plan a route after a measured step from each tile on its own, as the program does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Data/route_plans.golden.txt | 20 ++++-- .../PokemonBDSP_AutoStory_StoryExecutor.h | 2 + .../PokemonBDSP_AutoStory_StoryTable.cpp | 25 ++++--- ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 25 ++++++- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 67 +++++++++++++++++++ .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 13 ++++ ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 2 - ...onBDSP_AutoStory_StorySimulation_Tests.cpp | 44 +++++++++++- 8 files changed, 176 insertions(+), 22 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt index 41d46a087a..b31c00f6d0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt @@ -71,12 +71,20 @@ anchor); 0 from one start tile. 2. east 19 (open) -> Route 201 (4, 14) totals: 2 legs, 1 turns, 1 open, 1 localization -== 00.03 by_the_counter (costs: route) - from: PlayerHouse1F (5, 8) (6, 8) facing east (set) - target: PlayerHouse1F (4, 8) facing west (tile) - start candidates: PlayerHouse1F (5, 8), PlayerHouse1F (6, 8) - 1. west 2 (to wall) -> PlayerHouse1F (4, 8) - totals: 1 legs, 0 turns, 0 open, 1 localization +== 00.03 beside_the_door_column (costs: route) + from: PlayerHouse1F (4, 8) facing south (tile) + target: PlayerHouse1F (5, 9) facing east (tile) + start candidates: PlayerHouse1F (4, 8) + 1. east 1 (open) -> PlayerHouse1F (5, 8) + 2. south 1 (open) -> PlayerHouse1F (5, 9) + totals: 2 legs, 1 turns, 2 open, 0 localization + +== 00.03 beside_the_door_column (costs: route) + from: PlayerHouse1F (5, 10) facing south (tile) + target: PlayerHouse1F (5, 9) facing east (tile) + start candidates: PlayerHouse1F (5, 10) + 1. north 1 (open) -> PlayerHouse1F (5, 9) + totals: 1 legs, 0 turns, 1 open, 0 localization == 00.03 short_of_dawn (costs: route) from: TwinleafTown (20, 22) facing south (tile) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h index 178719d044..0a8b93f9c9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h @@ -180,6 +180,8 @@ class StoryExecutor : public Pokemon::TableExecutor{ // unless the step gives one. Variant "counted_wall": its one leg walks // to the wall, waiting out anyone walking about in the way, and fails // when the tiles walked are far off the map's from the step's start. + // Variant "measured": each leg in taps; the tiles of the step's start + // whose taps the map lets move as many as moved are where we are. // - STEP: one D-pad step `direction`, turning first: onto a scene's // trigger or into a door. Variant "to_banner": one tap into a cave // mouth, then wait for pose_after's map's location banner. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 2bcc88cb0c..9251434dbf 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -307,6 +307,14 @@ std::vector intro(){ }; } +// 00.03, home: west to the wall first, as from the rug's row (r27, r28): +// there it stops on (4, 8) against the table's corner (3, 8); a row lower +// on (5, 9) against the wall (4, 9). Not east: Mom at (7, 8) talks (r29). +StoryStep by_the_counter(){ + return anchored(to_walls("by_the_counter", {{.direction = WEST, .tiles = 2}}, "west to the table's corner, or the wall a row lower"), + Pokemon::tile_pose(HOME, {TilePos{4, 8}, TilePos{5, 9}}, WEST)); +} + std::vector lake_and_pokedex(){ return { row("00.02", "Lake Verity: the starter and the Starly battle", at(LAKEFRONT, "below_lake_entrance", NORTH), { @@ -327,17 +335,18 @@ std::vector lake_and_pokedex(){ step_into("rowans_stop", EAST, "the trigger (5, 14..16)"), // BDSP, unlike Diamond: after Rowan leaves, Dawn's and Barry's lines, then // the game fades to the house, where Mom gives the Running Shoes. The - // scene ends beside her on the rug, facing her: (6, 8) in r24 and r27, - // (5, 8) in r28. - scene("rowan_and_dawn", Pokemon::tile_pose(HOME, {TilePos{5, 8}, TilePos{6, 8}}, EAST), + // scene ends near her, by the rug: (6, 8) in r24 and r27, (5, 8) in + // r28, a row lower on lab-B 2026-11-09. + scene("rowan_and_dawn", Pokemon::tile_pose(HOME, {TilePos{5, 8}, TilePos{6, 8}, TilePos{5, 9}, TilePos{6, 9}}, EAST), "Rowan and Dawn come back; Barry, then home for the Running Shoes"), // Mom's warning was spent in 00.01, so the door's tile (6, 10) is a plain // door now: stepping onto it goes out (r27). - // Line up on the table's corner west first: a plan from either tile - // ran east into Mom at (7, 8), who talks (r29). - route("by_the_counter", at(HOME, 4, 8, WEST), "west against the table's corner (3, 8)"), - anchored(legs("above_the_door_again", {{.direction = EAST, .tiles = 1}, {.direction = SOUTH, .tiles = 1}, {.direction = EAST, .tiles = 1}}, - "east, south past the wall (4, 9), and east to above the door: not south toward it"), at(HOME, 6, 9, EAST)), + by_the_counter(), + // A tap south tells (4, 8) and (5, 9) apart; from there to beside the + // door's column, not down it: an open leg south could slide onto the door. + legs("which_row", {{.direction = SOUTH, .tiles = 1}}, "a tap south: the wall (4, 9) stops it, or not", "measured"), + route("beside_the_door_column", at(HOME, 5, 9, EAST), "from the tile the tap told us"), + legs("above_the_door_again", {{.direction = EAST, .tiles = 1}}, "east a tile to above the door: not south toward it"), step_into("out_of_the_house_again", SOUTH, "onto the door's tile (6, 10), and out", at(TWINLEAF, "house_doorstep", SOUTH)), // Through the grass now, with a starter: wild battles are run from. route("short_of_dawn", at(ROUTE_201, 63, 5, EAST), "Twinleaf, then east along Route 201 to its east edge"), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index 289837b23c..3a5ffbbb7e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -29,6 +29,7 @@ #include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_StoryTable_Tests.h" +#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -45,7 +46,7 @@ using Pokemon::TilePos; const std::map>& built_in_variants(){ static const std::map> variants{ {StoryStepKind::ROUTE, {"", "town", "robust", "line"}}, - {StoryStepKind::LEGS, {"", "one_short_ok", "to_wall", "counted_wall", "to_dialogue", "to_map"}}, + {StoryStepKind::LEGS, {"", "one_short_ok", "to_wall", "counted_wall", "measured", "to_dialogue", "to_map"}}, {StoryStepKind::STEP, {"", "to_banner", "tap"}}, {StoryStepKind::MASH, {"", "a"}}, {StoryStepKind::BATTLE, {"", "doubles", "starter"}}, @@ -275,15 +276,33 @@ std::optional pose_after_step(const std::optional& return step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP ? std::nullopt : at; } +// A ROUTE step after a "measured" LEGS step plans from the one tile the +// taps measured: one TableRoute for each tile of `at`. +void add_measured_routes(std::vector& routes, const std::string& row, const Pokemon::StoryStep& step, const Pokemon::Pose& at){ + for (const TilePos& pos : Pokemon::tiles_of(at)){ + const Pokemon::Pose one = Pokemon::tile_pose(at.map, {pos}, Pokemon::facing_of(at)); + routes.push_back({row, &step, one, story_plan_world(at.map, step.target->map)}); + } +} + std::vector table_routes(){ std::vector routes; for (const StoryCheckpoint& row : story_checkpoints()){ std::optional at = row.start; + bool measured = false; for (const Pokemon::StoryStep& step : row.steps){ - if (step.kind == StoryStepKind::ROUTE){ - const bool known = at && !Pokemon::tiles_of(*at).empty(); + const bool known = at && !Pokemon::tiles_of(*at).empty(); + if (step.kind == StoryStepKind::ROUTE && known && std::exchange(measured, false)){ + add_measured_routes(routes, row.id, step, *at); + }else if (step.kind == StoryStepKind::ROUTE){ routes.push_back({row.id, &step, at, known ? story_plan_world(at->map, step.target->map) : nullptr}); } + measured = false; + if (step.kind == StoryStepKind::LEGS && step.variant == "measured" && known && !step.pose_after){ + at = measured_ends(*at, step); + measured = at.has_value(); + continue; + } at = pose_after_step(at, step); } } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index bfc1f6a9a5..cf97fa7819 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -64,6 +64,34 @@ CenterEntry run_into_center(StoryStepIO& io, bool run, const std::function measured_ends(const Pose& from, const StoryStep& step){ + const StoryWorld* world = story_plan_world(from.map, from.map); + if (world == nullptr || step.legs.empty()){ + return std::nullopt; + } + std::vector at = Pokemon::tiles_of(from); + for (const Pokemon::StoryLeg& leg : step.legs){ + std::vector next; + for (const TilePos& pos : at){ + const TilePos end = tapped_end(*world, from.map, pos, leg).end; + if (std::find(next.begin(), next.end(), end) == next.end()){ + next.push_back(end); + } + } + at = std::move(next); + } + return Pokemon::tile_pose(from.map, at, step.legs.back().direction); +} + void StoryWalkSteps::begin_attempt(const std::string& row){ m_row = row; // A row starts from its save: after the shoes' row, the save has them. @@ -354,6 +382,42 @@ Outcome StoryWalkSteps::tap_legs(const Pose& from, const StoryStep& step){ return Pokemon::outcome_ok(Pokemon::tile_pose(from.map, at, step.legs.back().direction)); } +// A LEGS step "measured": each leg tapped, its taps that moved counted +// against the map's from each tile the player may stand on; the tiles +// whose count matches are where we are. A wall a tap bumps tells us +// where we are, where a fixed leg from a guessed tile walks on astray +// (00.03, lab-B 2026-11-09: a row low, the taps crossed the door's mat). +Outcome StoryWalkSteps::measured_legs(const Pose& from, const StoryStep& step){ + const StoryWorld* world = story_plan_world(from.map, from.map); + std::vector at = Pokemon::tiles_of(from); + if (world == nullptr || at.empty()){ + return Pokemon::outcome_failed("measured", "no map or tiles: " + Pokemon::to_string(from)); + } + for (const Pokemon::StoryLeg& leg : step.legs){ + turn(leg.direction); + const size_t tiles = (size_t)leg.tiles; + const WalkResult walk = m_io.route().walk_taps(leg.direction, tiles, step.name); + if (walk.wild_battles > 0){ + return Pokemon::outcome_failed("interrupted_leg_unconfirmed", step.name); + } + std::vector next; + for (const TilePos& pos : at){ + const TappedEnd tapped = tapped_end(*world, from.map, pos, leg); + if (tapped.moved == walk.moved_chunks){ + next.push_back(tapped.end); + } + } + log(std::format("[{}] {}: taps {} moved {} of {}: {} of {} tiles fit.", m_row, step.name, + direction_name(leg.direction), walk.moved_chunks, tiles, next.size(), at.size())); + if (next.empty()){ + return Pokemon::outcome_failed("measured", std::format("{} moved {}: no tile of {} fits", + direction_name(leg.direction), walk.moved_chunks, Pokemon::to_string(from))); + } + at = std::move(next); + } + return Pokemon::outcome_ok(Pokemon::tile_pose(from.map, at, step.legs.back().direction)); +} + // A LEGS step "counted_wall": its one leg held to the wall, its tiles // counted against the map's from each tile the table may have us on // (walk_counted_wall_leg()). The leg's tiles are the table's reading of @@ -387,6 +451,9 @@ Outcome StoryWalkSteps::legs(RunState& state, const StoryStep& step){ if (step.variant == "counted_wall"){ return counted_wall(state.pose, step); } + if (step.variant == "measured"){ + return measured_legs(state.pose, step); + } if (step.variant == "to_wall"){ for (const Pokemon::StoryLeg& leg : step.legs){ m_io.walk_until_stopped(leg.direction, (size_t)leg.tiles, label_of(step)); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index aa3990e645..dc6c5e20dc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -39,6 +39,18 @@ enum class CenterEntry{ // not, `line_up` lines up with the lit doorway and walks in (or fails). CenterEntry run_into_center(StoryStepIO& io, bool run, const std::function& inside, const std::function& line_up); +// Where a leg's taps end, and how many of them moved. +struct TappedEnd{ + Pokemon::TilePos end; + size_t moved = 0; +}; +// Where `leg`'s taps from `pos` (a tile of `map`) end on `world`: each tap +// moves a tile until a wall stops them. +TappedEnd tapped_end(const StoryWorld& world, const std::string& map, const Pokemon::TilePos& pos, const Pokemon::StoryLeg& leg); +// The tiles a "measured" LEGS step may end on from `from`, one a tile of +// it; the step measures which. Nothing if `from`'s map has no world. +std::optional measured_ends(const Pokemon::Pose& from, const Pokemon::StoryStep& step); + // Executes walking and movement-related story steps via StoryStepIO. class StoryWalkSteps{ @@ -76,6 +88,7 @@ class StoryWalkSteps{ const std::optional& moved); Pokemon::Outcome tap_legs(const Pokemon::Pose& from, const Pokemon::StoryStep& step); Pokemon::Outcome counted_wall(const Pokemon::Pose& from, const Pokemon::StoryStep& step); + Pokemon::Outcome measured_legs(const Pokemon::Pose& from, const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_dialogue(const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_map(const Pokemon::StoryStep& step); Pokemon::Outcome tap_to_banner(const Pokemon::Pose& from, const Pokemon::StoryStep& step); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp index 4ab3b410de..39b9146e98 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -49,8 +49,6 @@ const std::map KNOWN_FAILING{ {"01.05 through_the_gate is one run west", "planner: goal kinds and ms costs (PLANNER_DESIGN.md)"}, {"any one missed fade or banner from 00.00 to 01.11: every row still passes", "a third signal where a warp gives one (ONE_SIGNAL_STEPS): position (PLANNER_DESIGN.md 2, 4)"}, - {"00.03 out of the house from each tile Rowan's scene ends on, rows 8 and 9 (lab-B 2026-11-09)", - "00.03: the way to the door localized from each tile the scene ends on"}, {"01.08 with Route 204's youngster wandering (12..14, 2)", "planner: one recovery rule, a sidestep round a wanderer (PLANNER_DESIGN.md 4, 7)"}, }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index d6daef7b74..d16e009e0d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" @@ -29,6 +30,7 @@ #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" #include "PokemonBDSP_AutoStory_StorySimulation_Tests.h" namespace PokemonAutomation{ @@ -65,11 +67,13 @@ bool contains(const std::vector& tiles, const TilePos& pos){ return std::find(tiles.begin(), tiles.end(), pos) != tiles.end(); } -// Where a step ends, or why it does not plan. +// Where a step ends, or why it does not plan. A "measured" step ends on +// one of `at`'s tiles and the program knows which (`measured`). struct Walked{ std::optional at; std::string error; std::string plan; + bool measured = false; }; // The tiles a plan walks. @@ -145,6 +149,27 @@ Walked plan_route(const Pose& from, const StoryStep& step){ return walked; } +// A ROUTE step after a "measured" one: the program plans from the one +// tile it measured, so each tile of `from` must plan on its own. +Walked plan_route_from_each(const Pose& from, const StoryStep& step){ + Walked walked; + std::vector ends; + for (const TilePos& pos : Pokemon::tiles_of(from)){ + const Walked one = plan_route(Pokemon::tile_pose(from.map, {pos}, Pokemon::facing_of(from)), step); + if (!one.error.empty() || !one.at){ + return one; + } + walked.plan += (walked.plan.empty() ? "" : "; ") + one.plan; + for (const TilePos& end : Pokemon::tiles_of(*one.at)){ + if (!contains(ends, end)){ + ends.push_back(end); + } + } + walked.at = Pokemon::tile_pose(one.at->map, ends, Pokemon::facing_of(*one.at)); + } + return walked; +} + // `leg` of `step` from `pos`: adds where it ends to `next` (and a tile // short where the step allows it). Returns why it is blocked, or "". std::string walk_leg_from( @@ -176,6 +201,10 @@ Walked walk_legs(const Pose& from, const StoryStep& step){ if (step.variant == "to_map"){ return {step.pose_after, "", ""}; } + if (step.variant == "measured"){ + const std::optional ends = measured_ends(from, step); + return {ends, ends ? "" : step.name + ": no world holds " + from.map + ".", "", true}; + } const StoryWorld* world = story_plan_world(from.map, from.map); if (world == nullptr){ return {std::nullopt, step.name + ": no world holds " + from.map + ".", ""}; @@ -251,7 +280,12 @@ class FakeGame : public Pokemon::StoryStepExecutor{ return moved(plan_route(state.pose, step), "no_plan"); } virtual Outcome legs(RunState& state, const StoryStep& step) override{ - return moved(walk_legs(state.pose, step), "blocked"); + Walked walked = walk_legs(state.pose, step); + // The fake player stands on the first tile a measured step may end on. + if (walked.measured && walked.at && !Pokemon::tiles_of(*walked.at).empty()){ + walked.at = Pokemon::tile_pose(walked.at->map, {Pokemon::tiles_of(*walked.at).front()}, Pokemon::facing_of(*walked.at)); + } + return moved(walked, "blocked"); } virtual Outcome step(RunState& state, const StoryStep& step) override{ return moved(step_on(state.pose, step), "blocked"); @@ -437,6 +471,7 @@ UnitTestResult test_gives_up_after_attempts(Logger&){ // the player, by the same planning and walking the fake run does. UnitTestResult test_poses_chain(Logger&){ std::optional at; + bool measured = false; std::string last; for (const StoryCheckpoint& row : story_checkpoints()){ if (row.start){ @@ -456,12 +491,15 @@ UnitTestResult test_poses_chain(Logger&){ if (!at && step.variant != "to_wall" && step.variant != "jubilife_stairs"){ return row.id + " " + step.name + ": walks from an unknown pose."; } - const Walked walked = !at ? Walked{} : step.kind == StoryStepKind::ROUTE ? plan_route(*at, step) + const bool known = std::exchange(measured, false); + const Walked walked = !at ? Walked{} : step.kind == StoryStepKind::ROUTE + ? (known ? plan_route_from_each(*at, step) : plan_route(*at, step)) : step.kind == StoryStepKind::LEGS ? walk_legs(*at, step) : step_on(*at, step); if (!walked.error.empty()){ return row.id + " " + walked.error; } at = walked.at; + measured = walked.measured; }else if (step.kind == StoryStepKind::GAME || step.kind == StoryStepKind::SHOP || step.kind == StoryStepKind::MASH){ // A scene or an event: where it ends is the table's to say. at.reset(); From 2d3729d465c52bd51eb0989d819f8cc4280df236 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 13:38:09 -0800 Subject: [PATCH 089/166] BDSP AutoStory: test that every resource it loads is in Resources The Options templates the settings step loads ship only in the lab's Packages, so a deployment without them fails with a FileException. autostory_resource_paths() lists the files AutoStory loads, and the test fails naming each one missing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_Resources.cpp | 61 +++++++++++++++ .../PokemonBDSP_AutoStory_Resources.h | 35 +++++++++ .../PokemonBDSP_AutoStory_Resources_Tests.cpp | 78 +++++++++++++++++++ .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 2 + SerialPrograms/cmake/SourceFiles.cmake | 3 + 5 files changed, 179 insertions(+) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources_Tests.cpp diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.cpp new file mode 100644 index 0000000000..ff1f7aed18 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.cpp @@ -0,0 +1,61 @@ +/* BDSP AutoStory Resources + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonBDSP_AutoStory_Resources.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +const std::string_view PATHS[] = { + // Actions/PokemonBDSP_AutoStory_Settings.cpp: each row's label and + // target value, as SETTINGS there names them. + "PokemonBDSP/Autostory/Options/textspeed_label.png", + "PokemonBDSP/Autostory/Options/textspeed_value.png", + "PokemonBDSP/Autostory/Options/changewindow_label.png", + "PokemonBDSP/Autostory/Options/changewindow_value.png", + "PokemonBDSP/Autostory/Options/battleeffects_label.png", + "PokemonBDSP/Autostory/Options/battleeffects_value.png", + "PokemonBDSP/Autostory/Options/battlestyle_label.png", + "PokemonBDSP/Autostory/Options/battlestyle_value.png", + "PokemonBDSP/Autostory/Options/sendtoboxes_label.png", + "PokemonBDSP/Autostory/Options/sendtoboxes_value.png", + "PokemonBDSP/Autostory/Options/givenicknames_label.png", + "PokemonBDSP/Autostory/Options/givenicknames_value.png", + "PokemonBDSP/Autostory/Options/gyroscope_label.png", + "PokemonBDSP/Autostory/Options/gyroscope_value.png", + "PokemonBDSP/Autostory/Options/autosave_label.png", + "PokemonBDSP/Autostory/Options/autosave_value.png", + "PokemonBDSP/Autostory/Options/shownicknames_label.png", + "PokemonBDSP/Autostory/Options/shownicknames_value.png", + "PokemonBDSP/Autostory/Options/backgroundmusic_label.png", + "PokemonBDSP/Autostory/Options/backgroundmusic_value.png", + "PokemonBDSP/Autostory/Options/soundeffects_label.png", + "PokemonBDSP/Autostory/Options/soundeffects_value.png", + + // Actions/PokemonBDSP_AutoStory_Events_Lake.cpp + "PokemonBDSP/StarterBriefcase.png", + // Inference/PokemonBDSP_SelectionArrow.cpp and + // PokemonBDSP_NameListDetector.cpp + "PokemonBDSP/SelectionArrow.png", +}; + +} // namespace + + +const std::vector& autostory_resource_paths(){ + static const std::vector LIST(std::begin(PATHS), std::end(PATHS)); + return LIST; +} + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.h new file mode 100644 index 0000000000..ebcd4bf09c --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.h @@ -0,0 +1,35 @@ +/* BDSP 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_PokemonBDSP_AutoStory_Resources_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Resources_H + +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// 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 PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources_Tests.cpp new file mode 100644 index 0000000000..8296c8251e --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources_Tests.cpp @@ -0,0 +1,78 @@ +/* BDSP 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 "PokemonBDSP_AutoStory_Resources.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +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("PokemonBDSP::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 PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index c565ad7ef1..00c31523ee 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -48,6 +48,7 @@ #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" #include "PokemonBDSP_AutoStory_StorySim.h" #include "PokemonBDSP_AutoStory_StorySim_Tests.h" @@ -374,6 +375,7 @@ void add_tests_AutoStory_StorySim(UnitTestDatabase& database){ for (const auto& item : AUTO_STORY_STORY_SIM_CASES){ database.add(item); } + add_tests_AutoStoryResources(database); } } // namespace PokemonBDSP diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index aebd01e09d..b849dd7292 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1592,6 +1592,9 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.cpp From d0ade1fc83717b7782f346392e43663fad1a4d6b Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 13:49:41 -0800 Subject: [PATCH 090/166] BDSP AutoStory sim: sweep scene end poses and battle openings over every row Each row from 00.00 to 01.11 runs with a step whose end pose the game sets (a talk, scene, battle or event that moved the player) ending on each walkable tile next to the table's pose (SimWorldKnobs::lands, 00.03's console failure), and with a battle's opening still playing at each battle step and each step after a walk on a route or in a cave (battle_opening_before, 00.02's Starly). A row that fails clean is not swept. Rows that fail today are known failing with their likely fix, so the gate stays green while the list stays visible. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 2 + ...PokemonBDSP_AutoStory_FaultSweep_Tests.cpp | 360 ++++++++++++++++++ .../PokemonBDSP_AutoStory_FaultSweep_Tests.h | 27 ++ SerialPrograms/cmake/SourceFiles.cmake | 2 + 4 files changed, 391 insertions(+) create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.h diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index 7563a2a842..b6f5197ac7 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -9,6 +9,7 @@ #include "Inference/PokemonBDSP_MenuDetector.h" #include "Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h" +#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h" @@ -53,6 +54,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_RecoveryWalk(database); add_tests_AutoStory_StorySim(database); add_tests_AutoStory_SimFailureCases(database); + add_tests_AutoStory_FaultSweep(database); add_tests_AutoStory_StoryActions(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp new file mode 100644 index 0000000000..4d29c971bd --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp @@ -0,0 +1,360 @@ +/* BDSP AutoStory - Fault sweeps on the story simulation + * + * From: https://github.com/PokemonAutomation/ + * + * Each class of failure console B showed, injected at every step of every + * row where the game can cause it, instead of only where it was seen: + * + * - SCENE_END_POSE: a step whose end pose the game sets (a talk, a scene, + * a battle, an event) leaves the player on another walkable tile within + * one of the table's (00.03, lab-B 2026-11-09: Rowan's scene ended a row + * low). SimWorldKnobs::lands. + * - BATTLE_OPENING: a battle's opening is still playing when a step starts + * (00.02's Starly, lab-B 2026-11-09), at each battle step and at each + * step after a walk, which can end in a trainer's sight or in grass. + * SimWorldKnobs::battle_opening_before. + * + * Missed and short fades are swept by SimFailureCases_Tests (every single + * missed fade, banner and fade hold). Wild battles at the game's rates + * need grass on the story maps, which the simulation does not have yet. + * A lost tap from the input lockout waits for the measured movement + * table (FRLG #293); FaultClass::LOST_TAP is its slot. + * + * Each row is run clean first; a row that fails clean is not swept. A + * variant fails when the row then fails. 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, to be taken off the list. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StorySim.h" +#include "PokemonBDSP_AutoStory_FaultSweep_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +namespace{ + +using Pokemon::Direction; +using Pokemon::Pose; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + +enum class FaultClass{ + SCENE_END_POSE, + BATTLE_OPENING, + // Not swept yet: the measured movement table's lost taps (#293). + LOST_TAP, +}; +const char* fault_class_name(FaultClass fault){ + switch (fault){ + case FaultClass::SCENE_END_POSE: + return "scene end pose"; + case FaultClass::BATTLE_OPENING: + return "battle opening at step start"; + case FaultClass::LOST_TAP: + return "lost tap"; + } + return "?"; +} + +// The rows swept: those the clean simulation runs (SimFailureCases_Tests). +const char* FIRST_ROW = "00.00"; +const char* LAST_ROW = "01.11"; + +// Sweeps the program fails today, by test name, with the likely fix. +const std::map KNOWN_FAILING{ + {"PokemonBDSP::AutoStory - Fault sweep: 00.01, battle opening at step start", + "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, + {"PokemonBDSP::AutoStory - Fault sweep: 00.01, scene end pose", + "the walk after barry_runs_to_the_lake, barry_warns_us trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, + {"PokemonBDSP::AutoStory - Fault sweep: 00.02, battle opening at step start", + "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, + {"PokemonBDSP::AutoStory - Fault sweep: 00.03, battle opening at step start", + "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, + {"PokemonBDSP::AutoStory - Fault sweep: 00.03, scene end pose", + "the walk after rowan_and_dawn trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, + {"PokemonBDSP::AutoStory - Fault sweep: 00.04, battle opening at step start", + "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, + {"PokemonBDSP::AutoStory - Fault sweep: 00.04, scene end pose", + "the walk after mom_heals_us, moms_hat trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, + {"PokemonBDSP::AutoStory - Fault sweep: 00.04b, battle opening at step start", + "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, + {"PokemonBDSP::AutoStory - Fault sweep: 00.05, battle opening at step start", + "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, + {"PokemonBDSP::AutoStory - Fault sweep: 00.05b, battle opening at step start", + "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, + {"PokemonBDSP::AutoStory - Fault sweep: 00.05b, scene end pose", + "the walk after president_walks_up, tv_clowns_coupon trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, + {"PokemonBDSP::AutoStory - Fault sweep: 00.05c, scene end pose", + "the walk after the_poketch trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, + {"PokemonBDSP::AutoStory - Fault sweep: 01.01, battle opening at step start", + "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, + {"PokemonBDSP::AutoStory - Fault sweep: 01.02, battle opening at step start", + "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, + {"PokemonBDSP::AutoStory - Fault sweep: 01.02, scene end pose", + "the walk after the_hiker trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, + {"PokemonBDSP::AutoStory - Fault sweep: 01.02b, scene end pose", + "the walk after barrys_lines trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, + {"PokemonBDSP::AutoStory - Fault sweep: 01.03, battle opening at step start", + "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, + {"PokemonBDSP::AutoStory - Fault sweep: 01.03, scene end pose", + "the walk after roark_smashes_the_rock trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, + {"PokemonBDSP::AutoStory - Fault sweep: 01.05, battle opening at step start", + "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, + {"PokemonBDSP::AutoStory - Fault sweep: 01.05, scene end pose", + "the walk after barry_bumps_into_us trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, + {"PokemonBDSP::AutoStory - Fault sweep: 01.08, battle opening at step start", + "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, + {"PokemonBDSP::AutoStory - Fault sweep: 01.09, battle opening at step start", + "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, + {"PokemonBDSP::AutoStory - Fault sweep: 01.10, battle opening at step start", + "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, + {"PokemonBDSP::AutoStory - Fault sweep: 01.11, battle opening at step start", + "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, + {"PokemonBDSP::AutoStory - Fault sweep: 01.11, scene end pose", + "the walk after old_woman_talks trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, +}; + +// Runs row `row` with `knobs`: "" if it passes, else where and why it stopped. +std::string run_row(Logger& logger, const std::string& row, SimWorldKnobs knobs){ + SimExecutor executor(logger, {.fade = {}, .banner = {}}, std::move(knobs)); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = row, .to = row}); + return report.completed ? "" : std::format("stopped in {}: {}", executor.result().failed_step, executor.result().error); +} + +// Whether the game, not our walking, sets where `kind` ends. +bool game_sets_end(StoryStepKind kind){ + switch (kind){ + case StoryStepKind::NEW_GAME: + case StoryStepKind::TALK: + case StoryStepKind::ANSWER: + case StoryStepKind::MASH: + case StoryStepKind::BATTLE: + case StoryStepKind::GAME: + return true; + default: + return false; + } +} +bool walks(StoryStepKind kind){ + return kind == StoryStepKind::ROUTE || kind == StoryStepKind::LEGS || kind == StoryStepKind::STEP; +} +// Whether the game left the player where they stood: a talk or a trainer's +// battle ends where our walk did, so it is not the game's end pose. +bool same_tile(const Pose& a, const Pose& b){ + const std::vector x = Pokemon::tiles_of(a); + const std::vector y = Pokemon::tiles_of(b); + return a.map == b.map && !x.empty() && !y.empty() && x.front() == y.front(); +} +// Whether walk `step` ends where a battle can start: on a route (grass, a +// trainer's sight) or in a cave. Towns and rooms have neither. +bool wild_or_trainers(const StoryStep& step){ + const std::optional& end = step.pose_after ? step.pose_after : step.target; + if (!end){ + return true; + } + for (const char* place : {"Route", "Gate", "Mine", "RavagedPath"}){ + if (end->map.find(place) != std::string::npos){ + return true; + } + } + return false; +} + +// The tiles within one of `pose`'s first tile, diagonals too, that the +// player can reach from it in one or two steps: where a scene can leave +// them instead. A tile behind a wall or a person's is not one. +std::vector walkable_neighbors(const Pose& pose){ + const std::vector tiles = Pokemon::tiles_of(pose); + const StoryWorld* world = pose.map.empty() ? nullptr : story_plan_world(pose.map, pose.map); + if (tiles.empty() || world == nullptr){ + return {}; + } + const TilePos center = tiles.front(); + const auto step = [](const TilePos& tile, Direction direction){ + switch (direction){ + case Direction::NORTH: + return TilePos{tile.x, tile.y - 1}; + case Direction::SOUTH: + return TilePos{tile.x, tile.y + 1}; + case Direction::WEST: + return TilePos{tile.x - 1, tile.y}; + default: + return TilePos{tile.x + 1, tile.y}; + } + }; + const auto can_step = [&](const TilePos& from, Direction direction){ + GridSim sim(SimWorld{.world = world}, story_to_world(*world, pose.map, from), direction, false); + return sim_can_step(sim, direction); + }; + std::set> seen{{center.x, center.y}}; + std::vector out; + const auto add = [&](const TilePos& tile){ + if (seen.insert({tile.x, tile.y}).second){ + out.push_back(tile); + } + }; + const Direction all[] = {Direction::NORTH, Direction::SOUTH, Direction::WEST, Direction::EAST}; + for (Direction first : all){ + if (!can_step(center, first)){ + continue; + } + const TilePos one = step(center, first); + add(one); + for (Direction second : all){ + const TilePos two = step(one, second); + const bool diagonal = two.x != center.x && two.y != center.y; + if (diagonal && can_step(one, second)){ + add(two); + } + } + } + return out; +} + +// 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; +} + +// Row `row`'s steps whose end the game sets, each ending on every walkable +// tile next to the table's pose in turn. +UnitTestResult sweep_scene_end_pose(Logger& logger, const StoryCheckpoint& row){ + std::vector failures; + size_t variants = 0; + std::optional before = row.start; + for (const StoryStep& step : row.steps){ + const std::optional was = std::exchange(before, step.pose_after ? step.pose_after : walks(step.kind) ? step.target : before); + if (!game_sets_end(step.kind) || !step.pose_after || (was && same_tile(*was, *step.pose_after))){ + continue; + } + for (const TilePos& tile : walkable_neighbors(*step.pose_after)){ + SimWorldKnobs knobs; + knobs.lands[step.name] = Pokemon::tile_pose(step.pose_after->map, {tile}, Pokemon::facing_of(*step.pose_after)); + variants++; + const std::string stopped = run_row(logger, row.id, std::move(knobs)); + if (!stopped.empty()){ + failures.push_back({step.name, std::format("ends on ({}, {})", tile.x, tile.y), stopped}); + } + } + } + return sweep_result(logger, FaultClass::SCENE_END_POSE, row.id, variants, failures); +} + +// Row `row` with a battle's opening still playing at the start of each +// battle step and of each step after a walk, one at a time. +UnitTestResult sweep_battle_opening(Logger& logger, const StoryCheckpoint& row){ + std::vector failures; + size_t variants = 0; + for (size_t c = 0; c < row.steps.size(); c++){ + const StoryStep& step = row.steps[c]; + const bool after_walk = c > 0 && walks(row.steps[c - 1].kind) && wild_or_trainers(row.steps[c - 1]); + if (step.kind != StoryStepKind::BATTLE && !after_walk){ + continue; + } + SimWorldKnobs knobs; + knobs.battle_opening_before = [id = row.id, name = step.name](const std::string& r, const std::string& s){ + return r == id && s == name; + }; + variants++; + const std::string stopped = run_row(logger, row.id, std::move(knobs)); + if (!stopped.empty()){ + failures.push_back({step.name, "opening at its start", stopped}); + } + } + return sweep_result(logger, FaultClass::BATTLE_OPENING, row.id, variants, failures); +} + +class Test_AutoStoryFaultSweep : public UnitTest{ +public: + Test_AutoStoryFaultSweep(FaultClass fault, StoryCheckpoint row) + : UnitTest(std::format("PokemonBDSP::AutoStory - Fault sweep: {}, {}", row.id, fault_class_name(fault))) + , m_fault(fault) + , m_row(std::move(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 std::string clean = run_row(logger, m_row.id, {}); + if (!clean.empty()){ + logger.log(std::format("Fault sweep {}: not swept, the row fails clean: {}", m_row.id, clean)); + return true; + } + switch (m_fault){ + case FaultClass::SCENE_END_POSE: + return sweep_scene_end_pose(logger, m_row); + case FaultClass::BATTLE_OPENING: + return sweep_battle_opening(logger, m_row); + case FaultClass::LOST_TAP: + break; + } + return true; + } + + FaultClass m_fault; + StoryCheckpoint m_row; +}; + +} // namespace + +void add_tests_AutoStory_FaultSweep(UnitTestDatabase& database){ + for (const StoryCheckpoint& row : story_checkpoints()){ + if (row.id < FIRST_ROW || row.id > LAST_ROW){ + continue; + } + for (FaultClass fault : {FaultClass::SCENE_END_POSE, FaultClass::BATTLE_OPENING}){ + database.add(fault, row); + } + } +} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.h new file mode 100644 index 0000000000..7222d25869 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.h @@ -0,0 +1,27 @@ +/* BDSP AutoStory - Fault sweeps on the story simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_FaultSweep_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_FaultSweep_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// Each class of console failure injected at every step of every row where +// the game can cause it; the rows the program still fails are known failing. +void add_tests_AutoStory_FaultSweep(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index b849dd7292..165cf4edb2 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1787,6 +1787,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.h Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp From 0d79b7b6f4b655bc04aad7f7ea7e7ad2549d1ae5 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 13:50:35 -0800 Subject: [PATCH 091/166] BDSP AutoStory sim: fault sweep cases as a table of designated cases Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...PokemonBDSP_AutoStory_FaultSweep_Tests.cpp | 51 +++++++++++++++---- 1 file changed, 40 insertions(+), 11 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp index 4d29c971bd..5a47c3c6b2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp @@ -295,12 +295,36 @@ UnitTestResult sweep_battle_opening(Logger& logger, const StoryCheckpoint& row){ return sweep_result(logger, FaultClass::BATTLE_OPENING, row.id, variants, failures); } +// A fault class swept over row `row` (empty in FAULT_SWEEP_CASES: each +// row from FIRST_ROW to LAST_ROW). +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: - Test_AutoStoryFaultSweep(FaultClass fault, StoryCheckpoint row) - : UnitTest(std::format("PokemonBDSP::AutoStory - Fault sweep: {}, {}", row.id, fault_class_name(fault))) - , m_fault(fault) - , m_row(std::move(row)) + explicit Test_AutoStoryFaultSweep(FaultSweepCase test_case) + : UnitTest(std::format("PokemonBDSP::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; @@ -339,18 +363,23 @@ class Test_AutoStoryFaultSweep : public UnitTest{ } FaultClass m_fault; - StoryCheckpoint m_row; + const StoryCheckpoint& m_row; }; } // namespace +const FaultSweepCase FAULT_SWEEP_CASES[] = { + {.input = {.fault = FaultClass::SCENE_END_POSE}, .expectation = {}}, + {.input = {.fault = FaultClass::BATTLE_OPENING}, .expectation = {}}, +}; + void add_tests_AutoStory_FaultSweep(UnitTestDatabase& database){ - for (const StoryCheckpoint& row : story_checkpoints()){ - if (row.id < FIRST_ROW || row.id > LAST_ROW){ - continue; - } - for (FaultClass fault : {FaultClass::SCENE_END_POSE, FaultClass::BATTLE_OPENING}){ - database.add(fault, row); + for (const FaultSweepCase& item : FAULT_SWEEP_CASES){ + for (const StoryCheckpoint& row : story_checkpoints()){ + if (row.id < FIRST_ROW || row.id > LAST_ROW){ + continue; + } + database.add(FaultSweepCase{.input = {.fault = item.input.fault, .row = row.id}, .expectation = item.expectation}); } } } From 03006cd47f69219e44438a501da68781013ea1ce Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 14:07:27 -0800 Subject: [PATCH 092/166] BDSP AutoStory sim: sweep only scenes that moved the player, round every tile of their pose MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A step's end pose is the game's only when the clean run up to it does not already stand on it: talks and scenes that only turn the player (the old woman's, the hiker's, the Pokétch) end where our walk did. The landing tiles are the walkable neighbours of every tile of the pose, so 00.03's four tiles are swept round as a set. Six rows come off KNOWN_FAILING. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...PokemonBDSP_AutoStory_FaultSweep_Tests.cpp | 78 ++++++++++--------- 1 file changed, 43 insertions(+), 35 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp index 5a47c3c6b2..00d973a1d4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp @@ -81,7 +81,7 @@ const std::map KNOWN_FAILING{ {"PokemonBDSP::AutoStory - Fault sweep: 00.01, battle opening at step start", "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, {"PokemonBDSP::AutoStory - Fault sweep: 00.01, scene end pose", - "the walk after barry_runs_to_the_lake, barry_warns_us trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, + "the walk after barry_runs_to_the_lake trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, {"PokemonBDSP::AutoStory - Fault sweep: 00.02, battle opening at step start", "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, {"PokemonBDSP::AutoStory - Fault sweep: 00.03, battle opening at step start", @@ -98,22 +98,12 @@ const std::map KNOWN_FAILING{ "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, {"PokemonBDSP::AutoStory - Fault sweep: 00.05b, battle opening at step start", "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, - {"PokemonBDSP::AutoStory - Fault sweep: 00.05b, scene end pose", - "the walk after president_walks_up, tv_clowns_coupon trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, - {"PokemonBDSP::AutoStory - Fault sweep: 00.05c, scene end pose", - "the walk after the_poketch trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, {"PokemonBDSP::AutoStory - Fault sweep: 01.01, battle opening at step start", "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, {"PokemonBDSP::AutoStory - Fault sweep: 01.02, battle opening at step start", "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, - {"PokemonBDSP::AutoStory - Fault sweep: 01.02, scene end pose", - "the walk after the_hiker trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, - {"PokemonBDSP::AutoStory - Fault sweep: 01.02b, scene end pose", - "the walk after barrys_lines trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, {"PokemonBDSP::AutoStory - Fault sweep: 01.03, battle opening at step start", "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, - {"PokemonBDSP::AutoStory - Fault sweep: 01.03, scene end pose", - "the walk after roark_smashes_the_rock trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, {"PokemonBDSP::AutoStory - Fault sweep: 01.05, battle opening at step start", "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, {"PokemonBDSP::AutoStory - Fault sweep: 01.05, scene end pose", @@ -126,8 +116,6 @@ const std::map KNOWN_FAILING{ "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, {"PokemonBDSP::AutoStory - Fault sweep: 01.11, battle opening at step start", "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, - {"PokemonBDSP::AutoStory - Fault sweep: 01.11, scene end pose", - "the walk after old_woman_talks trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, }; // Runs row `row` with `knobs`: "" if it passes, else where and why it stopped. @@ -154,12 +142,25 @@ bool game_sets_end(StoryStepKind kind){ bool walks(StoryStepKind kind){ return kind == StoryStepKind::ROUTE || kind == StoryStepKind::LEGS || kind == StoryStepKind::STEP; } -// Whether the game left the player where they stood: a talk or a trainer's -// battle ends where our walk did, so it is not the game's end pose. -bool same_tile(const Pose& a, const Pose& b){ - const std::vector x = Pokemon::tiles_of(a); - const std::vector y = Pokemon::tiles_of(b); - return a.map == b.map && !x.empty() && !y.empty() && x.front() == y.front(); +// Whether row `row` run clean up to its step `c` leaves the player on one +// of `pose`'s tiles: a talk, a trainer's battle or a scene that only turns +// the player ends where our walk did, so its end is not the game's. +bool already_there(Logger& logger, const StoryCheckpoint& row, size_t c, const Pose& pose){ + StoryCheckpoint head = row; + head.steps.resize(c); + SimExecutor executor(logger, {.fade = {}, .banner = {}}, {}); + if (!run_rows_on(executor, logger, {.from = row.id, .to = row.id}, {head}).completed || executor.result().world == nullptr){ + return false; + } + const SimRun& run = executor.result(); + for (const TilePos& tile : Pokemon::tiles_of(pose)){ + try{ + if (story_to_world(*run.world, pose.map, tile) == run.end){ + return true; + } + }catch (const InternalProgramError&){} + } + return false; } // Whether walk `step` ends where a battle can start: on a route (grass, a // trainer's sight) or in a cave. Towns and rooms have neither. @@ -176,16 +177,10 @@ bool wild_or_trainers(const StoryStep& step){ return false; } -// The tiles within one of `pose`'s first tile, diagonals too, that the -// player can reach from it in one or two steps: where a scene can leave -// them instead. A tile behind a wall or a person's is not one. -std::vector walkable_neighbors(const Pose& pose){ - const std::vector tiles = Pokemon::tiles_of(pose); - const StoryWorld* world = pose.map.empty() ? nullptr : story_plan_world(pose.map, pose.map); - if (tiles.empty() || world == nullptr){ - return {}; - } - const TilePos center = tiles.front(); +// The tiles within one of `center`, diagonals too, that the player can +// reach from it in one or two steps, and not in `seen`: where a scene can +// leave them instead. A tile behind a wall is not one. +void walkable_neighbors(const StoryWorld* world, const Pose& pose, const TilePos& center, std::set>& seen, std::vector& out){ const auto step = [](const TilePos& tile, Direction direction){ switch (direction){ case Direction::NORTH: @@ -202,8 +197,6 @@ std::vector walkable_neighbors(const Pose& pose){ GridSim sim(SimWorld{.world = world}, story_to_world(*world, pose.map, from), direction, false); return sim_can_step(sim, direction); }; - std::set> seen{{center.x, center.y}}; - std::vector out; const auto add = [&](const TilePos& tile){ if (seen.insert({tile.x, tile.y}).second){ out.push_back(tile); @@ -224,6 +217,22 @@ std::vector walkable_neighbors(const Pose& pose){ } } } +} +// The walkable tiles next to any of `pose`'s tiles, not its own. +std::vector walkable_neighbors(const Pose& pose){ + const std::vector tiles = Pokemon::tiles_of(pose); + const StoryWorld* world = pose.map.empty() ? nullptr : story_plan_world(pose.map, pose.map); + std::vector out; + if (world == nullptr){ + return out; + } + std::set> seen; + for (const TilePos& tile : tiles){ + seen.insert({tile.x, tile.y}); + } + for (const TilePos& tile : tiles){ + walkable_neighbors(world, pose, tile, seen, out); + } return out; } @@ -252,10 +261,9 @@ UnitTestResult sweep_result(Logger& logger, FaultClass fault, const std::string& UnitTestResult sweep_scene_end_pose(Logger& logger, const StoryCheckpoint& row){ std::vector failures; size_t variants = 0; - std::optional before = row.start; - for (const StoryStep& step : row.steps){ - const std::optional was = std::exchange(before, step.pose_after ? step.pose_after : walks(step.kind) ? step.target : before); - if (!game_sets_end(step.kind) || !step.pose_after || (was && same_tile(*was, *step.pose_after))){ + for (size_t c = 0; c < row.steps.size(); c++){ + const StoryStep& step = row.steps[c]; + if (!game_sets_end(step.kind) || !step.pose_after || already_there(logger, row, c, *step.pose_after)){ continue; } for (const TilePos& tile : walkable_neighbors(*step.pose_after)){ From 0cab275589ab26e5b1eaedb1e63d8f86b830d842 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 14:09:56 -0800 Subject: [PATCH 093/166] BDSP AutoStory: 00.03 walks east into Rowan's scene The route to (4, 14) and the step onto the trigger become a route to the Lakefront's wall and one walk east until Rowan's scene starts (to_dialogue), 22 tiles at most. A sim case starts the scene on each of the trigger's rows 14..16 and checks the walk stops on it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Data/route_plans.golden.txt | 7 ++-- .../PokemonBDSP_AutoStory_StoryTable.cpp | 5 +-- ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 35 +++++++++++++++++++ 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt index b31c00f6d0..c08dc7959f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt @@ -63,13 +63,12 @@ anchor); 0 from one start tile. target: VerityLakefront (17, 14) facing north (tile) not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends) -== 00.03 short_of_rowan (costs: route) +== 00.03 to_the_lakefront_wall (costs: route) from: VerityLakefront (17, 14) (17, 15) (set) - target: Route201 (4, 14) facing east (tile) + target: VerityLakefront (17, 21) (tile) start candidates: Verity Lakefront (17, 14), Verity Lakefront (17, 15) 1. south 7 (to wall) -> Verity Lakefront (17, 21) - 2. east 19 (open) -> Route 201 (4, 14) - totals: 2 legs, 1 turns, 1 open, 1 localization + totals: 1 legs, 0 turns, 0 open, 1 localization == 00.03 beside_the_door_column (costs: route) from: PlayerHouse1F (4, 8) facing south (tile) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 9251434dbf..b1184724cc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -331,8 +331,9 @@ std::vector lake_and_pokedex(){ "Rowan's lines and the walk out of the lake"), }), row("00.03", "Back to Sandgem: Rowan, Dawn and the Pokedex", at_or_next_to(LAKEFRONT, "below_lake_entrance", SOUTH), { - route("short_of_rowan", at(ROUTE_201, 4, 14, EAST), "back east onto Route 201's lower level"), - step_into("rowans_stop", EAST, "the trigger (5, 14..16)"), + // The wall's row 21 runs on as Route 201's 14, through Rowan's trigger (5, 14..16). + route("to_the_lakefront_wall", at(LAKEFRONT, 17, 21), "south to the Lakefront's wall, the row into Rowan's trigger"), + legs("into_rowans_scene", {{.direction = EAST, .tiles = 22}}, "east onto Route 201 until Rowan's scene starts: 20 tiles, 22 at most", "to_dialogue"), // BDSP, unlike Diamond: after Rowan leaves, Dawn's and Barry's lines, then // the game fades to the house, where Mom gives the Running Shoes. The // scene ends near her, by the rug: (6, 8) in r24 and r27, (5, 8) in diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp index 39b9146e98..909327b5fa 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -345,6 +345,40 @@ UnitTestResult home_from_each_scene_end(Logger& logger){ return passes(failures); } +// The table with row `id` cut to `step` alone, from `start`. +std::vector table_with_row(const std::string& id, const Pose& start, const StoryStep& step){ + std::vector rows = story_checkpoints(); + for (StoryCheckpoint& checkpoint : rows){ + if (checkpoint.id == id){ + checkpoint.start = start; + checkpoint.steps = {step}; + } + } + return rows; +} +// 00.03: Rowan's trigger is the column (5, 14..16) on Route 201 (decomp). +// The walk east from the Lakefront's wall runs along Route 201's row 14, +// or a row or two lower if the hold south stopped short of the wall. Each +// of the three rows starts the scene, and the walk stops on its tile. +// The Lakefront's rows 21..23 are Route 201's 14..16. +UnitTestResult rowans_scene_on_each_row(Logger& logger){ + const StoryStep& walk = table_step("00.03", "into_rowans_scene"); + std::string failures; + for (int row = 14; row <= 16; row++){ + const Pose start = Pokemon::tile_pose("VerityLakefront", {TilePos{20, row + 7}}, Direction::EAST); + const std::vector rows = table_with_row("00.03", start, walk); + SimExecutor executor(logger, {.fade = {}, .banner = {}}, {}); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = "00.03", .to = "00.03"}, rows); + const Pose trigger = Pokemon::tile_pose("Route201", {TilePos{5, row}}, Direction::EAST); + if (!report.completed){ + failures += std::format("\nrow {}: stopped in {}: {}", row, executor.result().failed_step, executor.result().error); + }else if (!ends_on(executor.result(), trigger)){ + failures += std::format("\nrow {}: the walk ended at {}, not on (5, {})", row, end_of(executor.result()), row); + } + } + return passes(failures); +} + struct FailureCaseInput{ std::string name; std::function body; @@ -424,6 +458,7 @@ const FailureCase AUTO_STORY_FAILURE_CASES[] = { {.input = {"00.03 Rowan's scene opens with no box and fades home", rowans_scene_opens_with_no_box}, .expectation = {}}, {.input = {"00.02 the Starly battle's opening still plays after the starter (lab-B 2026-11-09)", starly_opening_after_the_starter}, .expectation = {}}, {.input = {"00.03 out of the house from each tile Rowan's scene ends on, rows 8 and 9 (lab-B 2026-11-09)", home_from_each_scene_end}, .expectation = {}}, + {.input = {"00.03 Rowan's scene starts on each of the trigger's rows 14..16, and the walk stops there", rowans_scene_on_each_row}, .expectation = {}}, }; void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database){ From 6647afa3ec798aa01b6533c47d026ae504a2f87c Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 14:17:00 -0800 Subject: [PATCH 094/166] BDSP AutoStory sim: a battle's opening shows its battle; sweep expects it cleared The sim's opening (SimWorldKnobs::battle_opening_before) stayed a white with no battle on every look. Now its battle shows on the sixth look of the screen, past a door fade's three, as the console's does a second or two after the flash, and the interrupt handler that clears it ends the opening. With StoryInterrupts waiting for an opening's battle (#122), the 51 steps of 00.01-01.11 the fault sweep injected an opening before now pass: off KNOWN_FAILING. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...PokemonBDSP_AutoStory_FaultSweep_Tests.cpp | 30 ------------------- .../PokemonBDSP_AutoStory_StorySim.cpp | 26 ++++++++++++---- .../PokemonBDSP_AutoStory_StorySim.h | 10 +++++-- 3 files changed, 28 insertions(+), 38 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp index 00d973a1d4..b4a2245277 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp @@ -78,44 +78,14 @@ const char* LAST_ROW = "01.11"; // Sweeps the program fails today, by test name, with the likely fix. const std::map KNOWN_FAILING{ - {"PokemonBDSP::AutoStory - Fault sweep: 00.01, battle opening at step start", - "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, {"PokemonBDSP::AutoStory - Fault sweep: 00.01, scene end pose", "the walk after barry_runs_to_the_lake trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, - {"PokemonBDSP::AutoStory - Fault sweep: 00.02, battle opening at step start", - "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, - {"PokemonBDSP::AutoStory - Fault sweep: 00.03, battle opening at step start", - "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, {"PokemonBDSP::AutoStory - Fault sweep: 00.03, scene end pose", "the walk after rowan_and_dawn trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, - {"PokemonBDSP::AutoStory - Fault sweep: 00.04, battle opening at step start", - "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, {"PokemonBDSP::AutoStory - Fault sweep: 00.04, scene end pose", "the walk after mom_heals_us, moms_hat trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, - {"PokemonBDSP::AutoStory - Fault sweep: 00.04b, battle opening at step start", - "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, - {"PokemonBDSP::AutoStory - Fault sweep: 00.05, battle opening at step start", - "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, - {"PokemonBDSP::AutoStory - Fault sweep: 00.05b, battle opening at step start", - "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, - {"PokemonBDSP::AutoStory - Fault sweep: 01.01, battle opening at step start", - "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, - {"PokemonBDSP::AutoStory - Fault sweep: 01.02, battle opening at step start", - "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, - {"PokemonBDSP::AutoStory - Fault sweep: 01.03, battle opening at step start", - "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, - {"PokemonBDSP::AutoStory - Fault sweep: 01.05, battle opening at step start", - "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, {"PokemonBDSP::AutoStory - Fault sweep: 01.05, scene end pose", "the walk after barry_bumps_into_us trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, - {"PokemonBDSP::AutoStory - Fault sweep: 01.08, battle opening at step start", - "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, - {"PokemonBDSP::AutoStory - Fault sweep: 01.09, battle opening at step start", - "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, - {"PokemonBDSP::AutoStory - Fault sweep: 01.10, battle opening at step start", - "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, - {"PokemonBDSP::AutoStory - Fault sweep: 01.11, battle opening at step start", - "StoryInterrupts: an opening before a step that is not a battle fails as interrupt_unsettled; wait for the battle and clear it (#122)"}, }; // Runs row `row` with `knobs`: "" if it passes, else where and why it stopped. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index ce0c89cbe6..36e7499a3d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -662,7 +662,11 @@ StoryBoundActions SimExecutor::sim_actions(){ }; } -Pokemon::ScreenLook SimExecutor::look(){ +// The look at a battle's opening that shows its battle: past the three +// looks of a door's fade (StoryInterrupts::max_looks), 1.8 s at BDSP's. +constexpr size_t OPENING_LOOKS = 6; + +Pokemon::ScreenLook SimExecutor::look(bool fresh){ const WallClock start = WallClock() + std::chrono::hours(1); Pokemon::ScreenLook out; out.log.record({Pokemon::ScreenEvent::PLAYER_CAN_MOVE}, start); @@ -671,13 +675,18 @@ Pokemon::ScreenLook SimExecutor::look(){ } if (m_battle_opening){ out.log.record({Pokemon::ScreenEvent::FADE_WHITE}, start + 33ms); + m_opening_looks = fresh ? 1 : m_opening_looks + 1; + if (m_opening_looks >= OPENING_LOOKS){ + out.log.record({Pokemon::ScreenEvent::BATTLE_STARTED}, start + BETWEEN_STEPS_LOOK - 33ms); + } } out.window = {.start = start, .end = start + BETWEEN_STEPS_LOOK}; return out; } -// Every kind closes what is up and logs it: the simulation shows only -// the dialogs it pops up. +// A dialog or a warp closes what is up and logs it: the simulation shows +// only the dialogs it pops up. A battle ends its opening only: a scene the +// walk before ran into goes on after it. StoryInterruptActions SimExecutor::sim_interrupt_actions(){ const auto cleared = [this](const char* what){ return [this, what](RunState&, const Pokemon::InterruptVerdict&){ @@ -687,9 +696,16 @@ StoryInterruptActions SimExecutor::sim_interrupt_actions(){ return Pokemon::outcome_ok(); }; }; + const auto battled = [this](const char* what){ + return [this, what](RunState&, const Pokemon::InterruptVerdict&){ + m_logger.log(std::format("[{}] {}: {} cleared before it.", m_row, m_step, what)); + m_battle_opening = false; + return Pokemon::outcome_ok(); + }; + }; return StoryInterruptActions{ - .wild = cleared("a wild battle"), - .trainer = cleared("a trainer's battle"), + .wild = battled("a wild battle"), + .trainer = battled("a trainer's battle"), .dialog = cleared("a dialog"), .warp = cleared("a warp"), }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index 6fb9563bb8..0f18be3e9d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -378,7 +378,7 @@ class SimExecutor : public Pokemon::TableExecutor{ , m_io(m_sim, m_notes, m_misses, m_knobs, m_step, [this]{ return cross(); }, [this](const Pokemon::Pose& far){ cross_to(far); }) , m_walks(m_io) , m_table(story_action_table(m_walks, sim_actions())) - , m_interrupts(story_interrupts([this](bool){ return look(); }, sim_interrupt_actions())) + , m_interrupts(story_interrupts([this](bool fresh){ return look(fresh); }, sim_interrupt_actions())) { if (m_knobs.clear_interrupts){ set_interrupts(&m_interrupts); @@ -433,8 +433,10 @@ class SimExecutor : public Pokemon::TableExecutor{ // A step the simulation does not play: its dialogue opened and closed. Pokemon::Outcome stub(); StoryBoundActions sim_actions(); - // The screen between steps: the dialog that popped up, if one did. - Pokemon::ScreenLook look(); + // The screen between steps: the dialog that popped up, if one did; a + // battle's opening, its battle on the OPENING_LOOKS-th look. `fresh` + // starts a new look. + Pokemon::ScreenLook look(bool fresh); // What the knobs put on the screen before `step`: a dialog that pops // up, a battle's opening still playing. void show_before(const Pokemon::StoryStep& step); @@ -471,6 +473,8 @@ class SimExecutor : public Pokemon::TableExecutor{ // A battle's opening is playing before this step // (SimWorldKnobs::battle_opening_before). bool m_battle_opening = false; + // Looks at the opening so far, from the fresh one. + size_t m_opening_looks = 0; // The planner's worlds with sim_people() on them, by world and who. mutable std::map, std::unique_ptr> m_peopled; // The steps of this row that have run. From ad99f1e83be3e33455134dc9035dec4b45b3bd18 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 15:03:15 -0800 Subject: [PATCH 095/166] BDSP AutoStory 00.03: out of the house from Mom's proven scene end Mom's Running Shoes scene ends on (6, 8) facing east: 7 of 7 console runs stopped right after it (lab-B 2026-11-09, ~/BDSPLab/captures/mom-proof). The rows 7, 9 and 10 seen before were our input landing in the scene's closing fade, which TalkOver now waits out. The scene's pose is that tile, and the four tolerance steps (by_the_counter, which_row, beside_the_door_column, above_the_door_again) go: the door step holds south onto the door's tile (6, 10). A new STEP variant "or_legs" covers a column west: with no fade the hold stopped on (5, 10), so it taps the step's legs (east onto the mat) and runs into the door again. The scene-end-pose sweep leaves out scenes the console has proven (PROVEN_SCENE_ENDS), so 00.03's sweep passes and leaves KNOWN_FAILING. The console guard logs how the screen looked before every step ([Screen]). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Data/route_plans.golden.txt | 15 -------- .../PokemonBDSP_AutoStory_StoryExecutor.cpp | 4 +++ .../PokemonBDSP_AutoStory_StoryExecutor.h | 5 ++- .../PokemonBDSP_AutoStory_StoryTable.cpp | 36 +++++++++---------- ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 2 +- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 26 +++++++++++++- .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 1 + ...PokemonBDSP_AutoStory_FaultSweep_Tests.cpp | 20 +++++++---- ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 12 +++---- 9 files changed, 73 insertions(+), 48 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt index c08dc7959f..5cf5b09f51 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt @@ -70,21 +70,6 @@ anchor); 0 from one start tile. 1. south 7 (to wall) -> Verity Lakefront (17, 21) totals: 1 legs, 0 turns, 0 open, 1 localization -== 00.03 beside_the_door_column (costs: route) - from: PlayerHouse1F (4, 8) facing south (tile) - target: PlayerHouse1F (5, 9) facing east (tile) - start candidates: PlayerHouse1F (4, 8) - 1. east 1 (open) -> PlayerHouse1F (5, 8) - 2. south 1 (open) -> PlayerHouse1F (5, 9) - totals: 2 legs, 1 turns, 2 open, 0 localization - -== 00.03 beside_the_door_column (costs: route) - from: PlayerHouse1F (5, 10) facing south (tile) - target: PlayerHouse1F (5, 9) facing east (tile) - start candidates: PlayerHouse1F (5, 10) - 1. north 1 (open) -> PlayerHouse1F (5, 9) - totals: 1 legs, 0 turns, 1 open, 0 localization - == 00.03 short_of_dawn (costs: route) from: TwinleafTown (20, 22) facing south (tile) target: Route201 (63, 5) facing east (tile) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp index 756a377fbc..8740e87d74 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp @@ -122,6 +122,10 @@ void ConsoleStepGuard::on_interrupt(const StoryStep& step, const Pokemon::Interr ), cleared ? COLOR_ORANGE : COLOR_RED); } +void ConsoleStepGuard::on_screen(const StoryStep& step, const Pokemon::ScreenSettle& screen){ + m_stream.log(std::format("[Screen] before {}: {}", step.name, Pokemon::describe(screen))); +} + // The table and the guard are members, built after the base: it only // keeps references to them until a step runs. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h index 0a8b93f9c9..71fdd805bd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h @@ -109,6 +109,7 @@ class ConsoleStepGuard : public Pokemon::StepGuard{ virtual bool stops_on_failure(const Pokemon::StoryStep& step) const override; virtual void on_failure(const Pokemon::StoryStep& step, const OperationFailedException& error) override; 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: VideoStream& m_stream; @@ -184,7 +185,9 @@ class StoryExecutor : public Pokemon::TableExecutor{ // whose taps the map lets move as many as moved are where we are. // - STEP: one D-pad step `direction`, turning first: onto a scene's // trigger or into a door. Variant "to_banner": one tap into a cave - // mouth, then wait for pose_after's map's location banner. + // mouth, then wait for pose_after's map's location banner. Variant + // "or_legs": into a door, and with no fade, the step's legs onto the + // door's tile and into it again. // - TALK: A at what we face; a dialogue must open. // - MASH: a dialogue opens (or has), then B through it to the overworld; // variant "a": A through it, for lines that give an item. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index b1184724cc..687cd309ca 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -307,12 +307,17 @@ std::vector intro(){ }; } -// 00.03, home: west to the wall first, as from the rug's row (r27, r28): -// there it stops on (4, 8) against the table's corner (3, 8); a row lower -// on (5, 9) against the wall (4, 9). Not east: Mom at (7, 8) talks (r29). -StoryStep by_the_counter(){ - return anchored(to_walls("by_the_counter", {{.direction = WEST, .tiles = 2}}, "west to the table's corner, or the wall a row lower"), - Pokemon::tile_pose(HOME, {TilePos{4, 8}, TilePos{5, 9}}, WEST)); +// 00.03, home: Mom's scene leaves us on (6, 8), and the door's tile +// (6, 10) is two below: hold south, and its fade is the way out. Mom's +// warning was spent in 00.01, so the door is a plain door now (r27). Were +// we a column west, the hold stops on (5, 10) against the wall with no +// fade: a tap east onto the mat, and south again. +StoryStep out_of_the_house_again(){ + StoryStep step = step_into("out_of_the_house_again", SOUTH, + "south onto the door's tile (6, 10), and out; from column 5, east onto the mat first", at(TWINLEAF, "house_doorstep", SOUTH)); + step.variant = "or_legs"; + step.legs = {{.direction = EAST, .tiles = 1}}; + return step; } std::vector lake_and_pokedex(){ @@ -336,19 +341,14 @@ std::vector lake_and_pokedex(){ legs("into_rowans_scene", {{.direction = EAST, .tiles = 22}}, "east onto Route 201 until Rowan's scene starts: 20 tiles, 22 at most", "to_dialogue"), // BDSP, unlike Diamond: after Rowan leaves, Dawn's and Barry's lines, then // the game fades to the house, where Mom gives the Running Shoes. The - // scene ends near her, by the rug: (6, 8) in r24 and r27, (5, 8) in - // r28, a row lower on lab-B 2026-11-09. - scene("rowan_and_dawn", Pokemon::tile_pose(HOME, {TilePos{5, 8}, TilePos{6, 8}, TilePos{5, 9}, TilePos{6, 9}}, EAST), + // scene ends on (6, 8) facing her, east: 7 of 7 console runs stopped + // right after the scene (lab-B 2026-11-09, ~/BDSPLab/captures/mom-proof). + // The other ends seen before (5, 8 in r28, a row lower at 12:49) were our + // input landing in the scene's closing fade, which the scene's end now + // waits out (TalkOver). + scene("rowan_and_dawn", at(HOME, 6, 8, EAST), "Rowan and Dawn come back; Barry, then home for the Running Shoes"), - // Mom's warning was spent in 00.01, so the door's tile (6, 10) is a plain - // door now: stepping onto it goes out (r27). - by_the_counter(), - // A tap south tells (4, 8) and (5, 9) apart; from there to beside the - // door's column, not down it: an open leg south could slide onto the door. - legs("which_row", {{.direction = SOUTH, .tiles = 1}}, "a tap south: the wall (4, 9) stops it, or not", "measured"), - route("beside_the_door_column", at(HOME, 5, 9, EAST), "from the tile the tap told us"), - legs("above_the_door_again", {{.direction = EAST, .tiles = 1}}, "east a tile to above the door: not south toward it"), - step_into("out_of_the_house_again", SOUTH, "onto the door's tile (6, 10), and out", at(TWINLEAF, "house_doorstep", SOUTH)), + out_of_the_house_again(), // Through the grass now, with a starter: wild battles are run from. route("short_of_dawn", at(ROUTE_201, 63, 5, EAST), "Twinleaf, then east along Route 201 to its east edge"), // Dawn's scene starts as we come into Sandgem (trigger (4, 10..15)); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index 3a5ffbbb7e..dd378da285 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -47,7 +47,7 @@ const std::map>& built_in_variants(){ static const std::map> variants{ {StoryStepKind::ROUTE, {"", "town", "robust", "line"}}, {StoryStepKind::LEGS, {"", "one_short_ok", "to_wall", "counted_wall", "measured", "to_dialogue", "to_map"}}, - {StoryStepKind::STEP, {"", "to_banner", "tap"}}, + {StoryStepKind::STEP, {"", "to_banner", "tap", "or_legs"}}, {StoryStepKind::MASH, {"", "a"}}, {StoryStepKind::BATTLE, {"", "doubles", "starter"}}, }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index cf97fa7819..43c3b1b703 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -243,6 +243,27 @@ Outcome StoryWalkSteps::tap_to_banner(const Pose& from, const StoryStep& step){ return Pokemon::outcome_ok(); } +// A STEP "or_legs" whose run into the door saw no fade: the run stopped +// beside the door's column, against the wall it is in. The step's legs, a +// tap a tile, put us on the door's tile, then the run goes again (00.03: +// from (5, 10) east onto the mat (6, 10), then south). A tap onto the +// tile that is itself the way through ends it. +WarpSeen StoryWalkSteps::door_from_beside(const StoryStep& step, Milliseconds timeout, const std::string& banner){ + for (const Pokemon::StoryLeg& leg : step.legs){ + turn(leg.direction); + const WalkResult walk = m_io.route().walk_taps(leg.direction, (size_t)leg.tiles, step.name); + log(std::format("[{}] {}: no fade; {} {} taps {}, {}.", m_row, step.name, leg.tiles, + direction_name(leg.direction), walk.moved_chunks, walk_stop_name(walk.stop))); + if (walk.warp.any()){ + return walk.warp; + } + } + const WarpSeen seen = m_io.run_into_door(step.direction, m_can_run, timeout, Milliseconds(0), banner); + log(std::format("[{}] {}: {} through the door again: {}.", m_row, step.name, + direction_name(step.direction), seen.any() ? describe(seen) : "nothing yet")); + return seen; +} + // The route before ran on through this step's warp (walk_route_to_warp()): // the step is done, unless the banner it read names another map. bool StoryWalkSteps::through_already(const StoryStep& step){ @@ -502,9 +523,12 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ } const std::string banner = story_arrival_banner(state.pose.map, step.pose_after->map); const DoorRun door = door_run(state.pose.map, state.pose, step.direction, m_can_run); - const WarpSeen seen = m_io.run_into_door(step.direction, m_can_run, door.timeout, door.dark_from, banner); + WarpSeen seen = m_io.run_into_door(step.direction, m_can_run, door.timeout, door.dark_from, banner); log(std::format("[{}] {}: {} through the door (timeout {} ms, dark from {} ms): {}.", m_row, step.name, direction_name(step.direction), door.timeout.count(), door.dark_from.count(), seen.any() ? describe(seen) : "nothing yet")); + if (!seen.any() && step.variant == "or_legs"){ + seen = door_from_beside(step, door.timeout, banner); + } m_io.settle(BUTTON_B, label_of(step), !seen.any(), banner); return Pokemon::outcome_ok(); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index dc6c5e20dc..2542c861aa 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -93,6 +93,7 @@ class StoryWalkSteps{ Pokemon::Outcome leg_to_map(const Pokemon::StoryStep& step); Pokemon::Outcome tap_to_banner(const Pokemon::Pose& from, const Pokemon::StoryStep& step); bool through_already(const Pokemon::StoryStep& step); + WarpSeen door_from_beside(const Pokemon::StoryStep& step, Milliseconds timeout, const std::string& banner); void turn(Pokemon::Direction direction); void log(const std::string& text); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp index b4a2245277..8716f0e795 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp @@ -79,13 +79,20 @@ const char* LAST_ROW = "01.11"; // Sweeps the program fails today, by test name, with the likely fix. const std::map KNOWN_FAILING{ {"PokemonBDSP::AutoStory - Fault sweep: 00.01, scene end pose", - "the walk after barry_runs_to_the_lake trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, - {"PokemonBDSP::AutoStory - Fault sweep: 00.03, scene end pose", - "the walk after rowan_and_dawn trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, + "the walk after barry_runs_to_the_lake trusts the table's pose: measure it or clip to a wall first"}, {"PokemonBDSP::AutoStory - Fault sweep: 00.04, scene end pose", - "the walk after mom_heals_us, moms_hat trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, + "the walk after mom_heals_us, moms_hat trusts the table's pose: measure it or clip to a wall first"}, {"PokemonBDSP::AutoStory - Fault sweep: 01.05, scene end pose", - "the walk after barry_bumps_into_us trusts the table's pose: measure it or clip to a wall first, as 00.03's which_row"}, + "the walk after barry_bumps_into_us trusts the table's pose: measure it or clip to a wall first"}, +}; + +// Scenes whose end the console has proven, by step name: the sweep leaves +// them out, as the tiles next to it are not where the game leaves us. +const std::map PROVEN_SCENE_ENDS{ + // Mom's Running Shoes scene: (6, 8) facing east in 7 of 7 runs stopped + // right after it (lab-B 2026-11-09). The rows 7, 9 and 10 seen before + // were our input landing in its closing fade, now waited out. + {"rowan_and_dawn", "lab-B 2026-11-09, 7 of 7 runs on (6, 8)"}, }; // Runs row `row` with `knobs`: "" if it passes, else where and why it stopped. @@ -233,7 +240,8 @@ UnitTestResult sweep_scene_end_pose(Logger& logger, const StoryCheckpoint& row){ size_t variants = 0; for (size_t c = 0; c < row.steps.size(); c++){ const StoryStep& step = row.steps[c]; - if (!game_sets_end(step.kind) || !step.pose_after || already_there(logger, row, c, *step.pose_after)){ + if (!game_sets_end(step.kind) || !step.pose_after || PROVEN_SCENE_ENDS.contains(step.name) || + already_there(logger, row, c, *step.pose_after)){ continue; } for (const TilePos& tile : walkable_neighbors(*step.pose_after)){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp index 909327b5fa..bdfaf2a847 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -328,13 +328,13 @@ UnitTestResult starly_opening_after_the_starter(Logger& logger){ return passes(run_case(logger, "00.02", "00.02", {.fade = {}, .banner = {}}, knobs)); } -// 00.03: Rowan's scene ends at home beside Mom, on the rug's row (r24, -// r27, r28) or a row lower (lab-B 2026-11-09 12:49: the walk west to the -// table's corner stopped on (5, 9) against the wall (4, 9), and the taps -// after crossed the door's mat to (7, 10)). The way out goes from each. +// 00.03: Rowan's scene ends at home on (6, 8) beside Mom (lab-B +// 2026-11-09, 7 of 7 runs). The way out holds south onto the door's tile +// (6, 10); from a column west, (5, 8), the hold stops on (5, 10) with no +// fade, and a tap east onto the mat goes out. UnitTestResult home_from_each_scene_end(Logger& logger){ std::string failures; - for (const TilePos& tile : {TilePos{5, 8}, TilePos{6, 8}, TilePos{5, 9}, TilePos{6, 9}}){ + for (const TilePos& tile : {TilePos{6, 8}, TilePos{5, 8}}){ SimWorldKnobs knobs; knobs.lands["rowan_and_dawn"] = Pokemon::tile_pose("PlayerHouse1F", {tile}, Direction::EAST); const std::string stopped = run_case(logger, "00.03", "00.03", {.fade = {}, .banner = {}}, std::move(knobs)); @@ -457,7 +457,7 @@ const FailureCase AUTO_STORY_FAILURE_CASES[] = { {.input = {"01.07 after the tag battle the grunts run off before anyone speaks", grunts_run_off_before_rowan}, .expectation = {}}, {.input = {"00.03 Rowan's scene opens with no box and fades home", rowans_scene_opens_with_no_box}, .expectation = {}}, {.input = {"00.02 the Starly battle's opening still plays after the starter (lab-B 2026-11-09)", starly_opening_after_the_starter}, .expectation = {}}, - {.input = {"00.03 out of the house from each tile Rowan's scene ends on, rows 8 and 9 (lab-B 2026-11-09)", home_from_each_scene_end}, .expectation = {}}, + {.input = {"00.03 out of the house from (6, 8), where Rowan's scene ends, and from a column west", home_from_each_scene_end}, .expectation = {}}, {.input = {"00.03 Rowan's scene starts on each of the trigger's rows 14..16, and the walk stops there", rowans_scene_on_each_row}, .expectation = {}}, }; From 9bea71fc344bba725f0915b37fd74312d8772e5c Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 15:05:29 -0800 Subject: [PATCH 096/166] BDSP AutoStory: keep the door step under the function limit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 26 ++++++++++--------- .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 2 +- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index 43c3b1b703..f59b1e15f2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -243,12 +243,16 @@ Outcome StoryWalkSteps::tap_to_banner(const Pose& from, const StoryStep& step){ return Pokemon::outcome_ok(); } -// A STEP "or_legs" whose run into the door saw no fade: the run stopped -// beside the door's column, against the wall it is in. The step's legs, a -// tap a tile, put us on the door's tile, then the run goes again (00.03: -// from (5, 10) east onto the mat (6, 10), then south). A tap onto the -// tile that is itself the way through ends it. -WarpSeen StoryWalkSteps::door_from_beside(const StoryStep& step, Milliseconds timeout, const std::string& banner){ +// A STEP "or_legs" whose run into the door saw nothing (`seen`): the run +// stopped beside the door's column, against the wall it is in. The step's +// legs, a tap a tile, put us on the door's tile, then the run goes again +// (00.03: from (5, 10) east onto the mat (6, 10), then south). A tap onto +// the tile that is itself the way through ends it. `seen` itself for +// another variant, or when the run saw the warp. +WarpSeen StoryWalkSteps::door_from_beside(const StoryStep& step, const WarpSeen& seen, Milliseconds timeout, const std::string& banner){ + if (seen.any() || step.variant != "or_legs"){ + return seen; + } for (const Pokemon::StoryLeg& leg : step.legs){ turn(leg.direction); const WalkResult walk = m_io.route().walk_taps(leg.direction, (size_t)leg.tiles, step.name); @@ -258,10 +262,10 @@ WarpSeen StoryWalkSteps::door_from_beside(const StoryStep& step, Milliseconds ti return walk.warp; } } - const WarpSeen seen = m_io.run_into_door(step.direction, m_can_run, timeout, Milliseconds(0), banner); + const WarpSeen again = m_io.run_into_door(step.direction, m_can_run, timeout, Milliseconds(0), banner); log(std::format("[{}] {}: {} through the door again: {}.", m_row, step.name, - direction_name(step.direction), seen.any() ? describe(seen) : "nothing yet")); - return seen; + direction_name(step.direction), again.any() ? describe(again) : "nothing yet")); + return again; } // The route before ran on through this step's warp (walk_route_to_warp()): @@ -526,9 +530,7 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ WarpSeen seen = m_io.run_into_door(step.direction, m_can_run, door.timeout, door.dark_from, banner); log(std::format("[{}] {}: {} through the door (timeout {} ms, dark from {} ms): {}.", m_row, step.name, direction_name(step.direction), door.timeout.count(), door.dark_from.count(), seen.any() ? describe(seen) : "nothing yet")); - if (!seen.any() && step.variant == "or_legs"){ - seen = door_from_beside(step, door.timeout, banner); - } + seen = door_from_beside(step, seen, door.timeout, banner); m_io.settle(BUTTON_B, label_of(step), !seen.any(), banner); return Pokemon::outcome_ok(); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index 2542c861aa..52fa17224d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -93,7 +93,7 @@ class StoryWalkSteps{ Pokemon::Outcome leg_to_map(const Pokemon::StoryStep& step); Pokemon::Outcome tap_to_banner(const Pokemon::Pose& from, const Pokemon::StoryStep& step); bool through_already(const Pokemon::StoryStep& step); - WarpSeen door_from_beside(const Pokemon::StoryStep& step, Milliseconds timeout, const std::string& banner); + WarpSeen door_from_beside(const Pokemon::StoryStep& step, const WarpSeen& seen, Milliseconds timeout, const std::string& banner); void turn(Pokemon::Direction direction); void log(const std::string& text); From a6e1e0b0d6547e29db115d42156f66e7a83999dd Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 15:08:50 -0800 Subject: [PATCH 097/166] BDSP AutoStory sim: a fade looks like BDSP's eyes see it; Mom's closing fade BDSP's overworld detector reads a black frame as no box, and black stays still, so the sim's fade beat now shows the overworld, still, with the fade. A new console-failure case plays Mom's scene ending in a closing fade (lab-B 2026-11-09 14:33): under the old TalkOver it was judged over 12.8 s in, inside the fade (red, checked); now it ends once the fade is back up and the overworld has been quiet since. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 19 +++++++++++++++++++ .../PokemonBDSP_AutoStory_StorySim.cpp | 2 +- .../PokemonBDSP_AutoStory_StorySim.h | 3 ++- 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp index bdfaf2a847..3cf6e812fe 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -317,6 +317,24 @@ UnitTestResult rowans_scene_opens_with_no_box(Logger& logger){ return passes(run_case(logger, "00.03", "00.03", {.fade = {}, .banner = {}}, knobs)); } +// 00.03: Mom's lines, a still moment, then the scene's closing fade +// (lab-B 2026-11-09 14:33). The scene once ended as the fade went down, +// and the next step's input landed in it: the talk-over must wait for the +// fade to come back up and for the quiet after it. +UnitTestResult moms_scene_ends_with_a_fade(Logger& logger){ + SimWorldKnobs knobs; + knobs.scenes["rowan_and_dawn"] = { + sim_line("Dawn"), + sim_line("Barry"), + sim_fade("the fade home", 1500ms), + sim_line("Mom: the Running Shoes"), + sim_line("Mom"), + sim_pause("Mom stands", 4000ms, false), + sim_fade("the scene's closing fade", 2000ms), + }; + return passes(run_case(logger, "00.03", "00.03", {.fade = {}, .banner = {}}, knobs)); +} + // 00.02: the Starly battle's opening is still playing when the battle // step starts, right after choose_starter (lab-B 2026-11-09 run 3, event // 7): the battle step's, not interrupt_unsettled before it. @@ -456,6 +474,7 @@ const FailureCase AUTO_STORY_FAILURE_CASES[] = { {.input = {"01.04 Roark's badge speech: the fanfare's pause, then a scene", roark_badge_speech}, .expectation = {}}, {.input = {"01.07 after the tag battle the grunts run off before anyone speaks", grunts_run_off_before_rowan}, .expectation = {}}, {.input = {"00.03 Rowan's scene opens with no box and fades home", rowans_scene_opens_with_no_box}, .expectation = {}}, + {.input = {"00.03 Mom's scene ends with a closing fade: over once it is back up (lab-B 2026-11-09)", moms_scene_ends_with_a_fade}, .expectation = {}}, {.input = {"00.02 the Starly battle's opening still plays after the starter (lab-B 2026-11-09)", starly_opening_after_the_starter}, .expectation = {}}, {.input = {"00.03 out of the house from (6, 8), where Rowan's scene ends, and from a column west", home_from_each_scene_end}, .expectation = {}}, {.input = {"00.03 Rowan's scene starts on each of the trigger's rows 14..16, and the walk stops there", rowans_scene_on_each_row}, .expectation = {}}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index 36e7499a3d..2f09a50379 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -72,7 +72,7 @@ SimBeat sim_pause(std::string what, Milliseconds length, bool moving){ return {.what = std::move(what), .length = length, .moving = moving}; } SimBeat sim_fade(std::string what, Milliseconds length, WarpFade fade){ - return {.what = std::move(what), .length = length, .overworld = false, .fade = fade}; + return {.what = std::move(what), .length = length, .overworld = true, .moving = false, .fade = fade}; } std::string play_scene(const SimScene& scene, const TalkOverRule& rule){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index 0f18be3e9d..64de628226 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -115,7 +115,8 @@ struct SimBeat{ SimBeat sim_line(std::string what); // `length` of overworld with no box, someone moving or not. SimBeat sim_pause(std::string what, Milliseconds length, bool moving); -// `length` of a fade, not the overworld. +// `length` of a fade, as BDSP's eyes see it: no box, so the overworld, +// and still (a black frame matches the one before). SimBeat sim_fade(std::string what, Milliseconds length, WarpFade fade = WarpFade::BLACK); // A talk or a scene as the screen shows it, beat by beat; the quiet // overworld after the last beat. From ec6c089c29d05ceb137ea1b88bf6cdc68813eb9a Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 15:24:40 -0800 Subject: [PATCH 098/166] BDSP AutoStory: route, then run into a scene until its dialogue A ROUTE step with a leg now walks its planned route, then holds on toward the leg's direction until a dialogue starts, for the leg's tiles at most; a wild battle on the way is run from and the run goes on, and no dialogue fails the step as no_dialogue. It replaces the LEGS "to_dialogue" taps. 00.03 uses it twice: to_the_lakefront_wall + into_rowans_scene become into_rowans_scene, and short_of_dawn + into_sandgem become into_dawns_scene. Sim tests: Rowan's trigger from each start, Dawn's trigger mid-run in the story sim, and on the grid sim Dawn's scene with and without a wild battle, and the cap failing cleanly with no scene. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Data/route_plans.golden.txt | 4 +- .../PokemonBDSP_AutoStory_StoryTable.cpp | 25 ++-- ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 2 +- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 39 +++--- .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 4 +- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 115 ++++++++++++++++++ ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 46 +++++-- 7 files changed, 195 insertions(+), 40 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt index 5cf5b09f51..4fc70f03fd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt @@ -63,14 +63,14 @@ anchor); 0 from one start tile. target: VerityLakefront (17, 14) facing north (tile) not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends) -== 00.03 to_the_lakefront_wall (costs: route) +== 00.03 into_rowans_scene (costs: route) from: VerityLakefront (17, 14) (17, 15) (set) target: VerityLakefront (17, 21) (tile) start candidates: Verity Lakefront (17, 14), Verity Lakefront (17, 15) 1. south 7 (to wall) -> Verity Lakefront (17, 21) totals: 1 legs, 0 turns, 0 open, 1 localization -== 00.03 short_of_dawn (costs: route) +== 00.03 into_dawns_scene (costs: route) from: TwinleafTown (20, 22) facing south (tile) target: Route201 (63, 5) facing east (tile) start candidates: Twinleaf Town (20, 22) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 687cd309ca..37502cd312 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -129,6 +129,15 @@ StoryStep route(std::string name, Pose target, std::string why, std::string cost step.variant = std::move(costs); return step; } +// The route to `target`, then a run on toward `run.direction` until a +// dialogue starts, wherever on the run it starts: a scene's trigger tile. +// No dialogue in `run.tiles` tiles fails the step. The scene is the next +// step's. +StoryStep route_into_scene(std::string name, Pose target, StoryLeg run, std::string why, std::string costs = ""){ + StoryStep step = route(std::move(name), std::move(target), std::move(why), std::move(costs)); + step.legs = {run}; + return step; +} StoryStep legs(std::string name, std::vector legs, std::string why, std::string variant = ""){ StoryStep step = make(StoryStepKind::LEGS, std::move(name), std::move(why)); step.legs = std::move(legs); @@ -336,9 +345,10 @@ std::vector lake_and_pokedex(){ "Rowan's lines and the walk out of the lake"), }), row("00.03", "Back to Sandgem: Rowan, Dawn and the Pokedex", at_or_next_to(LAKEFRONT, "below_lake_entrance", SOUTH), { - // The wall's row 21 runs on as Route 201's 14, through Rowan's trigger (5, 14..16). - route("to_the_lakefront_wall", at(LAKEFRONT, 17, 21), "south to the Lakefront's wall, the row into Rowan's trigger"), - legs("into_rowans_scene", {{.direction = EAST, .tiles = 22}}, "east onto Route 201 until Rowan's scene starts: 20 tiles, 22 at most", "to_dialogue"), + // The wall's row 21 runs on as Route 201's 14, through Rowan's trigger + // (5, 14..16): 20 tiles east of the wall. + route_into_scene("into_rowans_scene", at(LAKEFRONT, 17, 21), {.direction = EAST, .tiles = 22}, + "south to the Lakefront's wall, then east onto Route 201 until Rowan's scene starts: 20 tiles, 22 at most"), // BDSP, unlike Diamond: after Rowan leaves, Dawn's and Barry's lines, then // the game fades to the house, where Mom gives the Running Shoes. The // scene ends on (6, 8) facing her, east: 7 of 7 console runs stopped @@ -350,10 +360,11 @@ std::vector lake_and_pokedex(){ "Rowan and Dawn come back; Barry, then home for the Running Shoes"), out_of_the_house_again(), // Through the grass now, with a starter: wild battles are run from. - route("short_of_dawn", at(ROUTE_201, 63, 5, EAST), "Twinleaf, then east along Route 201 to its east edge"), - // Dawn's scene starts as we come into Sandgem (trigger (4, 10..15)); - // walk until it does rather than to a tile (r35, r36). - legs("into_sandgem", {{.direction = EAST, .tiles = 8}}, "east into Sandgem until Dawn's scene starts", "to_dialogue"), + // Dawn's scene starts as we come into Sandgem (trigger (4, 10..15), + // 5 tiles past Route 201's edge (63, 5) = Sandgem (-1, 12)): run until + // it does rather than to a tile (r35, r36). + route_into_scene("into_dawns_scene", at(ROUTE_201, 63, 5, EAST), {.direction = EAST, .tiles = 8}, + "Twinleaf, then east along Route 201 to its edge and on into Sandgem until Dawn's scene starts"), // Butters' sequence pressed B through Dawn's and Rowan's lines and // the nickname question (No), then A for the Pokedex. The scene's // B answers No too, and closes an item's lines as it did Barry's diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index dd378da285..c35f269f68 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -46,7 +46,7 @@ using Pokemon::TilePos; const std::map>& built_in_variants(){ static const std::map> variants{ {StoryStepKind::ROUTE, {"", "town", "robust", "line"}}, - {StoryStepKind::LEGS, {"", "one_short_ok", "to_wall", "counted_wall", "measured", "to_dialogue", "to_map"}}, + {StoryStepKind::LEGS, {"", "one_short_ok", "to_wall", "counted_wall", "measured", "to_map"}}, {StoryStepKind::STEP, {"", "to_banner", "tap", "or_legs"}}, {StoryStepKind::MASH, {"", "a"}}, {StoryStepKind::BATTLE, {"", "doubles", "starter"}}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index f59b1e15f2..e97e77cdde 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -155,29 +155,37 @@ Outcome StoryWalkSteps::route(RunState& state, const StoryStep& step){ if (Pokemon::tiles_of(state.pose).empty()){ return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); } - return Pokemon::outcome_ok(walk_to(state.pose, *step.target, step)); + const Pose end = walk_to(state.pose, *step.target, step); + if (step.legs.empty()){ + return Pokemon::outcome_ok(end); + } + return run_to_dialogue(step); } -// A LEGS step "to_dialogue": taps its one leg until a dialogue starts on the -// way, wherever it starts (Dawn's at Sandgem's edge, r35/r36: an exact tile -// and banner raced her scene). The scene's lines are the next step's. -Outcome StoryWalkSteps::leg_to_dialogue(const StoryStep& step){ +// The run of a ROUTE step with a leg, after its route: on toward the leg's +// direction until a dialogue starts, wherever on the run it starts (a +// scene's trigger: r35/r36 raced Dawn's to an exact tile and banner), for +// the leg's tiles at most. A wild battle on the way is run from and the run +// goes on. No dialogue fails the step. The scene's lines are the next step's. +Outcome StoryWalkSteps::run_to_dialogue(const StoryStep& step){ const Pokemon::StoryLeg& leg = step.legs.front(); - turn(leg.direction); - const WalkResult walk = m_io.route().walk_taps(leg.direction, (size_t)leg.tiles, step.name); - if (walk.wild_battles > 0){ - return Pokemon::outcome_failed("interrupted_dialogue_approach", step.name); - } - log(std::format("[{}] {}: taps {} to a dialogue: {} tiles, {}.", m_row, step.name, direction_name(leg.direction), walk.moved_chunks, walk_stop_name(walk.stop))); + const MoveSpeed speed = m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK; + const WalkResult walk = m_io.route().walk_to_wall({ + .direction = leg.direction, + .limit = ROUTE_START_DELAY + route_ms_per_tile(leg.direction, speed) * leg.tiles, + .label = label_of(step), + .options = {.arrived = nullptr, .pace = m_can_run ? DpadPace::RUN : DpadPace::WALK}, + }); + log(std::format("[{}] {}: ran {} to a dialogue: {} tiles of {} at most, {}, {} wild battle(s).", m_row, step.name, + direction_name(leg.direction), walk.moved_chunks, leg.tiles, walk_stop_name(walk.stop), walk.wild_battles)); if (walk.stop == WalkStop::DIALOG){ return Pokemon::outcome_ok(); } - // A scene can lock us before its first line: Dawn walks over first (r37), - // or Mom walks over to us on the mat (r7). + // A scene can lock us before its first line: Dawn walks over first (r37). if (m_io.route().dialog_within(10000ms, COLOR_CYAN)){ return Pokemon::outcome_ok(); } - return Pokemon::outcome_failed("no_dialogue", step.name); + return Pokemon::outcome_failed("no_dialogue", std::format("{}: no dialogue in {} tiles {}", step.name, leg.tiles, direction_name(leg.direction))); } // A LEGS step "to_map": runs its one leg until the location banner of @@ -485,9 +493,6 @@ Outcome StoryWalkSteps::legs(RunState& state, const StoryStep& step){ } return Pokemon::outcome_ok(); } - if (step.variant == "to_dialogue"){ - return leg_to_dialogue(step); - } if (step.variant == "to_map"){ return leg_to_map(step); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index 52fa17224d..eb9cb277cb 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -68,6 +68,8 @@ class StoryWalkSteps{ } // Walks the planned route to `step.target`. Variant: the plan's costs. + // With a leg, then runs on toward its direction until a dialogue starts, + // for its tiles at most (run_to_dialogue()). Pokemon::Outcome route(Pokemon::RunState& state, const Pokemon::StoryStep& step); // See StoryExecutor::legs(). Pokemon::Outcome legs(Pokemon::RunState& state, const Pokemon::StoryStep& step); @@ -89,7 +91,7 @@ class StoryWalkSteps{ Pokemon::Outcome tap_legs(const Pokemon::Pose& from, const Pokemon::StoryStep& step); Pokemon::Outcome counted_wall(const Pokemon::Pose& from, const Pokemon::StoryStep& step); Pokemon::Outcome measured_legs(const Pokemon::Pose& from, const Pokemon::StoryStep& step); - Pokemon::Outcome leg_to_dialogue(const Pokemon::StoryStep& step); + Pokemon::Outcome run_to_dialogue(const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_map(const Pokemon::StoryStep& step); Pokemon::Outcome tap_to_banner(const Pokemon::Pose& from, const Pokemon::StoryStep& step); bool through_already(const Pokemon::StoryStep& step); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 30b7c55788..b9696c5533 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -23,6 +23,7 @@ #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" #include "PokemonBDSP_AutoStory_GridSim.h" #include "PokemonBDSP_AutoStory_OldStorySteps.h" +#include "PokemonBDSP_AutoStory_StorySim.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" @@ -884,6 +885,116 @@ UnitTestResult test_oreburgh_mine_hall_corridor(Logger& logger){ return err.empty() ? UnitTestResult(true) : UnitTestResult(err); } +// Dawn's scene on the south world, in its tiles: the coord events of +// Sandgem that 00.03 arms (its trigger column (4, 10..15), decomp). +std::vector dawns_triggers(const StoryWorld& world){ + std::vector out; + for (const RowTrigger& armed : story_triggers()){ + if (armed.row != "00.03" || armed.map != "SandgemTown"){ + continue; + } + SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; + for (const TilePos& pos : armed.trigger.tiles){ + trigger.tiles.push_back(story_to_world(world, armed.map, pos)); + } + out.push_back(std::move(trigger)); + } + return out; +} + +// How 00.03's into_dawns_scene went on the grid simulation: its outcome, +// where it left the player, how many tiles east of the route's end, whether +// a dialogue is open, whether a wild battle was run from, and the failure +// the program would have stopped on instead of failing the step. +struct SceneRun{ + Pokemon::Outcome outcome; + TilePos end; + int run_tiles = 0; + bool dialog = false; + bool ran_from_battle = false; + std::string program_failure; +}; +// 00.03's into_dawns_scene from where the table has the player before it, +// at the run's pace (the shoes are 00.03's): the route to Route 201's east +// edge, then the run east into Sandgem. With `dawn`, Dawn's scene is armed; +// with `battle`, a wild battle interrupts the run. +SceneRun run_into_dawns_scene(bool dawn, bool battle){ + const std::optional table = table_steps("00.03", "into_dawns_scene", "rowan_gives_pokedex"); + if (!table || table->steps.size() != 1 || !table->steps.front().target){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "00.03 has no ROUTE into_dawns_scene right before rowan_gives_pokedex."); + } + const StoryStep& step = table->steps.front(); + const StoryWorld& world = *story_plan_world(table->start.map, step.target->map); + SimWorld sim_world{.world = &world, .trainers = story_trainers(world), .can_run = true}; + if (dawn){ + sim_world.triggers = dawns_triggers(world); + } + GridSim sim(sim_world, story_to_world(world, table->start.map, Pokemon::tiles_of(table->start).front()), Direction::SOUTH, true); + std::vector notes; + std::vector encounters; + if (battle){ + encounters.push_back({.label = "into dawns scene", .direction = Direction::EAST, .battle = {}}); + } + GridSimRouteIO route_io(sim, notes, {}, std::move(encounters)); + WalkStepsIO io(sim, route_io); + StoryWalkSteps walk(io); + // A row after the shoes' row runs, as 00.03 does once Mom gave them. + walk.begin_attempt("00.04"); + Pokemon::RunState state{.pose = table->start, .flags = {}}; + SceneRun out; + try{ + out.outcome = walk.route(state, step); + }catch (const GridSimFailure& e){ + out.program_failure = e.message; + } + out.end = nearest_tile(sim.player().pos); + out.run_tiles = out.end.x - story_to_world(world, step.target->map, Pokemon::tiles_of(*step.target).front()).x; + out.dialog = sim.player().dialog; + out.ran_from_battle = std::find(notes.begin(), notes.end(), "[Sim] into dawns scene: wild battle run from.") != notes.end(); + return out; +} + +// 00.03, Route 201 to Sandgem: the route to the edge, then a run east that +// Dawn's scene stops wherever on the run it starts, a wild battle on the +// way or not. With no scene, the run stops at its cap and the step fails +// as "no_dialogue", not the program. +UnitTestResult test_run_into_dawns_scene(Logger& logger){ + struct SceneCase{ + const char* name; + bool dawn; + bool battle; + }; + const SceneCase cases[] = { + {"Dawn's scene mid-run", true, false}, + {"Dawn's scene after a wild battle on the run", true, true}, + {"no scene", false, false}, + {"a wild battle and no scene", false, true}, + }; + const StoryWorld& world = *story_plan_world("Route201", "SandgemTown"); + std::string failures; + for (const SceneCase& item : cases){ + const SceneRun run = run_into_dawns_scene(item.dawn, item.battle); + const std::optional sandgem = story_to_local(world, "SandgemTown", run.end); + logger.log(std::format("{}: {}, ended {} tiles on at {}.", item.name, + !run.program_failure.empty() ? "program failure: " + run.program_failure + : run.outcome.succeeded() ? std::string("done") : Pokemon::to_string(run.outcome), + run.run_tiles, describe(world, run.end))); + if (!run.program_failure.empty()){ + failures += std::format("\n{}: the program failed instead of the step: {}", item.name, run.program_failure); + }else if (item.dawn && (!run.outcome.succeeded() || !run.dialog || !sandgem || sandgem->x != 4)){ + failures += std::format("\n{}: {}, ended at {}, not in Dawn's scene on Sandgem's column 4.", item.name, + Pokemon::to_string(run.outcome), describe(world, run.end)); + }else if (!item.dawn && run.outcome.failure != "no_dialogue"){ + failures += std::format("\n{}: expected the step to fail as no_dialogue; {}.", item.name, Pokemon::to_string(run.outcome)); + }else if (item.battle != run.ran_from_battle){ + failures += std::format("\n{}: expected {} wild battle on the run.", item.name, item.battle ? "a" : "no"); + }else if (run.run_tiles < 0 || run.run_tiles > 8){ + failures += std::format("\n{}: the run went {} tiles past the route's end, outside its cap of 8.", item.name, run.run_tiles); + } + } + return failures.empty() ? UnitTestResult(true) : UnitTestResult(failures); +} + struct AutoStoryGridSimInput{ std::string name; std::function body; @@ -971,6 +1082,10 @@ const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { .input = {"01.11, the old woman from each tile Floaroma's banner stops us on (lab-B, 2026-11-08)", test_old_couple_from_each_arrival}, .expectation = {}, }, + { + .input = {"00.03, the run into Sandgem stops in Dawn's scene, or fails at its cap with no scene", test_run_into_dawns_scene}, + .expectation = {}, + }, }; void add_tests_AutoStory_GridSim(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp index 3cf6e812fe..5eb9b7b3f8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -25,6 +25,7 @@ #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" @@ -374,28 +375,48 @@ std::vector table_with_row(const std::string& id, const Pose& s } return rows; } -// 00.03: Rowan's trigger is the column (5, 14..16) on Route 201 (decomp). -// The walk east from the Lakefront's wall runs along Route 201's row 14, -// or a row or two lower if the hold south stopped short of the wall. Each -// of the three rows starts the scene, and the walk stops on its tile. -// The Lakefront's rows 21..23 are Route 201's 14..16. -UnitTestResult rowans_scene_on_each_row(Logger& logger){ +// 00.03: Rowan's trigger is the column (5, 14..16) on Route 201 (decomp), +// 20 tiles east of the Lakefront's wall row 21 (Route 201's row 14). The +// step routes from where the lake's scene leaves us, or from a row or two +// lower (21..23), onto that row, then runs east until his scene stops the +// run on a tile of the column. +UnitTestResult rowans_scene_from_each_start(Logger& logger){ const StoryStep& walk = table_step("00.03", "into_rowans_scene"); + const Pose trigger = Pokemon::tile_pose("Route201", {TilePos{5, 14}, TilePos{5, 15}, TilePos{5, 16}}, Direction::EAST); std::string failures; - for (int row = 14; row <= 16; row++){ - const Pose start = Pokemon::tile_pose("VerityLakefront", {TilePos{20, row + 7}}, Direction::EAST); + for (const TilePos& tile : {TilePos{17, 14}, TilePos{17, 15}, TilePos{20, 21}, TilePos{20, 22}, TilePos{20, 23}}){ + const Pose start = Pokemon::tile_pose("VerityLakefront", {tile}, Direction::SOUTH); const std::vector rows = table_with_row("00.03", start, walk); SimExecutor executor(logger, {.fade = {}, .banner = {}}, {}); const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = "00.03", .to = "00.03"}, rows); - const Pose trigger = Pokemon::tile_pose("Route201", {TilePos{5, row}}, Direction::EAST); if (!report.completed){ - failures += std::format("\nrow {}: stopped in {}: {}", row, executor.result().failed_step, executor.result().error); + failures += std::format("\nfrom ({}, {}): stopped in {}: {}", tile.x, tile.y, executor.result().failed_step, executor.result().error); }else if (!ends_on(executor.result(), trigger)){ - failures += std::format("\nrow {}: the walk ended at {}, not on (5, {})", row, end_of(executor.result()), row); + failures += std::format("\nfrom ({}, {}): the walk ended at {}, not on Rowan's trigger", tile.x, tile.y, end_of(executor.result())); } } return passes(failures); } +// 00.03: Dawn's scene starts on Sandgem's column 4 (rows 10..15, decomp), +// five tiles into the run east from Route 201's edge (Sandgem (-1, 12) is +// Route 201 (63, 5)). From the house's doorstep, the step routes to the +// edge and runs on until her scene stops it there (r35, r36: an exact +// tile and banner raced her scene). +UnitTestResult dawns_scene_mid_run(Logger& logger){ + const StoryStep& walk = table_step("00.03", "into_dawns_scene"); + const Pose start = Pokemon::tile_pose("TwinleafTown", {map_point("TwinleafTown", "house_doorstep")}, Direction::SOUTH); + const std::vector rows = table_with_row("00.03", start, walk); + SimExecutor executor(logger, {.fade = {}, .banner = {}}, {}); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = "00.03", .to = "00.03"}, rows); + if (!report.completed){ + return std::format("stopped in {}: {}", executor.result().failed_step, executor.result().error); + } + const Pose trigger = Pokemon::tile_pose("SandgemTown", {TilePos{4, 12}}, Direction::EAST); + if (!ends_on(executor.result(), trigger)){ + return std::format("the walk ended at {}, not on Dawn's trigger (4, 12).", end_of(executor.result())); + } + return true; +} struct FailureCaseInput{ std::string name; @@ -477,7 +498,8 @@ const FailureCase AUTO_STORY_FAILURE_CASES[] = { {.input = {"00.03 Mom's scene ends with a closing fade: over once it is back up (lab-B 2026-11-09)", moms_scene_ends_with_a_fade}, .expectation = {}}, {.input = {"00.02 the Starly battle's opening still plays after the starter (lab-B 2026-11-09)", starly_opening_after_the_starter}, .expectation = {}}, {.input = {"00.03 out of the house from (6, 8), where Rowan's scene ends, and from a column west", home_from_each_scene_end}, .expectation = {}}, - {.input = {"00.03 Rowan's scene starts on each of the trigger's rows 14..16, and the walk stops there", rowans_scene_on_each_row}, .expectation = {}}, + {.input = {"00.03 the walk into Rowan's scene routes onto his row and stops on his trigger mid-run", rowans_scene_from_each_start}, .expectation = {}}, + {.input = {"00.03 the walk into Sandgem stops on Dawn's trigger mid-run", dawns_scene_mid_run}, .expectation = {}}, }; void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database){ From 69e18b53cb7599459d34f683fc545a98f96b5d63 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 15:27:55 -0800 Subject: [PATCH 099/166] BDSP AutoStory sim: the run into Sandgem's cases as their own tests Moved from GridSim_Tests (over its 1000 lines) beside the wall-leg battle cases, one test a case, with an options struct for the case's knobs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_GridSim_Tests.cpp | 115 ---------- ...emonBDSP_AutoStory_WallBattleSim_Tests.cpp | 202 +++++++++++++++++- ...okemonBDSP_AutoStory_WallBattleSim_Tests.h | 2 + 3 files changed, 203 insertions(+), 116 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index b9696c5533..30b7c55788 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -23,7 +23,6 @@ #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" #include "PokemonBDSP_AutoStory_GridSim.h" #include "PokemonBDSP_AutoStory_OldStorySteps.h" -#include "PokemonBDSP_AutoStory_StorySim.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" @@ -885,116 +884,6 @@ UnitTestResult test_oreburgh_mine_hall_corridor(Logger& logger){ return err.empty() ? UnitTestResult(true) : UnitTestResult(err); } -// Dawn's scene on the south world, in its tiles: the coord events of -// Sandgem that 00.03 arms (its trigger column (4, 10..15), decomp). -std::vector dawns_triggers(const StoryWorld& world){ - std::vector out; - for (const RowTrigger& armed : story_triggers()){ - if (armed.row != "00.03" || armed.map != "SandgemTown"){ - continue; - } - SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; - for (const TilePos& pos : armed.trigger.tiles){ - trigger.tiles.push_back(story_to_world(world, armed.map, pos)); - } - out.push_back(std::move(trigger)); - } - return out; -} - -// How 00.03's into_dawns_scene went on the grid simulation: its outcome, -// where it left the player, how many tiles east of the route's end, whether -// a dialogue is open, whether a wild battle was run from, and the failure -// the program would have stopped on instead of failing the step. -struct SceneRun{ - Pokemon::Outcome outcome; - TilePos end; - int run_tiles = 0; - bool dialog = false; - bool ran_from_battle = false; - std::string program_failure; -}; -// 00.03's into_dawns_scene from where the table has the player before it, -// at the run's pace (the shoes are 00.03's): the route to Route 201's east -// edge, then the run east into Sandgem. With `dawn`, Dawn's scene is armed; -// with `battle`, a wild battle interrupts the run. -SceneRun run_into_dawns_scene(bool dawn, bool battle){ - const std::optional table = table_steps("00.03", "into_dawns_scene", "rowan_gives_pokedex"); - if (!table || table->steps.size() != 1 || !table->steps.front().target){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "00.03 has no ROUTE into_dawns_scene right before rowan_gives_pokedex."); - } - const StoryStep& step = table->steps.front(); - const StoryWorld& world = *story_plan_world(table->start.map, step.target->map); - SimWorld sim_world{.world = &world, .trainers = story_trainers(world), .can_run = true}; - if (dawn){ - sim_world.triggers = dawns_triggers(world); - } - GridSim sim(sim_world, story_to_world(world, table->start.map, Pokemon::tiles_of(table->start).front()), Direction::SOUTH, true); - std::vector notes; - std::vector encounters; - if (battle){ - encounters.push_back({.label = "into dawns scene", .direction = Direction::EAST, .battle = {}}); - } - GridSimRouteIO route_io(sim, notes, {}, std::move(encounters)); - WalkStepsIO io(sim, route_io); - StoryWalkSteps walk(io); - // A row after the shoes' row runs, as 00.03 does once Mom gave them. - walk.begin_attempt("00.04"); - Pokemon::RunState state{.pose = table->start, .flags = {}}; - SceneRun out; - try{ - out.outcome = walk.route(state, step); - }catch (const GridSimFailure& e){ - out.program_failure = e.message; - } - out.end = nearest_tile(sim.player().pos); - out.run_tiles = out.end.x - story_to_world(world, step.target->map, Pokemon::tiles_of(*step.target).front()).x; - out.dialog = sim.player().dialog; - out.ran_from_battle = std::find(notes.begin(), notes.end(), "[Sim] into dawns scene: wild battle run from.") != notes.end(); - return out; -} - -// 00.03, Route 201 to Sandgem: the route to the edge, then a run east that -// Dawn's scene stops wherever on the run it starts, a wild battle on the -// way or not. With no scene, the run stops at its cap and the step fails -// as "no_dialogue", not the program. -UnitTestResult test_run_into_dawns_scene(Logger& logger){ - struct SceneCase{ - const char* name; - bool dawn; - bool battle; - }; - const SceneCase cases[] = { - {"Dawn's scene mid-run", true, false}, - {"Dawn's scene after a wild battle on the run", true, true}, - {"no scene", false, false}, - {"a wild battle and no scene", false, true}, - }; - const StoryWorld& world = *story_plan_world("Route201", "SandgemTown"); - std::string failures; - for (const SceneCase& item : cases){ - const SceneRun run = run_into_dawns_scene(item.dawn, item.battle); - const std::optional sandgem = story_to_local(world, "SandgemTown", run.end); - logger.log(std::format("{}: {}, ended {} tiles on at {}.", item.name, - !run.program_failure.empty() ? "program failure: " + run.program_failure - : run.outcome.succeeded() ? std::string("done") : Pokemon::to_string(run.outcome), - run.run_tiles, describe(world, run.end))); - if (!run.program_failure.empty()){ - failures += std::format("\n{}: the program failed instead of the step: {}", item.name, run.program_failure); - }else if (item.dawn && (!run.outcome.succeeded() || !run.dialog || !sandgem || sandgem->x != 4)){ - failures += std::format("\n{}: {}, ended at {}, not in Dawn's scene on Sandgem's column 4.", item.name, - Pokemon::to_string(run.outcome), describe(world, run.end)); - }else if (!item.dawn && run.outcome.failure != "no_dialogue"){ - failures += std::format("\n{}: expected the step to fail as no_dialogue; {}.", item.name, Pokemon::to_string(run.outcome)); - }else if (item.battle != run.ran_from_battle){ - failures += std::format("\n{}: expected {} wild battle on the run.", item.name, item.battle ? "a" : "no"); - }else if (run.run_tiles < 0 || run.run_tiles > 8){ - failures += std::format("\n{}: the run went {} tiles past the route's end, outside its cap of 8.", item.name, run.run_tiles); - } - } - return failures.empty() ? UnitTestResult(true) : UnitTestResult(failures); -} - struct AutoStoryGridSimInput{ std::string name; std::function body; @@ -1082,10 +971,6 @@ const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { .input = {"01.11, the old woman from each tile Floaroma's banner stops us on (lab-B, 2026-11-08)", test_old_couple_from_each_arrival}, .expectation = {}, }, - { - .input = {"00.03, the run into Sandgem stops in Dawn's scene, or fails at its cap with no scene", test_run_into_dawns_scene}, - .expectation = {}, - }, }; void add_tests_AutoStory_GridSim(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp index d4bd12f569..6fe4f6a408 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp @@ -4,21 +4,32 @@ * * A wild battle on a leg to a wall, walked by the route walker on the grid * simulation: however the escape ends the battle, the leg must still end at - * the wall with the battle counted. + * the wall with the battle counted. And a run into a scene (00.03's into + * Sandgem), a wild battle on it or not: the scene stops the run wherever it + * starts, and with no scene the run stops at its cap and the step fails. * */ #include #include +#include #include #include #include +#include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" #include "PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_StorySim.h" #include "PokemonBDSP_AutoStory_WallBattleSim_Tests.h" namespace PokemonAutomation{ @@ -29,6 +40,7 @@ namespace PokemonBDSP{ namespace{ using Pokemon::Direction; +using Pokemon::StoryStep; using Pokemon::TilePos; @@ -130,6 +142,191 @@ const WallBattleCase WALL_BATTLE_SIM_CASES[] = { {.input = {.name = "bound: every Run refused", .battle = {.run_refusals = 20}}, .expectation = {.ended = "fought to its end"}}, }; + +// The route walker's IO alone, for a ROUTE step: anything else the step +// asks of the console fails the walk. +class RouteOnlyStepIO : public StoryStepIO{ +public: + explicit RouteOnlyStepIO(GridSimRouteIO& route) + : m_route(route) + {} + + virtual RouteIO& route() override{ + return m_route; + } + virtual void fight(const std::string& trainer) override{ + unsupported("a fight with " + trainer); + } + virtual void walk_until_stopped(Direction, size_t, const std::string& label) override{ + unsupported(label + ": a walk until stopped"); + } + virtual bool run_until_map(Direction, Milliseconds, const std::string& map, const std::string&) override{ + unsupported("a run onto " + map); + return false; + } + virtual WarpSeen run_into_door(Direction, bool, Milliseconds, Milliseconds, const std::string&) override{ + unsupported("a run into a door"); + return {}; + } + virtual std::optional tap_to_banner(Direction, const std::string& map, size_t) override{ + unsupported("taps to " + map + "'s banner"); + return std::nullopt; + } + virtual void settle(Button, const std::string& label, bool, const std::string&) override{ + unsupported(label + "'s settle"); + } + +private: + void unsupported(const std::string& what){ + m_route.note(what + " is not simulated here.", RouteNote::FAILURE); + } + + GridSimRouteIO& m_route; +}; + +// Dawn's scene on `world`, in its tiles: the coord events of Sandgem that +// 00.03 arms (its trigger column (4, 10..15), decomp). +std::vector dawns_triggers(const StoryWorld& world){ + std::vector out; + for (const RowTrigger& armed : story_triggers()){ + if (armed.row != "00.03" || armed.map != "SandgemTown"){ + continue; + } + SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; + for (const TilePos& pos : armed.trigger.tiles){ + trigger.tiles.push_back(story_to_world(world, armed.map, pos)); + } + out.push_back(std::move(trigger)); + } + if (out.empty()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "00.03 arms no coord event in Sandgem."); + } + return out; +} + +// The table's 00.03 into_dawns_scene. +const StoryStep& into_dawns_scene(){ + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const StoryStep& step : checkpoint.steps){ + if (checkpoint.id == "00.03" && step.name == "into_dawns_scene" && step.target && step.legs.size() == 1){ + return step; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "00.03 has no ROUTE into_dawns_scene with a run."); +} + +struct SceneRunInput{ + std::string name; + // Dawn's scene is armed. + bool dawn = false; + // A wild battle interrupts the run. + bool battle = false; +}; +struct SceneRunExpectation{ + // The step ends in Dawn's scene; else it fails as "no_dialogue". + bool in_scene = false; +}; +struct SceneRunCase{ + SceneRunInput input; + SceneRunExpectation expectation; +}; + +// How 00.03's into_dawns_scene went: its outcome, where it left the player, +// how many tiles east of the route's end, whether a dialogue is open, +// whether a wild battle was run from, and the failure the program would +// have stopped on instead of failing the step. +struct SceneRun{ + Pokemon::Outcome outcome; + TilePos end; + int run_tiles = 0; + bool dialog = false; + bool ran_from_battle = false; + std::string program_failure; +}; +// 00.03's into_dawns_scene from the house's doorstep, where the step before +// it leaves us, at the run's pace (Mom gave the shoes in 00.03): the route +// to Route 201's east edge, then the run east into Sandgem. +SceneRun run_into_dawns_scene(const SceneRunInput& input){ + const StoryStep& step = into_dawns_scene(); + const Pokemon::Pose start = Pokemon::tile_pose("TwinleafTown", {map_point("TwinleafTown", "house_doorstep")}, Direction::SOUTH); + const StoryWorld& world = *story_plan_world(start.map, step.target->map); + SimWorld sim_world{.world = &world, .trainers = story_trainers(world), .can_run = true}; + if (input.dawn){ + sim_world.triggers = dawns_triggers(world); + } + GridSim sim(sim_world, story_to_world(world, start.map, Pokemon::tiles_of(start).front()), Direction::SOUTH, true); + std::vector notes; + std::vector encounters; + if (input.battle){ + encounters.push_back({.label = "into dawns scene", .direction = Direction::EAST, .battle = {}}); + } + GridSimRouteIO route_io(sim, notes, {}, std::move(encounters)); + RouteOnlyStepIO io(route_io); + StoryWalkSteps walk(io); + // A row after the shoes' row runs, as 00.03 does once Mom gave them. + walk.begin_attempt("00.04"); + Pokemon::RunState state{.pose = start, .flags = {}}; + SceneRun out; + try{ + out.outcome = walk.route(state, step); + }catch (const GridSimFailure& e){ + out.program_failure = e.message; + } + out.end = nearest_tile(sim.player().pos); + out.run_tiles = out.end.x - story_to_world(world, step.target->map, Pokemon::tiles_of(*step.target).front()).x; + out.dialog = sim.player().dialog; + out.ran_from_battle = std::find(notes.begin(), notes.end(), "[Sim] into dawns scene: wild battle run from.") != notes.end(); + return out; +} + +// Why `run` is not what `test_case` expects, or "". +std::string scene_run_error(const SceneRunCase& test_case, const SceneRun& run){ + const StoryWorld& world = *story_plan_world("Route201", "SandgemTown"); + const std::optional sandgem = story_to_local(world, "SandgemTown", run.end); + const int cap = into_dawns_scene().legs.front().tiles; + if (!run.program_failure.empty()){ + return "the program failed instead of the step: " + run.program_failure; + } + if (test_case.input.battle != run.ran_from_battle){ + return std::format("expected {} wild battle on the run.", test_case.input.battle ? "a" : "no"); + } + if (run.run_tiles < 0 || run.run_tiles > cap){ + return std::format("the run went {} tiles past the route's end, outside its cap of {}.", run.run_tiles, cap); + } + if (test_case.expectation.in_scene && (!run.outcome.succeeded() || !run.dialog || !sandgem || sandgem->x != 4)){ + return std::format("\"{}\", ended at {}, not in Dawn's scene on Sandgem's column 4.", Pokemon::to_string(run.outcome), describe(world, run.end)); + } + if (!test_case.expectation.in_scene && run.outcome.failure != "no_dialogue"){ + return std::format("expected the step to fail as no_dialogue; \"{}\".", Pokemon::to_string(run.outcome)); + } + return ""; +} + +class Test_SceneRunSim : public UnitTest{ +public: + explicit Test_SceneRunSim(SceneRunCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Grid sim: 00.03's run into Sandgem: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const SceneRun run = run_into_dawns_scene(m_case.input); + logger.log(std::format("{}: \"{}\", ended {} tiles on.", m_case.input.name, Pokemon::to_string(run.outcome), run.run_tiles)); + const std::string error = scene_run_error(m_case, run); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } + +private: + SceneRunCase m_case; +}; + +const SceneRunCase SCENE_RUN_SIM_CASES[] = { + {.input = {.name = "Dawn's scene stops it mid-run", .dawn = true, .battle = false}, .expectation = {.in_scene = true}}, + {.input = {.name = "Dawn's scene stops it after a wild battle on the run", .dawn = true, .battle = true}, .expectation = {.in_scene = true}}, + {.input = {.name = "no scene: the step fails at the cap", .dawn = false, .battle = false}, .expectation = {.in_scene = false}}, + {.input = {.name = "a wild battle and no scene: the step fails at the cap", .dawn = false, .battle = true}, .expectation = {.in_scene = false}}, +}; + } // namespace @@ -137,6 +334,9 @@ void add_tests_AutoStory_WallBattleSim(UnitTestDatabase& database){ for (const WallBattleCase& item : WALL_BATTLE_SIM_CASES){ database.add(item); } + for (const SceneRunCase& item : SCENE_RUN_SIM_CASES){ + database.add(item); + } } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h index 0833c3040a..864d05a021 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h @@ -17,6 +17,8 @@ namespace PokemonBDSP{ // A wild battle on a leg to a wall, on the grid simulation: run from, or // fought when the game refuses the escape, the leg still ends at the wall. +// And 00.03's run into Sandgem: Dawn's scene stops it, a wild battle on the +// way or not; with no scene, the step fails at the run's cap. void add_tests_AutoStory_WallBattleSim(UnitTestDatabase& database); From bd521023107bdd056edebc16c8bd86e723d1f025 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 15:46:33 -0800 Subject: [PATCH 100/166] BDSP AutoStory: look for the Switch HOME menu before each step ConsoleScreenLook puts Pokemon::SwitchHomeObserver in front of BDSP's observer, so a step that starts on HOME fails as game_not_running instead of pressing X on it and walking 22 tiles (lab-B 2026-11-09 15:31). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp | 7 ++++--- .../AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h | 8 ++++++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp index 81d6efa36f..3a9edd889a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp @@ -53,11 +53,12 @@ Pokemon::StoryInterrupts story_interrupts(Pokemon::ScreenLookFunction look, cons } -ConsoleScreenLook::ConsoleScreenLook(VideoStream& stream, ProControllerContext& context) - : m_stream(stream) +ConsoleScreenLook::ConsoleScreenLook(ConsoleHandle& console, ProControllerContext& context) + : m_stream(console) , m_context(context) , m_observer(BattleCue::WILD_MENU, "") - , m_watcher(m_observer) + , m_eyes(console, m_observer) + , m_watcher(m_eyes) , m_start(current_time()) {} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h index 542512f855..000352fcbd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h @@ -21,6 +21,7 @@ #include "Common/Cpp/Time.h" #include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" #include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" #include "Pokemon/AutoStory/Pokemon_StoryInterrupts.h" @@ -53,10 +54,12 @@ bool presses_through_text(Pokemon::StoryStepKind kind); constexpr Milliseconds BETWEEN_STEPS_LOOK = Milliseconds(300); // The console's look between steps: BDSP's screen events for -// BETWEEN_STEPS_LOOK, everything showing in it judged. +// BETWEEN_STEPS_LOOK, everything showing in it judged. The Switch's HOME +// menu comes first (Pokemon::SwitchHomeObserver): BDSP's detectors read it +// as a quiet overworld (lab-B 2026-11-09 15:31). class ConsoleScreenLook{ public: - ConsoleScreenLook(VideoStream& stream, ProControllerContext& context); + ConsoleScreenLook(ConsoleHandle& console, ProControllerContext& context); Pokemon::ScreenLook look(bool fresh); @@ -64,6 +67,7 @@ class ConsoleScreenLook{ VideoStream& m_stream; ProControllerContext& m_context; BdspScreenObserver m_observer; + Pokemon::SwitchHomeObserver m_eyes; Pokemon::ScreenEventWatcher m_watcher; WallClock m_start; }; From fe2da03e79feee0c5ed554a96b9ff7159e62ae26 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 15:53:58 -0800 Subject: [PATCH 101/166] BDSP AutoStory sim: walk east and west slower than the walker's pace Console B, 00.03 (2026-11-09): the run east into Rowan's scene, timed at 160 ms a tile before the Running Shoes, held 3520 ms and stopped short of his trigger 20 tiles on. A held walk east or west in the sim now takes 200 ms a tile, so that run stops short here too (red), and RouteWalk gets the slowest walking and running paces a limit in tiles is timed at. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Simulation/PokemonBDSP_AutoStory_GridSim.cpp | 12 +++++++++++- .../Utils/PokemonBDSP_AutoStory_RouteWalk.cpp | 5 +++++ .../Utils/PokemonBDSP_AutoStory_RouteWalk.h | 14 ++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp index 0002095794..077ee46542 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -65,8 +65,18 @@ bool is_door(const StoryWorld& world, const TilePos& pos){ return tile && *tile == TileKind::DOOR && !world.occupied(pos); } +// Held time per tile of a walk east or west to a wall: slower than the +// walker's 160 ms. On the console 3520 ms held east before the Running +// Shoes went fewer than 20 tiles (lab-B 2026-11-09, 00.03): at least 176 ms +// a tile. A limit timed at the walker's pace stops short here as it did +// there. North and south keep their measured 240 ms. +constexpr Milliseconds SIM_WALK_MS_PER_TILE_ACROSS = Milliseconds(200); + Milliseconds per_tile(Direction direction, SimPace pace, bool can_run){ - return route_ms_per_tile(direction, pace == SimPace::RUN && can_run ? MoveSpeed::RUN : MoveSpeed::WALK); + if (pace == SimPace::RUN && can_run){ + return route_ms_per_tile(direction, MoveSpeed::RUN); + } + return std::max(route_ms_per_tile(direction, MoveSpeed::WALK), SIM_WALK_MS_PER_TILE_ACROSS); } uint32_t step_rng(uint64_t& state){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp index 2ee8492217..7a16a26391 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.cpp @@ -48,6 +48,11 @@ Milliseconds route_ms_per_tile(Direction direction, MoveSpeed speed){ return across(direction) ? ROUTE_MS_PER_TILE_ACROSS : ROUTE_MS_PER_TILE_UP_DOWN; } +Milliseconds route_limit_for_tiles(MoveSpeed speed, size_t tiles){ + const Milliseconds per_tile = speed == MoveSpeed::RUN ? ROUTE_RUN_MS_PER_TILE_SLOWEST : ROUTE_WALK_MS_PER_TILE_SLOWEST; + return ROUTE_START_DELAY + per_tile * tiles; +} + JoystickPosition route_stick(Direction direction){ switch (direction){ case Direction::NORTH: diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h index 2eed12b8e9..6460fa0ddc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h @@ -51,8 +51,22 @@ constexpr Milliseconds ROUTE_RUN_MS_PER_TILE_ACROSS = Milliseconds(100); // Running time per vertical tile (north or south). constexpr Milliseconds ROUTE_RUN_MS_PER_TILE_UP_DOWN = Milliseconds(150); +// The most held time a tile can take at each speed, in any direction: the +// pace a limit in tiles is timed at, so that it never cuts a run short. +// The times above are the fastest seen: a walk east before the Running +// Shoes, timed at 160 ms a tile, stopped short of Rowan's trigger 20 tiles +// on after 3520 ms held (lab-B 2026-11-09, 00.03). A Gen 4 walking step +// takes 8 frames at 30 fps, 267 ms; a run went 35 tiles north in about +// 5.75 s (r27). +constexpr Milliseconds ROUTE_WALK_MS_PER_TILE_SLOWEST = Milliseconds(270); +// The most held time a running tile can take. +constexpr Milliseconds ROUTE_RUN_MS_PER_TILE_SLOWEST = Milliseconds(170); + // Time per tile in `direction` at `speed`. Milliseconds route_ms_per_tile(Pokemon::Direction direction, MoveSpeed speed = MoveSpeed::WALK); +// The longest `tiles` tiles at `speed` take to hold, from standing: a +// limit for a run that something on the way ends (a scene's dialogue). +Milliseconds route_limit_for_tiles(MoveSpeed speed, size_t tiles); // The left stick for a direction. Row 0 is the top of a map, and the // stick's y is positive upward. JoystickPosition route_stick(Pokemon::Direction direction); From 2543014423a385127720c60086732f4a15f31751 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 15:53:58 -0800 Subject: [PATCH 102/166] BDSP AutoStory: time a run into a scene at the slowest pace run_to_dialogue() timed its tiles at the walker's nominal pace, so a walk before the Running Shoes ran out of time short of Rowan's trigger in 00.03 (lab-B 2026-11-09). Its limit is now the leg's tiles at the slowest pace of the player's speed; the scene's dialogue ends the run wherever it is. The Dawn cap test allows the further run of the sim's faster pace. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 7 +++++-- .../PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp | 6 ++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index e97e77cdde..49c612ce53 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -167,16 +167,19 @@ Outcome StoryWalkSteps::route(RunState& state, const StoryStep& step){ // scene's trigger: r35/r36 raced Dawn's to an exact tile and banner), for // the leg's tiles at most. A wild battle on the way is run from and the run // goes on. No dialogue fails the step. The scene's lines are the next step's. +// The leg's tiles are timed at the slowest pace of the player's speed (a +// walk before the Running Shoes): a run past the trigger's tile is ended by +// its dialogue anyway, where one cut short fails (lab-B 2026-11-09, 00.03). Outcome StoryWalkSteps::run_to_dialogue(const StoryStep& step){ const Pokemon::StoryLeg& leg = step.legs.front(); const MoveSpeed speed = m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK; const WalkResult walk = m_io.route().walk_to_wall({ .direction = leg.direction, - .limit = ROUTE_START_DELAY + route_ms_per_tile(leg.direction, speed) * leg.tiles, + .limit = route_limit_for_tiles(speed, leg.tiles), .label = label_of(step), .options = {.arrived = nullptr, .pace = m_can_run ? DpadPace::RUN : DpadPace::WALK}, }); - log(std::format("[{}] {}: ran {} to a dialogue: {} tiles of {} at most, {}, {} wild battle(s).", m_row, step.name, + log(std::format("[{}] {}: ran {} to a dialogue: {} moved chunks, {} tiles at most, {}, {} wild battle(s).", m_row, step.name, direction_name(leg.direction), walk.moved_chunks, leg.tiles, walk_stop_name(walk.stop), walk.wild_battles)); if (walk.stop == WalkStop::DIALOG){ return Pokemon::outcome_ok(); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp index 6fe4f6a408..ba75e1319e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp @@ -285,14 +285,16 @@ std::string scene_run_error(const SceneRunCase& test_case, const SceneRun& run){ const StoryWorld& world = *story_plan_world("Route201", "SandgemTown"); const std::optional sandgem = story_to_local(world, "SandgemTown", run.end); const int cap = into_dawns_scene().legs.front().tiles; + // The cap is timed at the slowest run; the sim runs faster, this far. + const int most = (int)((route_limit_for_tiles(MoveSpeed::RUN, cap) - ROUTE_START_DELAY) / route_ms_per_tile(Direction::EAST, MoveSpeed::RUN)); if (!run.program_failure.empty()){ return "the program failed instead of the step: " + run.program_failure; } if (test_case.input.battle != run.ran_from_battle){ return std::format("expected {} wild battle on the run.", test_case.input.battle ? "a" : "no"); } - if (run.run_tiles < 0 || run.run_tiles > cap){ - return std::format("the run went {} tiles past the route's end, outside its cap of {}.", run.run_tiles, cap); + if (run.run_tiles < 0 || run.run_tiles > most){ + return std::format("the run went {} tiles past the route's end, outside its cap of {} ({} at the sim's pace).", run.run_tiles, cap, most); } if (test_case.expectation.in_scene && (!run.outcome.succeeded() || !run.dialog || !sandgem || sandgem->x != 4)){ return std::format("\"{}\", ended at {}, not in Dawn's scene on Sandgem's column 4.", Pokemon::to_string(run.outcome), describe(world, run.end)); From 662adf80725ee1d2aa48141b2ab5bbbb7754ae51 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 16:28:27 -0800 Subject: [PATCH 103/166] BDSP AutoStory sim: a wild battle on every pass through tall grass The grid sim's RouteIO can now set off a wild battle each N tall-grass tiles the player steps onto, across walks (SimGrassBattles, SimWorldKnobs::grass). The fault sweep runs every row with one each 8 tiles, and a failure case runs 00.04's walk to the ledge column so: on lab-B (2026-11-09 16:14) its route went west through Route 201's row-5 grass to the wall and back east, met a battle on each pass, and each replan went back through the grass until "too many plans". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...PokemonBDSP_AutoStory_FaultSweep_Tests.cpp | 26 ++++++++- .../PokemonBDSP_AutoStory_GridSim.cpp | 26 ++++++++- .../PokemonBDSP_AutoStory_GridSim.h | 17 +++++- ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 54 +++++++++++++++++++ .../PokemonBDSP_AutoStory_StorySim.h | 4 +- 5 files changed, 122 insertions(+), 5 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp index 8716f0e795..3946a7d511 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp @@ -13,10 +13,13 @@ * (00.02's Starly, lab-B 2026-11-09), at each battle step and at each * step after a walk, which can end in a trainer's sight or in grass. * SimWorldKnobs::battle_opening_before. + * - GRASS_BATTLES: a wild battle on every pass through tall grass, one + * each 8 grass tiles (00.04, lab-B 2026-11-09 16:14: four in a row on + * Route 201, each replan back through the grass, "too many plans"). + * SimWorldKnobs::grass. One variant a row: the whole row so. * * Missed and short fades are swept by SimFailureCases_Tests (every single - * missed fade, banner and fade hold). Wild battles at the game's rates - * need grass on the story maps, which the simulation does not have yet. + * missed fade, banner and fade hold). * A lost tap from the input lockout waits for the measured movement * table (FRLG #293); FaultClass::LOST_TAP is its slot. * @@ -57,6 +60,7 @@ using Pokemon::TilePos; enum class FaultClass{ SCENE_END_POSE, BATTLE_OPENING, + GRASS_BATTLES, // Not swept yet: the measured movement table's lost taps (#293). LOST_TAP, }; @@ -66,6 +70,8 @@ const char* fault_class_name(FaultClass fault){ return "scene end pose"; case FaultClass::BATTLE_OPENING: return "battle opening at step start"; + case FaultClass::GRASS_BATTLES: + return "wild battles on every grass pass"; case FaultClass::LOST_TAP: return "lost tap"; } @@ -281,6 +287,19 @@ UnitTestResult sweep_battle_opening(Logger& logger, const StoryCheckpoint& row){ return sweep_result(logger, FaultClass::BATTLE_OPENING, row.id, variants, failures); } +// Row `row` with a wild battle each 8 tall-grass tiles stepped onto, all +// through the row. +UnitTestResult sweep_grass_battles(Logger& logger, const StoryCheckpoint& row){ + SimWorldKnobs knobs; + knobs.grass.every = 8; + const std::string stopped = run_row(logger, row.id, std::move(knobs)); + std::vector failures; + if (!stopped.empty()){ + failures.push_back({"", "a battle each 8 grass tiles", stopped}); + } + return sweep_result(logger, FaultClass::GRASS_BATTLES, row.id, 1, failures); +} + // A fault class swept over row `row` (empty in FAULT_SWEEP_CASES: each // row from FIRST_ROW to LAST_ROW). struct FaultSweepInput{ @@ -342,6 +361,8 @@ class Test_AutoStoryFaultSweep : public UnitTest{ return sweep_scene_end_pose(logger, m_row); case FaultClass::BATTLE_OPENING: return sweep_battle_opening(logger, m_row); + case FaultClass::GRASS_BATTLES: + return sweep_grass_battles(logger, m_row); case FaultClass::LOST_TAP: break; } @@ -357,6 +378,7 @@ class Test_AutoStoryFaultSweep : public UnitTest{ const FaultSweepCase FAULT_SWEEP_CASES[] = { {.input = {.fault = FaultClass::SCENE_END_POSE}, .expectation = {}}, {.input = {.fault = FaultClass::BATTLE_OPENING}, .expectation = {}}, + {.input = {.fault = FaultClass::GRASS_BATTLES}, .expectation = {}}, }; void add_tests_AutoStory_FaultSweep(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp index 077ee46542..d0d3abe9ec 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -442,6 +442,19 @@ void GridSimRouteIO::escape_scripted_battle(const SimWildBattle& battle, const s m_notes.push_back(std::format("[Sim] {}: wild battle {}.", label, ended)); } +bool GridSimRouteIO::grass_battle(const TilePos& tile){ + if (m_grass.every == 0 || m_sim.world().tile(tile) != TileKind::TALL_GRASS){ + return false; + } + if (++m_grass_tiles < m_grass.every){ + return false; + } + m_grass_tiles = 0; + return true; +} + +// A grass battle on the hold does not stop it: the hold goes on to the +// wall after it, as a scripted one's does. WalkResult GridSimRouteIO::walk_to_wall(const RouteWallWalk& walk){ size_t wild_battles = 0; if (const auto encounter = take_wall_encounter(walk)){ @@ -449,7 +462,15 @@ WalkResult GridSimRouteIO::walk_to_wall(const RouteWallWalk& walk){ wild_battles = 1; } const SimPace pace = walk.options.pace == DpadPace::RUN ? SimPace::RUN : SimPace::WALK; + TilePos stepped = nearest_tile(m_sim.player().pos); const SimMove move = m_sim.hold(walk.direction, walk.limit, pace); + for (int tile = 0; tile < move.distance / SIM_TILE; tile++){ + stepped = stepped.next(walk.direction); + if (grass_battle(stepped)){ + escape_scripted_battle(SimWildBattle{}, walk.label); + wild_battles++; + } + } m_notes.push_back(std::format("[Sim] {}: held {} to {} at {}.", walk.label, direction_name(walk.direction), sim_stop_name(move.stop), to_string(m_sim.player().pos))); WalkResult result{.stop = walk_stop(move.stop), .walked = move.time, .wild_battles = wild_battles, .moved_chunks = (size_t)(move.distance / SIM_TILE)}; @@ -478,9 +499,12 @@ WalkResult GridSimRouteIO::walk_taps(Direction direction, size_t tiles, const st size_t still = 0; size_t moved_at_battle = 0; for (size_t tap = 0; tap < tiles && result.stop == WalkStop::LIMIT; tap++){ - const auto encounter = take_encounter(direction, tiles, tap + 1, label); + std::optional encounter = take_encounter(direction, tiles, tap + 1, label); const SimMove move = encounter && encounter->phase == SimEncounterPhase::BEFORE_MOVEMENT ? SimMove{} : m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + if (!encounter && move.distance > 0 && grass_battle(nearest_tile(m_sim.player().pos))){ + encounter = SimWildTap{.label = label, .direction = direction, .requested_tiles = tiles, .tap = tap + 1}; + } result.walked += 800ms; if (encounter){ // Match the production escape_battle() credit, independently diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h index 68db3ed247..a0beab03c8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h @@ -209,6 +209,15 @@ struct SimWallEncounter{ Pokemon::Direction direction = Pokemon::Direction::NORTH; SimWildBattle battle; }; +// Wild battles in tall grass on every pass: one each `every` grass tiles +// the player steps onto, counted across walks, each run from at once. A +// fixed count, not the game's dice, so a route that crosses the grass +// again after each battle's replan meets a battle every time (00.04 on +// Route 201's row 5, lab-B 2026-11-09 16:14: a battle on each of four +// passes of 10 grass tiles). 0: no grass battles. +struct SimGrassBattles{ + size_t every = 0; +}; // The walker's RouteIO on a GridSim. A failure throws GridSimFailure. class GridSimRouteIO : public RouteIO{ @@ -216,12 +225,14 @@ class GridSimRouteIO : public RouteIO{ // Every line noted goes to `notes`, which must outlive this. GridSimRouteIO( GridSim& sim, std::vector& notes, - std::vector encounters = {}, std::vector wall_encounters = {} + std::vector encounters = {}, std::vector wall_encounters = {}, + SimGrassBattles grass = {} ) : m_sim(sim) , m_notes(notes) , m_encounters(std::move(encounters)) , m_wall_encounters(std::move(wall_encounters)) + , m_grass(grass) {} virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override; @@ -238,11 +249,15 @@ class GridSimRouteIO : public RouteIO{ // The escape policy on `battle`; notes a FAILURE where the console // would fail the program. void escape_scripted_battle(const SimWildBattle& battle, const std::string& label); + // Whether stepping onto `tile` sets off a grass battle (SimGrassBattles). + bool grass_battle(const Pokemon::TilePos& tile); GridSim& m_sim; std::vector& m_notes; std::vector m_encounters; std::vector m_wall_encounters; + SimGrassBattles m_grass; + size_t m_grass_tiles = 0; // grass tiles stepped onto since the last grass battle }; // What GridSimRouteIO throws for RouteNote::FAILURE. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp index 5eb9b7b3f8..52b3dd7bd1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -418,6 +418,57 @@ UnitTestResult dawns_scene_mid_run(Logger& logger){ return true; } +// Route 201's grass, as the console met it: a wild battle on each of four +// passes of 10 tiles of row 5's grass (lab-B 2026-11-09 16:14). A battle +// each 8 grass tiles gives one on every such pass. +SimWorldKnobs route_201_grass(){ + SimWorldKnobs knobs; + knobs.grass.every = 8; + return knobs; +} +// 00.04's steps from Route 201's east end down over the ledge: those after +// "to_route_201" through "over_the_ledge", less `skip`. +std::vector ledge_walk(const std::set& skip){ + std::vector steps; + bool on = false; + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const StoryStep& step : checkpoint.steps){ + if (checkpoint.id != "00.04"){ + continue; + } + if (on && !skip.contains(step.name)){ + steps.push_back(step); + } + if (step.name == "over_the_ledge"){ + return steps; + } + on |= step.name == "to_route_201"; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No over_the_ledge after to_route_201 in 00.04"); +} +// 00.04 from Route 201's east end (57, 5) and (63, 5) to below the ledge, +// a wild battle each 8 grass tiles: "" if both get there, else where and +// why each stopped. Without `skip`, the table's walk. +std::string ledge_walk_in_grass(Logger& logger, const std::set& skip){ + std::string failures; + for (const int x : {57, 63}){ + const Pose start = Pokemon::tile_pose("Route201", {TilePos{x, 5}}, Direction::WEST); + std::vector rows = story_checkpoints(); + for (StoryCheckpoint& checkpoint : rows){ + if (checkpoint.id == "00.04"){ + checkpoint.start = start; + checkpoint.steps = ledge_walk(skip); + } + } + const std::string stopped = run_case(logger, "00.04", "00.04", {.fade = {}, .banner = {}}, route_201_grass(), rows); + if (!stopped.empty()){ + failures += std::format("\nfrom ({}, 5): {}", x, stopped); + } + } + return failures; +} + struct FailureCaseInput{ std::string name; std::function body; @@ -500,6 +551,9 @@ const FailureCase AUTO_STORY_FAILURE_CASES[] = { {.input = {"00.03 out of the house from (6, 8), where Rowan's scene ends, and from a column west", home_from_each_scene_end}, .expectation = {}}, {.input = {"00.03 the walk into Rowan's scene routes onto his row and stops on his trigger mid-run", rowans_scene_from_each_start}, .expectation = {}}, {.input = {"00.03 the walk into Sandgem stops on Dawn's trigger mid-run", dawns_scene_mid_run}, .expectation = {}}, + {.input = {"00.04 to the ledge column with a wild battle on each pass through Route 201's grass (lab-B 2026-11-09 16:14)", [](Logger& logger){ + return passes(ledge_walk_in_grass(logger, {})); + }}, .expectation = {}}, }; void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index 64de628226..6583ac0aeb 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -160,6 +160,8 @@ struct SimWorldKnobs{ // the program goes on from the table's pose, the player from here // (00.03's scene a row low, lab-B 2026-11-09). std::map lands = {}; + // Wild battles in tall grass on every pass (SimGrassBattles); none unset. + SimGrassBattles grass = {}; }; // The walker's RouteIO on the story simulation, with SimWorldKnobs' slides @@ -171,7 +173,7 @@ class SimKnobRouteIO : public GridSimRouteIO{ GridSim& sim, std::vector& notes, SimMisses& misses, const SimWorldKnobs& knobs, const std::string& step, std::function cross ) - : GridSimRouteIO(sim, notes) + : GridSimRouteIO(sim, notes, {}, {}, knobs.grass) , m_grid(sim) , m_misses(misses) , m_knobs(knobs) From ea5ac8b3f68ea8ff49bff9fa4c8b66b200679054 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 16:30:47 -0800 Subject: [PATCH 104/166] BDSP AutoStory: 00.04 to the ledge column by the border sign, clear of the grass From the seven tiles the run into Route 201 leaves us on, the only wall that brought them together on row 5 was past its tall grass (x 42 to 52): west 21 to the wall at x 41, east 13 back. On lab-B (2026-11-09 16:14) each east pass met a wild battle, and each replan went back west through the grass until "too many plans". Now a tap north onto row 4, west to the border sign (55, 4), which stops us on (56, 4), then a row south and a tile west: no grass. The sim case runs it with a battle each 8 grass tiles; the old walk still fails there. 01.06's grass sweep is known failing (below_rowans_trigger's long open leg). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryTable.cpp | 15 ++++++- ...PokemonBDSP_AutoStory_FaultSweep_Tests.cpp | 2 + ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 39 +++++++++---------- 3 files changed, 34 insertions(+), 22 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 37502cd312..512a31b64e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -397,13 +397,24 @@ StoryStep out_of_the_lab_into_dawns_tour(){ } // West along Route 201 to Mom's doorstep: -// 1. Over the ledge at column 57 down onto Route 201's main road (row 14). +// 0. A tap north onto the border sign's row 4, west to the sign (55, 4), +// which stops us on (56, 4) from any of the seven tiles the run in left +// us on, then a row south and a tile west to ledge column 55. Row 5's +// own wall is past its tall grass (x 42 to 52): the old route ran west +// through it to the wall at x 41 and back east, met a wild battle on +// each pass, and each replan went back through it until "too many +// plans" (lab-B 2026-11-09 16:14). +// 1. Over the ledge at column 55 down onto Route 201's main road (row 14). // 2. West along the main road (row 14) to the Twinleaf path at column 15. // 3. South down column 15 into Twinleaf Town to row 22. // 4. East to Mom's house doorstep at (20, 22), facing north into the door. std::vector home_to_the_doors_column(){ return { - route("to_ledge_column", at(ROUTE_201, 55, 5, WEST), "west to ledge column 55", "line"), + anchored(legs("to_the_signs_row", {{.direction = NORTH, .tiles = 1}}, "a tap north onto the border sign's row"), + Pokemon::tile_pose(ROUTE_201, { + TilePos{57, 4}, TilePos{58, 4}, TilePos{59, 4}, TilePos{60, 4}, TilePos{61, 4}, TilePos{62, 4}, TilePos{63, 4} + }, NORTH)), + route("to_ledge_column", at(ROUTE_201, 55, 5, WEST), "west to the border sign, a row south, west to ledge column 55", "line"), anchored(legs("over_the_ledge", {{.direction = SOUTH, .tiles = 8}}, "south over the ledge to the lower road"), at(ROUTE_201, 55, 14, SOUTH)), route("along_route_201_road", at(ROUTE_201, 15, 14, WEST), "west along Route 201's road to the Twinleaf path", "line"), diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp index 3946a7d511..479690bf3f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp @@ -90,6 +90,8 @@ const std::map KNOWN_FAILING{ "the walk after mom_heals_us, moms_hat trusts the table's pose: measure it or clip to a wall first"}, {"PokemonBDSP::AutoStory - Fault sweep: 01.05, scene end pose", "the walk after barry_bumps_into_us trusts the table's pose: measure it or clip to a wall first"}, + {"PokemonBDSP::AutoStory - Fault sweep: 01.06, wild battles on every grass pass", + "below_rowans_trigger's open leg west 57: taps after a battle in the grass run on into a dialogue or warp the walk does not confirm"}, }; // Scenes whose end the console has proven, by step name: the sweep leaves diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp index 52b3dd7bd1..5f0cc74f2e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -426,8 +426,9 @@ SimWorldKnobs route_201_grass(){ knobs.grass.every = 8; return knobs; } -// 00.04's steps from Route 201's east end down over the ledge: those after -// "to_route_201" through "over_the_ledge", less `skip`. +// 00.04's steps from the east end of Sandgem's path down over Route 201's +// ledge: "to_route_201" through "over_the_ledge", less `skip`. The run +// west leaves us on one of seven tiles, as on the console. std::vector ledge_walk(const std::set& skip){ std::vector steps; bool on = false; @@ -436,37 +437,29 @@ std::vector ledge_walk(const std::set& skip){ if (checkpoint.id != "00.04"){ continue; } + on |= step.name == "to_route_201"; if (on && !skip.contains(step.name)){ steps.push_back(step); } if (step.name == "over_the_ledge"){ return steps; } - on |= step.name == "to_route_201"; } } throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No over_the_ledge after to_route_201 in 00.04"); } -// 00.04 from Route 201's east end (57, 5) and (63, 5) to below the ledge, -// a wild battle each 8 grass tiles: "" if both get there, else where and -// why each stopped. Without `skip`, the table's walk. +// 00.04 from the east end of Sandgem's path to below Route 201's ledge, a +// wild battle each 8 grass tiles: "" if it gets there, else where and why +// it stopped. Without `skip`, the table's walk. std::string ledge_walk_in_grass(Logger& logger, const std::set& skip){ - std::string failures; - for (const int x : {57, 63}){ - const Pose start = Pokemon::tile_pose("Route201", {TilePos{x, 5}}, Direction::WEST); - std::vector rows = story_checkpoints(); - for (StoryCheckpoint& checkpoint : rows){ - if (checkpoint.id == "00.04"){ - checkpoint.start = start; - checkpoint.steps = ledge_walk(skip); - } - } - const std::string stopped = run_case(logger, "00.04", "00.04", {.fade = {}, .banner = {}}, route_201_grass(), rows); - if (!stopped.empty()){ - failures += std::format("\nfrom ({}, 5): {}", x, stopped); + std::vector rows = story_checkpoints(); + for (StoryCheckpoint& checkpoint : rows){ + if (checkpoint.id == "00.04"){ + checkpoint.start = table_step("00.04", "onto_the_path").target; + checkpoint.steps = ledge_walk(skip); } } - return failures; + return run_case(logger, "00.04", "00.04", {.fade = {}, .banner = {}}, route_201_grass(), rows); } struct FailureCaseInput{ @@ -554,6 +547,12 @@ const FailureCase AUTO_STORY_FAILURE_CASES[] = { {.input = {"00.04 to the ledge column with a wild battle on each pass through Route 201's grass (lab-B 2026-11-09 16:14)", [](Logger& logger){ return passes(ledge_walk_in_grass(logger, {})); }}, .expectation = {}}, + {.input = {"00.04 the old walk to the ledge column, west to row 5's wall through the grass, fails there: too many plans", [](Logger& logger){ + const std::string stopped = ledge_walk_in_grass(logger, {"to_the_signs_row"}); + return stopped.find("too many plans") != std::string::npos + ? UnitTestResult(true) + : UnitTestResult("the grass battles no longer stop the old walk: " + (stopped.empty() ? std::string("it passes") : stopped)); + }}, .expectation = {}}, }; void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database){ From a43a9079abbfe9c91ea6a6e8e1634fe8dd4b7dab Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 16:31:32 -0800 Subject: [PATCH 105/166] BDSP AutoStory: route plans golden for 00.04's walk by the border sign Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Programs/AutoStory/Data/route_plans.golden.txt | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt index 4fc70f03fd..c5e7fbf5c6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt @@ -93,12 +93,13 @@ anchor); 0 from one start tile. totals: 3 legs, 2 turns, 1 open, 2 localization == 00.04 to_ledge_column (costs: line) - from: Route201 (57, 5) (58, 5) (59, 5) (60, 5) (61, 5) (62, 5) (63, 5) facing west (set) + from: Route201 (57, 4) (58, 4) (59, 4) (60, 4) (61, 4) (62, 4) (63, 4) facing north (set) target: Route201 (55, 5) facing west (tile) - start candidates: Route 201 (57, 5), Route 201 (58, 5), Route 201 (59, 5), Route 201 (60, 5), Route 201 (61, 5), Route 201 (62, 5), Route 201 (63, 5) - 1. west 21 (to wall) -> Route 201 (42, 5) - 2. east 13 (open) -> Route 201 (55, 5) - totals: 2 legs, 1 turns, 1 open, 1 localization + start candidates: Route 201 (57, 4), Route 201 (58, 4), Route 201 (59, 4), Route 201 (60, 4), Route 201 (61, 4), Route 201 (62, 4), Route 201 (63, 4) + 1. west 7 (to wall) -> Route 201 (56, 4) + 2. south 1 (open) -> Route 201 (56, 5) + 3. west 1 (open) -> Route 201 (55, 5) + totals: 3 legs, 2 turns, 2 open, 1 localization == 00.04 along_route_201_road (costs: line) from: Route201 (55, 14) facing south (tile) From d4db4ddf2d2431d48075eb23eb784e2df29b5c9b Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 16:49:23 -0800 Subject: [PATCH 106/166] BDSP AutoStory: rows after 01.02 no longer meet Route 203's Youngster 01.02's walk east along Route 203's row 18 crosses the Youngster's sight down column 31, so every later row's save has him beaten. The walker and the story sim still gave him to 01.06, and in the grass sweep a wild battle on the open leg west 57 was followed by his dialogue, which an interrupted open leg cannot confirm. row_trainers() now leaves out the trainers an earlier row fights. 01.06's grass sweep stays known failing on a second cause: the battle leaves the leg's end on Jubilife's (44, 22) or (45, 22), and from there the Ace Trainer's wander zone (45..47, 21) leaves no plan. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 23 ++++++++++++++- .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 4 +++ .../PokemonBDSP_AutoStory_Walk_Tests.cpp | 28 +++++++++++++++++++ ...PokemonBDSP_AutoStory_FaultSweep_Tests.cpp | 3 +- .../PokemonBDSP_AutoStory_StorySim.cpp | 2 +- 5 files changed, 57 insertions(+), 3 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index 49c612ce53..0937fc153c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -50,9 +50,30 @@ std::string label_of(const StoryStep& step){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "RouteIO::note() returned from a failure: " + message); } +// A trainer every pass of a row fights, by that row. +struct FoughtTrainer{ + const char* row; + const char* name; +}; +// 01.02's walk east along Route 203's row 18 crosses his sight down +// column 31 (route_203_trainer_sights()). +const FoughtTrainer FOUGHT_TRAINERS[] = { + {"01.02", "Youngster (above row 18)"}, +}; + } // namespace +std::vector row_trainers(const StoryWorld& world, const std::string& row){ + std::vector sights = story_trainers(world); + std::erase_if(sights, [&row](const TrainerSight& sight){ + return std::any_of(std::begin(FOUGHT_TRAINERS), std::end(FOUGHT_TRAINERS), [&](const FoughtTrainer& fought){ + return row > std::string(fought.row) && sight.name == fought.name; + }); + }); + return sights; +} + CenterEntry run_into_center(StoryStepIO& io, bool run, const std::function& inside, const std::function& line_up){ if (io.run_into_door(Direction::NORTH, run).any()){ return CenterEntry::FADED; @@ -127,7 +148,7 @@ Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep targets.push_back(story_to_world(*maps, goal.map, pos)); } // The ones fought stay off m_trainers until the next attempt. - std::vector& sights = m_trainers.try_emplace(maps, story_trainers(*maps)).first->second; + std::vector& sights = m_trainers.try_emplace(maps, row_trainers(*maps, m_row)).first->second; RouteTrainers trainers{ sights, [this](const std::string& trainer){ m_io.fight(trainer); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index eb9cb277cb..d340d36e80 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -50,6 +50,10 @@ TappedEnd tapped_end(const StoryWorld& world, const std::string& map, const Poke // The tiles a "measured" LEGS step may end on from `from`, one a tile of // it; the step measures which. Nothing if `from`'s map has no world. std::optional measured_ends(const Pokemon::Pose& from, const Pokemon::StoryStep& step); +// The trainers of `world` who can see us in row `row`: story_trainers(), +// less those an earlier row fights, whom its save and every later one's +// keep beaten. +std::vector row_trainers(const StoryWorld& world, const std::string& row); // Executes walking and movement-related story steps via StoryStepIO. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp index 4fbc831eab..715a5aac4d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp @@ -4,6 +4,7 @@ * */ +#include #include #include #include @@ -18,7 +19,9 @@ #include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "Utils/PokemonBDSP_AutoStory_Walk.h" #include "Actions/PokemonBDSP_AutoStory_Talks.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" #include "PokemonBDSP_AutoStory_Walk_Tests.h" namespace PokemonAutomation{ @@ -329,6 +332,27 @@ UnitTestResult test_pokemon_center_on_screen(Logger&){ return true; } +// 01.02's walk east beats the Youngster above Route 203's row 18; the rows +// after it, from saves made since, do not meet him again. +UnitTestResult test_row_trainers(Logger&){ + const StoryWorld* world = story_plan_world("Route203", "JubilifeCity"); + if (world == nullptr){ + return std::string("no world joins Route 203 and Jubilife"); + } + const auto has_youngster = [world](const std::string& row){ + const std::vector sights = row_trainers(*world, row); + return std::any_of(sights.begin(), sights.end(), [](const TrainerSight& sight){ + return sight.name == "Youngster (above row 18)"; + }); + }; + if (!has_youngster("01.02")){ + return std::string("01.02 fights the Youngster: he must be on its trainers"); + } + if (has_youngster("01.06")){ + return std::string("01.06 starts from a save after 01.02 beat the Youngster"); + } + return true; +} struct AutoStoryWalkInput{ std::string name; @@ -444,6 +468,10 @@ const AutoStoryWalkCase AUTO_STORY_WALK_CASES[] = { .input = {"a wild battle on an open leg's taps, placed by its screen events", test_leg_battle_place}, .expectation = {}, }, + { + .input = {"a row's trainers leave out those an earlier row beat", test_row_trainers}, + .expectation = {}, + }, }; void add_tests_AutoStory_Walk(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp index 479690bf3f..76946f5d6c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp @@ -91,7 +91,8 @@ const std::map KNOWN_FAILING{ {"PokemonBDSP::AutoStory - Fault sweep: 01.05, scene end pose", "the walk after barry_bumps_into_us trusts the table's pose: measure it or clip to a wall first"}, {"PokemonBDSP::AutoStory - Fault sweep: 01.06, wild battles on every grass pass", - "below_rowans_trigger's open leg west 57: taps after a battle in the grass run on into a dialogue or warp the walk does not confirm"}, + "below_rowans_trigger's open leg west 57: a battle in its grass leaves it on Jubilife's (44, 22) or (45, 22), " + "from which the Ace Trainer's (45..47, 21) leaves no plan: end the long leg on a column both of whose candidates clip north to row 8"}, }; // Scenes whose end the console has proven, by step name: the sweep leaves diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index 2f09a50379..d2dfa710aa 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -426,7 +426,7 @@ const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ SimWorld SimExecutor::setup(const StoryWorld* world) const{ // B runs once the shoes' scene has given them: the scene ends at home. - SimWorld out{.world = world, .trainers = story_trainers(*world), .can_run = m_walks.can_run()}; + SimWorld out{.world = world, .trainers = row_trainers(*world, m_row), .can_run = m_walks.can_run()}; for (const SimStairs& stairs : sim_stairs()){ if (sim_world(stairs.map) == world){ out.doors.push_back(story_to_world(*world, stairs.map, map_point(stairs.map, "stairs").next(stairs.side))); From ca67fa7b5d4226b8612a931d1af4e15d2aaf70c1 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 17:01:37 -0800 Subject: [PATCH 107/166] BDSP AutoStory: 00.04 clips to walls after Mom's scenes The legs after mom_heals_us and the route after moms_hat started from the table's guessed end tile; from a tile next to it they ended a tile off or replanned until "too many plans" (fault sweep). North, east and south to the walls now end on (11, 8) from each of them, and west to Twinleaf's wall gives the route two known start tiles. The sweep no longer lands a scene on a door's tile, which a step onto would go through. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Data/route_plans.golden.txt | 36 ++++++++++++------- .../PokemonBDSP_AutoStory_StoryTable.cpp | 17 +++++++-- ...PokemonBDSP_AutoStory_FaultSweep_Tests.cpp | 11 ++++-- 3 files changed, 46 insertions(+), 18 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt index c5e7fbf5c6..141639b0a8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt @@ -132,21 +132,31 @@ anchor); 0 from one start tile. 1. north 1 (open) -> PlayerHouse1F (6, 8) totals: 1 legs, 0 turns, 1 open, 0 localization +== 00.04 around_mom (costs: route) + from: PlayerHouse1F (11, 8) facing south (tile) + target: PlayerHouse1F (6, 9) facing south (tile) + start candidates: PlayerHouse1F (11, 8) + 1. west 1 (open) -> PlayerHouse1F (10, 8) + 2. south 1 (open) -> PlayerHouse1F (10, 9) + 3. west 4 (open) -> PlayerHouse1F (6, 9) + totals: 3 legs, 2 turns, 3 open, 0 localization + == 00.04 short_of_the_catch_tutorial (costs: route) - from: TwinleafTown (19, 22) facing east (tile) + from: TwinleafTown (6, 22) (6, 23) facing west (set) target: Route202 (22, 27) facing west (tile) - start candidates: Twinleaf Town (19, 22) - 1. west 2 (open) -> Twinleaf Town (17, 22) - 2. north 34 (to wall) -> Route 201 (17, 13) - 3. east 40 (to wall) -> Route 201 (57, 13) - 4. west 7 (open) -> Route 201 (50, 13) - 5. north 7 (open) -> Route 201 (50, 6) - 6. east 43 (to wall) -> Sandgem Town (29, 13) - 7. west 5 (open) -> Sandgem Town (24, 13) - 8. north 21 (to wall) -> Route 202 (25, 24) - 9. west 3 (to wall) -> Route 202 (22, 24) - 10. south 3 (open) -> Route 202 (22, 27) - totals: 10 legs, 9 turns, 5 open, 0 localization + start candidates: Twinleaf Town (6, 22), Twinleaf Town (6, 23) + 1. north 19 (to wall) -> Twinleaf Town (6, 4) + 2. east 8 (open) -> Twinleaf Town (14, 4) + 3. north 16 (to wall) -> Route 201 (14, 13) + 4. east 43 (to wall) -> Route 201 (57, 13) + 5. west 7 (open) -> Route 201 (50, 13) + 6. north 7 (open) -> Route 201 (50, 6) + 7. east 43 (to wall) -> Sandgem Town (29, 13) + 8. west 5 (open) -> Sandgem Town (24, 13) + 9. north 21 (to wall) -> Route 202 (25, 24) + 10. west 3 (to wall) -> Route 202 (22, 24) + 11. south 3 (open) -> Route 202 (22, 27) + totals: 11 legs, 10 turns, 5 open, 1 localization == 00.04b to_catch_grass (costs: route) from: Route202 (15, 25) (16, 25) (17, 25) (18, 25) (19, 25) (20, 25) (21, 25) (15, 26) (16, 26) (17, 26) (18, 26) (19, 26) (20, 26) (21, 26) (15, 27) (16, 27) (17, 27) (18, 27) (19, 27) (20, 27) (21, 27) (21, 28) (21, 29) (set) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 512a31b64e..c013659b72 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -439,10 +439,23 @@ std::vector to_the_catch(){ steps.push_back(route("beside_mom", at(HOME, 6, 8, EAST), "west of Mom at (7, 8)")); steps.push_back(talk("mom", "Mom")); steps.push_back(scene("mom_heals_us", at(HOME, 7, 7, SOUTH), "Mom heals us; Barry's mom gives us his parcel")); - steps.push_back(legs("around_mom", {{.direction = WEST, .tiles = 1}, {.direction = SOUTH, .tiles = 2}}, - "around Mom to (6, 9) above the door")); + // Where her scene leaves us is a guess (no console run stopped after + // it): from any tile next to it, fixed legs ended a tile off or + // against her. North, east and south to the walls end on (11, 8) from + // each of them: row 5's shelves stop columns 6 and 7 on row 6, the + // wall stops column 8 on row 5, the east wall column 11, row 9's wall + // row 8. The route goes on from there. + steps.push_back(anchored(to_walls("into_the_east_corner", { + {.direction = NORTH, .tiles = 4}, {.direction = EAST, .tiles = 6}, {.direction = SOUTH, .tiles = 4}, + }, "north, east and south to the walls, into the room's east corner"), at(HOME, 11, 8, SOUTH))); + steps.push_back(route("around_mom", at(HOME, 6, 9, SOUTH), "round Mom to (6, 9) above the door")); steps.push_back(step_into("to_moms_call", SOUTH, "onto the door mat (6, 10), triggering Mom's call")); steps.push_back(scene("moms_hat", at(TWINLEAF, 19, 22, EAST), "Mom's hat; she walks out with us")); + // Her scene's end is a guess too, and Mom may stand east of us: west + // along the row to Twinleaf's west wall, column 6, from either row the + // scene may leave us on. The route plans from both. + steps.push_back(anchored(to_walls("to_twinleafs_west_wall", {{.direction = WEST, .tiles = 16}}, + "west along the row to the town's west wall"), Pokemon::tile_pose(TWINLEAF, {TilePos{6, 22}, TilePos{6, 23}}, WEST))); steps.push_back(route("short_of_the_catch_tutorial", at(ROUTE_202, 22, 27, WEST), "through Sandgem onto Route 202, east of its trigger column")); steps.push_back(step_into("catch_tutorial_trigger", WEST, "the trigger (21, 25..29), VAR_ROUTE_202_STATE 0")); steps.push_back(event("catch_tutorial", "Dawn's catching tutorial")); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp index 76946f5d6c..389fb59c18 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp @@ -41,6 +41,8 @@ #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Pokemon/Navigation/Pokemon_MapData.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_StorySim.h" #include "PokemonBDSP_AutoStory_FaultSweep_Tests.h" @@ -86,8 +88,6 @@ const char* LAST_ROW = "01.11"; const std::map KNOWN_FAILING{ {"PokemonBDSP::AutoStory - Fault sweep: 00.01, scene end pose", "the walk after barry_runs_to_the_lake trusts the table's pose: measure it or clip to a wall first"}, - {"PokemonBDSP::AutoStory - Fault sweep: 00.04, scene end pose", - "the walk after mom_heals_us, moms_hat trusts the table's pose: measure it or clip to a wall first"}, {"PokemonBDSP::AutoStory - Fault sweep: 01.05, scene end pose", "the walk after barry_bumps_into_us trusts the table's pose: measure it or clip to a wall first"}, {"PokemonBDSP::AutoStory - Fault sweep: 01.06, wild battles on every grass pass", @@ -165,7 +165,8 @@ bool wild_or_trainers(const StoryStep& step){ // The tiles within one of `center`, diagonals too, that the player can // reach from it in one or two steps, and not in `seen`: where a scene can -// leave them instead. A tile behind a wall is not one. +// leave them instead. A tile behind a wall is not one, nor a door's: a +// step onto it goes through (00.04's moms_hat by the house's door). void walkable_neighbors(const StoryWorld* world, const Pose& pose, const TilePos& center, std::set>& seen, std::vector& out){ const auto step = [](const TilePos& tile, Direction direction){ switch (direction){ @@ -183,7 +184,11 @@ void walkable_neighbors(const StoryWorld* world, const Pose& pose, const TilePos GridSim sim(SimWorld{.world = world}, story_to_world(*world, pose.map, from), direction, false); return sim_can_step(sim, direction); }; + const Pokemon::MapData& map = story_map(pose.map); const auto add = [&](const TilePos& tile){ + if (map.tiles.at(tile) == Pokemon::TileKind::DOOR){ + return; + } if (seen.insert({tile.x, tile.y}).second){ out.push_back(tile); } From 905d42115962bcb29aa392e2d866148c5189408b Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 17:04:21 -0800 Subject: [PATCH 108/166] BDSP AutoStory: Mom's heal and hat steps in their own function to_the_catch() was 56 lines after the wall clips (code health limit 50). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryTable.cpp | 52 +++++++++++-------- 1 file changed, 31 insertions(+), 21 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index c013659b72..96f066c47d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -423,6 +423,34 @@ std::vector home_to_the_doors_column(){ }; } +// Into the house, Mom's heal, and out with her hat: her scenes' ends +// are guesses, so walls tell us where we are after each. +std::vector moms_heal_and_hat(){ + return { + step_into("into_the_house", NORTH, "the house's door", at(HOME, 6, 9, NORTH)), + route("beside_mom", at(HOME, 6, 8, EAST), "west of Mom at (7, 8)"), + talk("mom", "Mom"), + scene("mom_heals_us", at(HOME, 7, 7, SOUTH), "Mom heals us; Barry's mom gives us his parcel"), + // Where her scene leaves us is a guess (no console run stopped after + // it): from any tile next to it, fixed legs ended a tile off or + // against her. North, east and south to the walls end on (11, 8) from + // each of them: row 5's shelves stop columns 6 and 7 on row 6, the + // wall stops column 8 on row 5, the east wall column 11, row 9's wall + // row 8. The route goes on from there. + anchored(to_walls("into_the_east_corner", { + {.direction = NORTH, .tiles = 4}, {.direction = EAST, .tiles = 6}, {.direction = SOUTH, .tiles = 4}, + }, "north, east and south to the walls, into the room's east corner"), at(HOME, 11, 8, SOUTH)), + route("around_mom", at(HOME, 6, 9, SOUTH), "round Mom to (6, 9) above the door"), + step_into("to_moms_call", SOUTH, "onto the door mat (6, 10), triggering Mom's call"), + scene("moms_hat", at(TWINLEAF, 19, 22, EAST), "Mom's hat; she walks out with us"), + // Her scene's end is a guess too, and Mom may stand east of us: west + // along the row to Twinleaf's west wall, column 6, from either row the + // scene may leave us on. The route plans from both. + anchored(to_walls("to_twinleafs_west_wall", {{.direction = WEST, .tiles = 16}}, + "west along the row to the town's west wall"), Pokemon::tile_pose(TWINLEAF, {TilePos{6, 22}, TilePos{6, 23}}, WEST)), + }; +} + std::vector to_the_catch(){ std::vector steps{ out_of_the_lab_into_dawns_tour(), @@ -435,27 +463,9 @@ std::vector to_the_catch(){ for (StoryStep& s : home_to_the_doors_column()){ steps.push_back(std::move(s)); } - steps.push_back(step_into("into_the_house", NORTH, "the house's door", at(HOME, 6, 9, NORTH))); - steps.push_back(route("beside_mom", at(HOME, 6, 8, EAST), "west of Mom at (7, 8)")); - steps.push_back(talk("mom", "Mom")); - steps.push_back(scene("mom_heals_us", at(HOME, 7, 7, SOUTH), "Mom heals us; Barry's mom gives us his parcel")); - // Where her scene leaves us is a guess (no console run stopped after - // it): from any tile next to it, fixed legs ended a tile off or - // against her. North, east and south to the walls end on (11, 8) from - // each of them: row 5's shelves stop columns 6 and 7 on row 6, the - // wall stops column 8 on row 5, the east wall column 11, row 9's wall - // row 8. The route goes on from there. - steps.push_back(anchored(to_walls("into_the_east_corner", { - {.direction = NORTH, .tiles = 4}, {.direction = EAST, .tiles = 6}, {.direction = SOUTH, .tiles = 4}, - }, "north, east and south to the walls, into the room's east corner"), at(HOME, 11, 8, SOUTH))); - steps.push_back(route("around_mom", at(HOME, 6, 9, SOUTH), "round Mom to (6, 9) above the door")); - steps.push_back(step_into("to_moms_call", SOUTH, "onto the door mat (6, 10), triggering Mom's call")); - steps.push_back(scene("moms_hat", at(TWINLEAF, 19, 22, EAST), "Mom's hat; she walks out with us")); - // Her scene's end is a guess too, and Mom may stand east of us: west - // along the row to Twinleaf's west wall, column 6, from either row the - // scene may leave us on. The route plans from both. - steps.push_back(anchored(to_walls("to_twinleafs_west_wall", {{.direction = WEST, .tiles = 16}}, - "west along the row to the town's west wall"), Pokemon::tile_pose(TWINLEAF, {TilePos{6, 22}, TilePos{6, 23}}, WEST))); + for (StoryStep& s : moms_heal_and_hat()){ + steps.push_back(std::move(s)); + } steps.push_back(route("short_of_the_catch_tutorial", at(ROUTE_202, 22, 27, WEST), "through Sandgem onto Route 202, east of its trigger column")); steps.push_back(step_into("catch_tutorial_trigger", WEST, "the trigger (21, 25..29), VAR_ROUTE_202_STATE 0")); steps.push_back(event("catch_tutorial", "Dawn's catching tutorial")); From 82f0bfbfa6c0a3c8f068bc4da911a37ff88c9878 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 17:07:46 -0800 Subject: [PATCH 109/166] BDSP AutoStory: 01.05 clips to walls before the Gate's mouth From a row above or below the tile Barry's push is assumed to leave us on, the run west missed the Gate's mouth (fault sweep). South to row 17's wall and west to column 2's end on (2, 17) from each of them; four taps north put us on the mouth's row. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryTable.cpp | 15 +++++++++++---- .../PokemonBDSP_AutoStory_FaultSweep_Tests.cpp | 2 -- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 96f066c47d..923d323ace 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -683,10 +683,17 @@ StoryCheckpoint oreburgh_to_route_203(){ "west along the street, north up the stairs west of the houses, west along the Gate's row", "town"), step_into("barrys_trigger", WEST, "the trigger (6, 12..15)"), scene("barry_bumps_into_us", at(OREBURGH, 5, 13, EAST), "Barry runs into us, talks of Eterna, and leaves (assumed: the push)"), - // Straight west from where Barry leaves us into the Gate's mouth - // (1, 13), running until the fade; the warp's other end is the - // Gate's (27, 22), beside its east mouth. Not an open walk to the - // tile beside the mouth and then a tap: that walk slid onto the warp + // Where the push leaves us is assumed: a row up or down, the run + // west below missed the mouth. South to the wall, row 17, and west + // to it, column 2, from any of those tiles; then taps up to the + // mouth's row. + anchored(to_walls("below_the_gates_mouth", {{.direction = SOUTH, .tiles = 6}, {.direction = WEST, .tiles = 6}}, + "south to row 17's wall, then west to column 2's"), at(OREBURGH, 2, 17, WEST)), + legs("to_the_gates_row", {{.direction = NORTH, .tiles = 4}}, "taps up column 2 to the mouth's row 13"), + // West from there into the Gate's mouth (1, 13), running until + // the fade; the warp's other end is the Gate's (27, 22), beside + // its east mouth. Not an open walk to the tile beside the mouth + // and then a tap: that walk slid onto the warp // (screen change 177 at 1.6 s), the banner came and went unwatched, // and the tap step took the Gate's dim floor for its fade and waited // for a banner already gone (lab-B, 2026-11-08 15:31, 15:39, 15:47, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp index 389fb59c18..3eb48f2293 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp @@ -88,8 +88,6 @@ const char* LAST_ROW = "01.11"; const std::map KNOWN_FAILING{ {"PokemonBDSP::AutoStory - Fault sweep: 00.01, scene end pose", "the walk after barry_runs_to_the_lake trusts the table's pose: measure it or clip to a wall first"}, - {"PokemonBDSP::AutoStory - Fault sweep: 01.05, scene end pose", - "the walk after barry_bumps_into_us trusts the table's pose: measure it or clip to a wall first"}, {"PokemonBDSP::AutoStory - Fault sweep: 01.06, wild battles on every grass pass", "below_rowans_trigger's open leg west 57: a battle in its grass leaves it on Jubilife's (44, 22) or (45, 22), " "from which the Ace Trainer's (45..47, 21) leaves no plan: end the long leg on a column both of whose candidates clip north to row 8"}, From 905488cccc7fe37843862ebb2606f8c43a3a14d3 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 17:13:33 -0800 Subject: [PATCH 110/166] BDSP AutoStory: 00.01 clips to Barry's back wall before his stairs From a tile next to where Barry's scene is assumed to leave us, the route to the stairs' mat had no plan or ended a column east (fault sweep). A tap east and north to the back wall put each of them on row 4 east of the stairs, and the run west goes down them. Barry's house steps move to their own function to keep bedroom_to_lakefront() short. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Data/route_plans.golden.txt | 7 -- .../PokemonBDSP_AutoStory_StoryTable.cpp | 64 +++++++++++++------ ...PokemonBDSP_AutoStory_FaultSweep_Tests.cpp | 2 - 3 files changed, 45 insertions(+), 28 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt index 141639b0a8..73ae322c95 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt @@ -43,13 +43,6 @@ anchor); 0 from one start tile. target: RivalHouse1F (2, 3) facing east (tile) not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends) -== 00.01 above_barrys_stairs (costs: route) - from: RivalHouse2F (3, 5) facing north (tile) - target: RivalHouse2F (3, 4) facing west (tile) - start candidates: RivalHouse2F (3, 5) - 1. north 1 (to wall) -> RivalHouse2F (3, 4) - totals: 1 legs, 0 turns, 0 open, 0 localization - == 00.01 above_barrys_door (costs: route) from: RivalHouse1F (2, 3) (tile) target: RivalHouse1F (6, 9) facing south (tile) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 923d323ace..6e2cf3fbfd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -252,6 +252,48 @@ std::vector route_201_to_the_lakefront(){ }; } +// Barry's room east of its stairs: columns 3 to 5, rows 4 to `bottom`. +Pose barrys_room_by_the_stairs(int bottom){ + std::vector tiles; + for (int y = 4; y <= bottom; y++){ + for (int x = 3; x <= 5; x++){ + tiles.push_back({x, y}); + } + } + return Pokemon::tile_pose(BARRYS_ROOM, tiles, NORTH); +} + +// 00.01's visit to Barry: his door, up to his room, and out again. +std::vector barrys_house(){ + return { + // From (9, 13) straight north through (9, 12) (its trigger is spent) into + // his door: a separate tap to (9, 12) first stepped into the door before + // into_barrys_house watched for the fade. + step_into("into_barrys_house", NORTH, "past (9, 12) into his door", at(BARRYS_HOUSE, "door", NORTH)), + legs("off_barrys_mat", {{.direction = NORTH, .tiles = 1}}, "off the door's mat, which no route starts on"), + // Like ours: stairs are entered sideways from the top of their mat, the + // stairs point (r11: north from (2, 4) only bumps the wall). + route("below_barrys_stairs", at(BARRYS_HOUSE, "stairs", EAST), "past his mother at (4, 6) to the top of the stairs' mat"), + step_into("up_barrys_stairs", EAST, "onto the stairs", at(BARRYS_ROOM, "stairs")), + // Automatic on arrival (2F frame script), not a talk: Barry runs past us down + // the stairs and the game walks us a tile south of them (decomp; Butters + // never walked to him). + scene("barry_runs_to_the_lake", at(BARRYS_ROOM, 3, 5, NORTH), "Barry's lines; he runs off to the lake", "a"), + // Where the scene leaves us is the decomp's: from a tile next to it, + // the route to the stairs' mat had no plan or ended a column east. + // A tap east takes each of them (column 2 only from row 6) into + // columns 3 to 5, and north to the back wall onto row 4 there, + // east of the stairs, which a run west goes down. + anchored(legs("off_barrys_west_wall", {{.direction = EAST, .tiles = 1}}, "a tap east, clear of the west wall"), + barrys_room_by_the_stairs(6)), + anchored(to_walls("up_to_barrys_back_wall", {{.direction = NORTH, .tiles = 3}}, "north to the room's back wall"), + barrys_room_by_the_stairs(4)), + step_into("down_barrys_stairs", WEST, "west along row 4 onto the stairs", at(BARRYS_HOUSE, "stairs")), + route("above_barrys_door", at(BARRYS_HOUSE, 6, 9, SOUTH), "back to his door"), + step_into("out_of_barrys_house", SOUTH, "out of his door", at(TWINLEAF, "barry_doorstep", SOUTH)), + }; +} + // 00.01: down from the bedroom, Barry's house, and out to the Lakefront. StoryCheckpoint bedroom_to_lakefront(){ std::vector steps{ @@ -278,26 +320,10 @@ StoryCheckpoint bedroom_to_lakefront(){ // r10: the first north tap after the scene gave no warp, the second did). scene("barry_bursts_out", at(TWINLEAF, 9, 13, NORTH), "Barry runs out, bumps into us and runs back in", "a"), scene("barry_goes_home", at(TWINLEAF, 9, 13, NORTH), "his second lines (Butters waited for two)", "a"), - // From (9, 13) straight north through (9, 12) (its trigger is spent) into - // his door: a separate tap to (9, 12) first stepped into the door before - // into_barrys_house watched for the fade. - step_into("into_barrys_house", NORTH, "past (9, 12) into his door", at(BARRYS_HOUSE, "door", NORTH)), - legs("off_barrys_mat", {{.direction = NORTH, .tiles = 1}}, "off the door's mat, which no route starts on"), - // Like ours: stairs are entered sideways from the top of their mat, the - // stairs point (r11: north from (2, 4) only bumps the wall). - route("below_barrys_stairs", at(BARRYS_HOUSE, "stairs", EAST), "past his mother at (4, 6) to the top of the stairs' mat"), - step_into("up_barrys_stairs", EAST, "onto the stairs", at(BARRYS_ROOM, "stairs")), - // Automatic on arrival (2F frame script), not a talk: Barry runs past us down - // the stairs and the game walks us a tile south of them (decomp; Butters - // never walked to him). - scene("barry_runs_to_the_lake", at(BARRYS_ROOM, 3, 5, NORTH), "Barry's lines; he runs off to the lake", "a"), - // Butters went west from there straight into the stairs; ours are entered from - // the mat's top tile, so go there first (unchecked: which works). - route("above_barrys_stairs", at(BARRYS_ROOM, "stairs", WEST), "back to the top of the stairs' mat"), - step_into("down_barrys_stairs", WEST, "onto the stairs", at(BARRYS_HOUSE, "stairs")), - route("above_barrys_door", at(BARRYS_HOUSE, 6, 9, SOUTH), "back to his door"), - step_into("out_of_barrys_house", SOUTH, "out of his door", at(TWINLEAF, "barry_doorstep", SOUTH)), }; + for (StoryStep& step : barrys_house()){ + steps.push_back(std::move(step)); + } for (StoryStep& step : route_201_to_the_lakefront()){ steps.push_back(std::move(step)); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp index 3eb48f2293..9de636f82d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp @@ -86,8 +86,6 @@ const char* LAST_ROW = "01.11"; // Sweeps the program fails today, by test name, with the likely fix. const std::map KNOWN_FAILING{ - {"PokemonBDSP::AutoStory - Fault sweep: 00.01, scene end pose", - "the walk after barry_runs_to_the_lake trusts the table's pose: measure it or clip to a wall first"}, {"PokemonBDSP::AutoStory - Fault sweep: 01.06, wild battles on every grass pass", "below_rowans_trigger's open leg west 57: a battle in its grass leaves it on Jubilife's (44, 22) or (45, 22), " "from which the Ace Trainer's (45..47, 21) leaves no plan: end the long leg on a column both of whose candidates clip north to row 8"}, From 781830802f6024baf1420c987398c1bc58a6f3e9 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 17:20:23 -0800 Subject: [PATCH 111/166] BDSP AutoStory: 01.06 turns up Jubilife's road at its west column A wild battle in the grass on the long leg west left the route to Rowan's trigger on Jubilife (44, 22) or (45, 22), from which no plan clears the Ace Trainer who wanders (45..47, 21) (fault sweep, a battle each 8 grass tiles). The route now ends on the road's west corner (41, 8): from (41, 22) and (42, 22) alike the walls bring us there. Then east along row 8 to the sign's wall below the trigger. KNOWN_FAILING is empty. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Data/route_plans.golden.txt | 18 ++++++++++++------ .../PokemonBDSP_AutoStory_StoryTable.cpp | 12 ++++++++++-- .../PokemonBDSP_AutoStory_FaultSweep_Tests.cpp | 3 --- 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt index 73ae322c95..43c45d0b61 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt @@ -360,17 +360,23 @@ anchor); 0 from one start tile. 6. west 3 (open) -> OreburghGate (5, 22) totals: 6 legs, 5 turns, 1 open, 3 localization -== 01.06 below_rowans_trigger (costs: town) +== 01.06 up_jubilifes_road (costs: town) from: Route203 (55, 9) facing west (tile) - target: JubilifeCity (47, 8) facing north (tile) + target: JubilifeCity (41, 8) facing north (tile) start candidates: Route 203 (55, 9) 1. south 10 (to wall) -> Route 203 (55, 19) 2. west 17 (to wall) -> Route 203 (38, 19) 3. north 1 (open) -> Route 203 (38, 18) - 4. west 57 (open) -> Jubilife City (44, 22) - 5. north 14 (to wall) -> Jubilife City (44, 8) - 6. east 3 (to wall) -> Jubilife City (47, 8) - totals: 6 legs, 5 turns, 2 open, 0 localization + 4. west 60 (open) -> Jubilife City (41, 22) + 5. north 14 (to wall) -> Jubilife City (41, 8) + totals: 5 legs, 4 turns, 2 open, 0 localization + +== 01.06 below_rowans_trigger (costs: town) + from: JubilifeCity (41, 8) facing north (tile) + target: JubilifeCity (47, 8) facing north (tile) + start candidates: Jubilife City (41, 8) + 1. east 6 (to wall) -> Jubilife City (47, 8) + totals: 1 legs, 0 turns, 0 open, 0 localization == 01.08 below_the_ravaged_path (costs: town) from: JubilifeCity (44, 5) facing west (tile) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 6e2cf3fbfd..e70457ec8c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -901,8 +901,16 @@ std::vector to_floaroma(){ row("01.06", "Route 203 to Jubilife", out_of_oreburgh_gate(), { // Trainers who saw us going east in 01.02 are beaten; any other // sees us here and is fought (route_203_trainer_sights()). - route("below_rowans_trigger", below_rowans_trigger(), - "down Route 203 (its ledges only south), west along it into Jubilife's street, north up the road", "town"), + // Up the road's west column 41 to its corner (41, 8) first: + // from (41, 22), or (42, 22) where a wild battle in the grass + // cuts the long leg west a tile short, the walls bring us there. + // One route to the trigger turned north at column 44: such a + // battle left it on (44, 22) or (45, 22), and column 45 has no + // wall up the road, nor a way round the Ace Trainer who wanders + // (45..47, 21) (fault sweep). + route("up_jubilifes_road", at(JUBILIFE, 41, 8, NORTH), + "down Route 203 (its ledges only south), west along it into Jubilife's street, north up the road's west column", "town"), + route("below_rowans_trigger", below_rowans_trigger(), "east along row 8 to the sign's wall", "town"), }), rowan_and_the_grunts(), row("01.08", "Jubilife to the Ravaged Path", after_the_grunts(), { diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp index 9de636f82d..a38b111cf7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp @@ -86,9 +86,6 @@ const char* LAST_ROW = "01.11"; // Sweeps the program fails today, by test name, with the likely fix. const std::map KNOWN_FAILING{ - {"PokemonBDSP::AutoStory - Fault sweep: 01.06, wild battles on every grass pass", - "below_rowans_trigger's open leg west 57: a battle in its grass leaves it on Jubilife's (44, 22) or (45, 22), " - "from which the Ace Trainer's (45..47, 21) leaves no plan: end the long leg on a column both of whose candidates clip north to row 8"}, }; // Scenes whose end the console has proven, by step name: the sweep leaves From 246eb21b615249bb47890acd4a93dbd56aa960a1 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 17:46:46 -0800 Subject: [PATCH 112/166] BDSP AutoStory sim: Mom's call on (6, 9) and early scenes, as tests Console B (lab-B 2026-11-09 17:29): Mom's call fired at the end of 00.04's walk west along row 9 onto (6, 9), the walk's unknown-trainer handler pressed it through with B, the step south went out of the door and moms_hat waited 120 s for a fade. The sim now fires her call on (6, 9), notes scenes a walk fights as a trainer's, and forgets a warp from an earlier step. New failure cases for the old and new walk, and a fault sweep that starts the scene of each scene step after a route on that route's end. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- ...PokemonBDSP_AutoStory_FaultSweep_Tests.cpp | 43 ++++++++++++++ .../PokemonBDSP_AutoStory_GridSim.cpp | 3 + .../PokemonBDSP_AutoStory_GridSim.h | 10 ++++ .../PokemonBDSP_AutoStory_OldStorySteps.cpp | 12 ++++ .../PokemonBDSP_AutoStory_OldStorySteps.h | 7 +++ ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 56 +++++++++++++++++++ .../PokemonBDSP_AutoStory_StorySim.cpp | 49 +++++++++++++++- .../PokemonBDSP_AutoStory_StorySim.h | 20 +++++++ 8 files changed, 199 insertions(+), 1 deletion(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp index a38b111cf7..4d10cef347 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp @@ -17,6 +17,11 @@ * each 8 grass tiles (00.04, lab-B 2026-11-09 16:14: four in a row on * Route 201, each replan back through the grass, "too many plans"). * SimWorldKnobs::grass. One variant a row: the whole row so. + * - SCENE_EARLY: a scene starts early, on the last tiles of the route walk + * before its step: its trigger lies on the way (00.04's Mom's call on + * (6, 9), lab-B 2026-11-09 17:29: the walk took it for a trainer and + * pressed through it). A variant also fails when the walk fights it. + * SimWorldKnobs::scene_at_walk_end. * * Missed and short fades are swept by SimFailureCases_Tests (every single * missed fade, banner and fade hold). @@ -30,6 +35,7 @@ * */ +#include #include #include #include @@ -63,6 +69,7 @@ enum class FaultClass{ SCENE_END_POSE, BATTLE_OPENING, GRASS_BATTLES, + SCENE_EARLY, // Not swept yet: the measured movement table's lost taps (#293). LOST_TAP, }; @@ -74,6 +81,8 @@ const char* fault_class_name(FaultClass fault){ return "battle opening at step start"; case FaultClass::GRASS_BATTLES: return "wild battles on every grass pass"; + case FaultClass::SCENE_EARLY: + return "scene starts during the walk before it"; case FaultClass::LOST_TAP: return "lost tap"; } @@ -301,6 +310,37 @@ UnitTestResult sweep_grass_battles(Logger& logger, const StoryCheckpoint& row){ return sweep_result(logger, FaultClass::GRASS_BATTLES, row.id, 1, failures); } +// Row `row` with the scene of each scene step after a route walk starting +// on that walk's target, one at a time. +UnitTestResult sweep_scene_early(Logger& logger, const StoryCheckpoint& row){ + std::vector failures; + size_t variants = 0; + for (size_t c = 1; c < row.steps.size(); c++){ + const StoryStep& walk = row.steps[c - 1]; + if (row.steps[c].kind != StoryStepKind::MASH || walk.kind != StoryStepKind::ROUTE){ + continue; + } + SimWorldKnobs knobs; + knobs.scene_at_walk_end = [id = row.id, name = walk.name](const std::string& r, const std::string& s){ + return r == id && s == name; + }; + variants++; + SimExecutor executor(logger, {.fade = {}, .banner = {}}, std::move(knobs)); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = row.id, .to = row.id}); + const SimRun& run = executor.result(); + const std::string early = "early scene after " + walk.name; + const bool fought = std::any_of(run.scenes_fought.begin(), run.scenes_fought.end(), [&](const std::string& scene){ + return scene.ends_with(early); + }); + if (!report.completed){ + failures.push_back({row.steps[c].name, "starts on " + walk.name + "'s end", std::format("stopped in {}: {}", run.failed_step, run.error)}); + }else if (fought){ + failures.push_back({row.steps[c].name, "starts on " + walk.name + "'s end", "the walk fought it as a trainer's"}); + } + } + return sweep_result(logger, FaultClass::SCENE_EARLY, row.id, variants, failures); +} + // A fault class swept over row `row` (empty in FAULT_SWEEP_CASES: each // row from FIRST_ROW to LAST_ROW). struct FaultSweepInput{ @@ -364,6 +404,8 @@ class Test_AutoStoryFaultSweep : public UnitTest{ return sweep_battle_opening(logger, m_row); case FaultClass::GRASS_BATTLES: return sweep_grass_battles(logger, m_row); + case FaultClass::SCENE_EARLY: + return sweep_scene_early(logger, m_row); case FaultClass::LOST_TAP: break; } @@ -380,6 +422,7 @@ const FaultSweepCase FAULT_SWEEP_CASES[] = { {.input = {.fault = FaultClass::SCENE_END_POSE}, .expectation = {}}, {.input = {.fault = FaultClass::BATTLE_OPENING}, .expectation = {}}, {.input = {.fault = FaultClass::GRASS_BATTLES}, .expectation = {}}, + {.input = {.fault = FaultClass::SCENE_EARLY}, .expectation = {}}, }; void add_tests_AutoStory_FaultSweep(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp index d0d3abe9ec..f6837d4ee2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -140,6 +140,7 @@ void GridSim::place(SimWorld world, const TilePos& start, std::optional GridSim::arrive(){ if (!fired && std::find(trigger.tiles.begin(), trigger.tiles.end(), tile) != trigger.tiles.end()){ m_player.fired.push_back(trigger.name); m_player.dialog = true; + m_player.scene = trigger.name; return SimStop::DIALOG; } } @@ -364,6 +366,7 @@ void GridSim::end_dialogue(){ m_player.fought.push_back(*m_player.trainer); } m_player.trainer.reset(); + m_player.scene.reset(); m_player.dialog = false; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h index a0beab03c8..d6ec6eafff 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h @@ -118,6 +118,8 @@ struct SimPlayer{ bool dialog = false; // The trainer whose dialogue is open, if one is. std::optional trainer; + // The scene (SimTrigger) whose dialogue is open, if one is. + std::optional scene; // The door the last warp stepped onto. std::optional warped; std::vector fought = {}; @@ -147,6 +149,14 @@ class GridSim{ void end_dialogue(); // Puts the player on `start` of `world`: after a warp or a scene. void place(SimWorld world, const Pokemon::TilePos& start, std::optional facing); + // A scene's trigger on the world the player is on, from now on. + void add_trigger(SimTrigger trigger){ + m_world.triggers.push_back(std::move(trigger)); + } + // A new step starts: the warp a step before stepped onto is not this one's. + void forget_warp(){ + m_player.warped.reset(); + } const SimPlayer& player() const{ return m_player; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp index a508c54be5..e4020d552f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp @@ -73,6 +73,18 @@ StoryStep old_coal_room_crate_cut(){ return step; } +std::vector old_round_mom_to_the_mat(){ + StoryStep around; + around.kind = StoryStepKind::ROUTE; + around.name = "around_mom"; + around.target = Pokemon::tile_pose("PlayerHouse1F", {TilePos{6, 9}}, Direction::SOUTH); + StoryStep step; + step.kind = StoryStepKind::STEP; + step.name = "to_moms_call"; + step.direction = Direction::SOUTH; + return {around, step}; +} + StoryStep old_tap_into_the_gate(){ StoryStep step; step.kind = StoryStepKind::STEP; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h index 7c4608e445..8913f73f17 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h @@ -12,6 +12,7 @@ #define PokemonAutomation_PokemonBDSP_AutoStory_OldStorySteps_H #include +#include #include "Pokemon/AutoStory/Pokemon_StorySteps.h" namespace PokemonAutomation{ @@ -51,6 +52,12 @@ Pokemon::StoryStep old_tap_into_the_gate(); // below the old man (lab-B 2026-11-08 18:41). Pokemon::StoryStep old_west_along_the_field(); +// 00.04's old walk round Mom to (6, 9) and step south onto the mat (6, 10) +// for her call: her call fired on (6, 9) at the walk's end, the walk took +// it for a trainer and pressed through it, the step went out of the door, +// and her hat scene saw no fade (lab-B 2026-11-09 17:29). +std::vector old_round_mom_to_the_mat(); + } // namespace PokemonBDSP diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp index 5f0cc74f2e..c38954a49e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -29,6 +29,7 @@ #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_OldStorySteps.h" #include "PokemonBDSP_AutoStory_StorySim.h" #include "PokemonBDSP_AutoStory_SimFailureCases_Tests.h" @@ -462,6 +463,59 @@ std::string ledge_walk_in_grass(Logger& logger, const std::set& ski return run_case(logger, "00.04", "00.04", {.fade = {}, .banner = {}}, route_201_grass(), rows); } +// The scenes a run's walks fought as trainers', or "none". +std::string fought(const SimRun& run){ + std::string out; + for (const std::string& scene : run.scenes_fought){ + out += (out.empty() ? "" : "; ") + scene; + } + return out.empty() ? "none" : out; +} +// 00.04: Mom's call after her heal fires on (6, 9), above the mat +// (lab-B 2026-11-09 17:29). The walk into it ends in her call, which her +// hat scene's step plays to the fade out with her; no walk fights it. +UnitTestResult moms_call_above_the_mat(Logger& logger){ + SimExecutor executor(logger, {.fade = {}, .banner = {}}, {}); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = "00.04", .to = "00.04"}); + if (!report.completed){ + return std::format("stopped in {}: {}", executor.result().failed_step, executor.result().error); + } + if (!executor.result().scenes_fought.empty()){ + return "a walk fought a scene: " + fought(executor.result()); + } + return true; +} +// 00.04's old walk round Mom to (6, 9) and step onto the mat, as on the +// console: the walk fights her call, the step goes out of the door, and +// her hat scene sees no fade. +UnitTestResult old_walk_fights_moms_call(Logger& logger){ + std::vector rows = story_checkpoints(); + for (StoryCheckpoint& checkpoint : rows){ + if (checkpoint.id != "00.04"){ + continue; + } + std::vector steps; + for (StoryStep& step : checkpoint.steps){ + if (step.name != "into_moms_call"){ + steps.push_back(std::move(step)); + continue; + } + for (StoryStep& old : old_round_mom_to_the_mat()){ + steps.push_back(std::move(old)); + } + } + checkpoint.steps = std::move(steps); + } + SimExecutor executor(logger, {.fade = {}, .banner = {}}, {}); + run_rows_on(executor, logger, {.from = "00.04", .to = "00.04"}, rows); + const SimRun& run = executor.result(); + if (run.failed_step != "00.04 moms_hat" || run.scenes_fought.empty()){ + return std::format("the old walk no longer goes wrong as on the console: failed in \"{}\" ({}), scenes fought: {}", + run.failed_step, run.error, fought(run)); + } + return true; +} + struct FailureCaseInput{ std::string name; std::function body; @@ -544,6 +598,8 @@ const FailureCase AUTO_STORY_FAILURE_CASES[] = { {.input = {"00.03 out of the house from (6, 8), where Rowan's scene ends, and from a column west", home_from_each_scene_end}, .expectation = {}}, {.input = {"00.03 the walk into Rowan's scene routes onto his row and stops on his trigger mid-run", rowans_scene_from_each_start}, .expectation = {}}, {.input = {"00.03 the walk into Sandgem stops on Dawn's trigger mid-run", dawns_scene_mid_run}, .expectation = {}}, + {.input = {"00.04 Mom's call fires above the mat, on (6, 9): the walk ends in it, her hat scene plays it (lab-B 2026-11-09 17:29)", moms_call_above_the_mat}, .expectation = {}}, + {.input = {"00.04 the old walk round Mom fights her call on (6, 9); her hat scene then sees no fade (lab-B 2026-11-09 17:29)", old_walk_fights_moms_call}, .expectation = {}}, {.input = {"00.04 to the ledge column with a wild battle on each pass through Route 201's grass (lab-B 2026-11-09 16:14)", [](Logger& logger){ return passes(ledge_walk_in_grass(logger, {})); }}, .expectation = {}}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index d2dfa710aa..8577a09dea 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -340,8 +340,32 @@ std::optional var_state(const CoordEvent& event){ return std::nullopt; } +// A coord event the console showed on other tiles than its map's. +struct ConsoleTrigger{ + std::string map; + std::string name; + std::vector tiles; +}; +std::vector console_triggers(){ + return { + // Mom's call after her heal fires on (6, 9), above the mat: a walk + // west along row 9 stopped in it there with all 4 taps moved + // (lab-B 2026-11-09 17:29), and the step south from (6, 9) after + // it went out of the door, where the same step on 2026-11-04 12:20, + // pressed inside her scene, moved nobody. The map has the mat (6, 10) + // (r45, r46: her line came after that step was pressed). + {.map = "PlayerHouse1F", .name = "moms_call", .tiles = {{6, 9}}}, + }; +} + RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ - return {.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; + RowTrigger out{.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; + for (const ConsoleTrigger& seen : console_triggers()){ + if (seen.map == map && seen.name == event.name){ + out.trigger.tiles = seen.tiles; + } + } + return out; } } // namespace @@ -528,6 +552,21 @@ bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ return true; } +void SimExecutor::start_scene_at_end(const StoryStep& step){ + const std::optional& end = step.kind == StoryStepKind::ROUTE ? step.target : step.pose_after; + if (!end){ + return; + } + SimTrigger trigger{.name = "early scene after " + step.name, .tiles = {}}; + for (const TilePos& tile : Pokemon::tiles_of(*end)){ + try{ + trigger.tiles.push_back(story_to_world(m_sim.world(), end->map, tile)); + }catch (const InternalProgramError&){} + } + m_logger.log(std::format("[{}] {}: the next scene starts on its end, {}.", m_row, step.name, Pokemon::to_string(*end))); + m_sim.add_trigger(std::move(trigger)); +} + void SimExecutor::land(const std::string& step){ const auto lands = m_knobs.lands.find(step); if (lands == m_knobs.lands.end()){ @@ -744,6 +783,9 @@ Outcome SimExecutor::run_step(RunState& state, const StoryStep& step){ m_passed_over = true; return Pokemon::outcome_ok(); } + if (walks && m_knobs.scene_at_walk_end && m_knobs.scene_at_walk_end(m_row, step.name)){ + start_scene_at_end(step); + } return Pokemon::TableExecutor::run(state, step); } @@ -762,6 +804,7 @@ Outcome SimExecutor::run(RunState& state, const StoryStep& step){ Outcome outcome; m_passed_over = false; m_step = step.name; + m_sim.forget_warp(); show_before(step); try{ outcome = run_step(state, step); @@ -794,6 +837,10 @@ Outcome SimExecutor::run(RunState& state, const StoryStep& step){ m_result.error = m_row + " " + Pokemon::to_string(outcome); m_result.failed_step = m_row + " " + step.name; } + for (const std::string& scene : m_io.take_scenes_fought()){ + m_logger.log(std::format("[{}] {}: the walk fought {}'s dialogue as a trainer's.", m_row, step.name, scene)); + m_result.scenes_fought.push_back(std::format("{} {}: {}", m_row, step.name, scene)); + } m_result.world = m_placed ? &m_sim.world() : nullptr; m_result.end = nearest_tile(m_sim.player().pos); m_ran.insert(step.name); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index 6583ac0aeb..fb3c70664e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -162,6 +162,10 @@ struct SimWorldKnobs{ std::map lands = {}; // Wild battles in tall grass on every pass (SimGrassBattles); none unset. SimGrassBattles grass = {}; + // Whether the scene after row `row`'s walk `step` starts early, on the + // walk's last tiles (its target): its trigger lies on the way, so the + // walk runs into it (00.04's Mom's call on (6, 9), lab-B 2026-11-09 17:29). + std::function scene_at_walk_end = nullptr; }; // The walker's RouteIO on the story simulation, with SimWorldKnobs' slides @@ -250,6 +254,10 @@ struct SimRun{ // Where the player stood after the last step, if placed. const StoryWorld* world = nullptr; Pokemon::TilePos end; + // Scenes a walk took for a trainer's and pressed through, as + // "row step: scene" (the console's unknown-trainer handler, lab-B + // 2026-11-09 17:29: Mom's call, then her scene's fade missed). + std::vector scenes_fought = {}; }; // StoryStepIO on the simulation. A walk through a door or a cave mouth @@ -273,9 +281,18 @@ class SimStoryStepIO : public StoryStepIO{ virtual RouteIO& route() override{ return m_route; } + // A scene's dialogue fought as a trainer's is pressed through under the + // walk, not its own step: noted (take_scenes_fought()). virtual void fight(const std::string&) override{ + if (m_sim.player().scene){ + m_scenes_fought.push_back(*m_sim.player().scene); + } m_sim.end_dialogue(); } + // The scenes fought since the last call. + std::vector take_scenes_fought(){ + return std::exchange(m_scenes_fought, {}); + } virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; // A door's fade stops the run; with the fade missed, the run goes on @@ -339,6 +356,7 @@ class SimStoryStepIO : public StoryStepIO{ const SimWorldKnobs& m_knobs; std::function m_far_side; const std::string& m_step; + std::vector m_scenes_fought; }; // A scene's trigger the simulation fires from row `row` on, once the step @@ -448,6 +466,8 @@ class SimExecutor : public Pokemon::TableExecutor{ SimWorld setup(const StoryWorld* world) const; void arm(const std::string& after); bool sync(const Pokemon::Pose& pose, const StoryWorld* on = nullptr); + // Puts a trigger on walk `step`'s last tiles (SimWorldKnobs::scene_at_walk_end). + void start_scene_at_end(const Pokemon::StoryStep& step); // Puts the player where SimWorldKnobs::lands says `step` leaves them, if it says. void land(const std::string& step); bool cross(); From 422aa34e2c0147b6b3d9971d2fdd6ce12346c407 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 17:49:38 -0800 Subject: [PATCH 113/166] BDSP AutoStory: 00.04 runs into Mom's call on (6, 9); a walk hands an early scene to its step Mom's call fires on (6, 9), above the mat (lab-B 2026-11-09 17:29). The walk round her now stops on (7, 9) and runs west into her call, which moms_hat plays; to_moms_call is gone. A route followed by a scene step no longer presses a dialogue no trainer explains through as an unknown trainer's: the walk ends with it open and the scene's step plays it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryExecutor.cpp | 2 +- .../PokemonBDSP_AutoStory_StoryTable.cpp | 9 ++++-- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 14 ++++++-- .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 11 +++++-- .../PokemonBDSP_AutoStory_StorySim.h | 2 +- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 32 ++++++++++++++++--- .../PokemonBDSP_AutoStory_PlannedRoute.h | 8 +++++ 7 files changed, 64 insertions(+), 14 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp index 8740e87d74..b5f3c37c78 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp @@ -189,7 +189,7 @@ StoryInterruptActions StoryExecutor::console_interrupt_actions(){ void StoryExecutor::begin_attempt(const Pokemon::StoryCheckpoint& data){ m_checkpoint = data.id; - m_walks.begin_attempt(data.id); + m_walks.begin_attempt(data.id, data.steps); } Outcome StoryExecutor::new_game(RunState&, const StoryStep&){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index e70457ec8c..db74b097d8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -466,8 +466,13 @@ std::vector moms_heal_and_hat(){ anchored(to_walls("into_the_east_corner", { {.direction = NORTH, .tiles = 4}, {.direction = EAST, .tiles = 6}, {.direction = SOUTH, .tiles = 4}, }, "north, east and south to the walls, into the room's east corner"), at(HOME, 11, 8, SOUTH)), - route("around_mom", at(HOME, 6, 9, SOUTH), "round Mom to (6, 9) above the door"), - step_into("to_moms_call", SOUTH, "onto the door mat (6, 10), triggering Mom's call"), + // Her call fires on (6, 9), above the mat, not on the mat: a walk + // west along row 9 stopped in it there, all 4 taps moved (lab-B + // 2026-11-09 17:29); the step south from (6, 9) went out of the door + // after it, where on 2026-11-04 the same step inside her call did + // not. So the route stops a tile east and runs on into her call. + route_into_scene("into_moms_call", at(HOME, 7, 9, WEST), {.direction = WEST, .tiles = 1}, + "round Mom to (7, 9), then west until her call stops us on (6, 9)"), scene("moms_hat", at(TWINLEAF, 19, 22, EAST), "Mom's hat; she walks out with us"), // Her scene's end is a guess too, and Mom may stand east of us: west // along the row to Twinleaf's west wall, column 6, from either row the diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index 0937fc153c..37a27c4756 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -113,12 +113,18 @@ std::optional measured_ends(const Pose& from, const StoryStep& step){ return Pokemon::tile_pose(from.map, at, step.legs.back().direction); } -void StoryWalkSteps::begin_attempt(const std::string& row){ +void StoryWalkSteps::begin_attempt(const std::string& row, const std::vector& steps){ m_row = row; // A row starts from its save: after the shoes' row, the save has them. m_can_run = row > std::string(RUNNING_SHOES_ROW); m_trainers.clear(); m_warp = {}; + m_scene_next.clear(); + for (size_t c = 1; c < steps.size(); c++){ + if (steps[c].kind == Pokemon::StoryStepKind::MASH){ + m_scene_next.insert(steps[c - 1].name); + } + } } void StoryWalkSteps::turn(Direction direction){ @@ -155,11 +161,12 @@ Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep }; const RouteWalkPlan plan{ [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }, - label_of(step), {}, *costs, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK + label_of(step), {}, *costs, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK, m_scene_next.contains(step.name) }; RouteEnd end = walk_route_to_warp(m_io.route(), *maps, start, trainers, plan); sights = std::move(trainers.sights); m_warp = std::move(end.warp); + m_scene_started = end.scene; std::vector local; for (const TilePos& pos : end.tiles){ const std::optional tile = story_to_local(*maps, goal.map, pos); @@ -177,7 +184,8 @@ Outcome StoryWalkSteps::route(RunState& state, const StoryStep& step){ return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); } const Pose end = walk_to(state.pose, *step.target, step); - if (step.legs.empty()){ + // The next step's scene started on the way: its step plays it. + if (step.legs.empty() || m_scene_started){ return Pokemon::outcome_ok(end); } return run_to_dialogue(step); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index d340d36e80..09ab7b1118 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include "Pokemon/AutoStory/Pokemon_StorySteps.h" @@ -64,8 +65,10 @@ class StoryWalkSteps{ {} // A new attempt of the row `row`: every trainer can see us again, and - // the pace is the row's save's (a run after the Running Shoes). - void begin_attempt(const std::string& row); + // the pace is the row's save's (a run after the Running Shoes). With + // the row's `steps`, a route followed by a scene hands a dialogue that + // starts on the way to that scene (RouteWalkPlan::scene_next). + void begin_attempt(const std::string& row, const std::vector& steps = {}); // Whether the player has the Running Shoes: the pace routes are timed at. bool can_run() const{ return m_can_run; @@ -113,6 +116,10 @@ class StoryWalkSteps{ // The warp the last route ran on through at its end (walk_route_to_warp()), // for the step after it, which goes through that warp. WarpSeen m_warp; + // The row's steps followed by a scene (begin_attempt()). + std::set m_scene_next; + // The last route ended in the next step's scene (RouteEnd::scene). + bool m_scene_started = false; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index fb3c70664e..3fd441eed5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -422,7 +422,7 @@ class SimExecutor : public Pokemon::TableExecutor{ m_ran.clear(); m_astray = false; m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); - m_walks.begin_attempt(data.id); + m_walks.begin_attempt(data.id, data.steps); arm(""); } virtual Pokemon::Outcome run(Pokemon::RunState& state, const Pokemon::StoryStep& step) override; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index 5751df8e6a..42eb7353e8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -180,6 +180,7 @@ enum class LegNext{ NEXT_LEG, REPLAN, ARRIVED_EARLY, // through a warp at the leg's end (walk_route_to_warp()) + SCENE, // the next step's scene started (RouteWalkPlan::scene_next) }; // How far past a leg's end a walk that ran on may have gone. constexpr size_t WARP_SLIDE_TILES = 2; @@ -258,6 +259,8 @@ class RouteWalker{ void check_banners(LegWalk& walk); LegNext after_leg(LegWalk& walk); std::vector watching_trainers(const std::vector>& paths) const; + std::vector stopped_anywhere(const LegWalk& walk, const std::vector>& paths) const; + LegNext scene_started(const LegWalk& walk, const std::vector>& paths); LegNext unknown_trainer(LegWalk& walk, const std::vector>& paths); LegNext known_trainer(LegWalk& walk, const std::vector>& paths, const std::vector& watching); @@ -302,7 +305,8 @@ RouteEnd RouteWalker::run(std::vector from){ next = walk_leg(legs[number - 1], number, legs.size()); } if (next != LegNext::REPLAN){ - return {next == LegNext::ARRIVED_EARLY ? m_from : arrive(), m_warp}; + const bool early = next == LegNext::ARRIVED_EARLY || next == LegNext::SCENE; + return {early ? m_from : arrive(), m_warp, next == LegNext::SCENE}; } } fail(m_io, m_plan.label + ": too many plans."); @@ -706,6 +710,9 @@ LegNext RouteWalker::after_leg(LegWalk& walk){ log_leg_done(m_io, m_maps, m_plan.label, walk.planned, walk.result.wild_battles); return LegNext::NEXT_LEG; } + if (watching.empty() && m_plan.scene_next){ + return scene_started(walk, paths); + } if (watching.empty()){ return unknown_trainer(walk, paths); } @@ -729,9 +736,9 @@ std::vector RouteWalker::watching_trainers(const std::vector>& paths){ +// Where a leg a dialogue stopped may have left us: where its moved taps +// end, or anywhere on its paths. +std::vector RouteWalker::stopped_anywhere(const LegWalk& walk, const std::vector>& paths) const{ std::vector anywhere; const size_t moved = std::min(walk.planned.leg.tiles, walk.result.moved_chunks + walk.turn_moved); if (walk.result.stop == WalkStop::DIALOG && moved > 0){ @@ -748,7 +755,22 @@ LegNext RouteWalker::unknown_trainer(LegWalk& walk, const std::vector>& paths){ + m_from = stopped_anywhere(walk, paths); + m_io.note("[Route] " + walk.label + ": the next step's scene started on the way, at " + + describe(m_maps, m_from) + "; handing over.", RouteNote::WARNING); + return LegNext::SCENE; +} + +// A trainer the map does not have. Fight, then plan again from anywhere +// the leg could have stopped. +LegNext RouteWalker::unknown_trainer(LegWalk& walk, const std::vector>& paths){ + std::vector anywhere = stopped_anywhere(walk, paths); // A scene the map lacks (r14: Barry's Route 201 warning, then the row that // pulls us back) would replan into it forever: give up after the second. if (++m_unexplained_talks > 2){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h index 777019cfdd..29d9692969 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h @@ -50,6 +50,11 @@ struct RouteWalkPlan{ RobustPlanCosts costs = route_plan_costs(); // The pace of legs to a wall, which their tile counts are timed by. MoveSpeed speed = MoveSpeed::WALK; + // The story's next step is a scene: a dialogue no trainer explains is + // that scene, started early by a trigger on the way (00.04's Mom's + // call, lab-B 2026-11-09 17:29). The walk ends there with it open, + // for the scene's step, instead of pressing through it as a trainer's. + bool scene_next = false; }; // Walks from any of the world tiles `from` of `maps` until every tile the @@ -76,6 +81,9 @@ std::vector walk_route( struct RouteEnd{ std::vector tiles; WarpSeen warp = {}; + // The next step's scene started on the way (RouteWalkPlan::scene_next): + // its dialogue is open, and `tiles` are where the walk may have stopped. + bool scene = false; }; // walk_route(), but a fade on a leg with a warp at most a tile or two past // its end ends the walk there, as arrived early: the walk ran on onto the From 3e4ea9871407fc431883ab7e4834ec4c2b6a6239 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 17:52:52 -0800 Subject: [PATCH 114/166] BDSP AutoStory sim: a story variable's new value disarms its old triggers Route 201's row 19 pull-back (VAR_FOLLOWER_RIVAL_STATE 1) stayed armed into 00.03, where the variable is 2: Dawn's walk ran into it in the sim only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StorySim.cpp | 22 ++++++++++++++----- .../PokemonBDSP_AutoStory_StorySim.h | 4 +++- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index 8577a09dea..e22a8700d0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -359,7 +359,10 @@ std::vector console_triggers(){ } RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ - RowTrigger out{.row = state.row, .after = state.after, .map = map, .trigger = {.name = event.name, .tiles = event.tiles}}; + RowTrigger out{ + .row = state.row, .after = state.after, .map = map, + .trigger = {.name = event.name, .tiles = event.tiles}, .var = event.var, + }; for (const ConsoleTrigger& seen : console_triggers()){ if (seen.map == map && seen.name == event.name){ out.trigger.tiles = seen.tiles; @@ -513,15 +516,24 @@ std::vector SimExecutor::wanderers(const StoryWorld& world) const{ return out; } -// Arms the triggers of this row that start after `after`. +// Arms the triggers of this row that start after `after`. A variable holds +// one value: the triggers armed for its value before are disarmed (Route +// 201's row 19 pulls back only after Barry's warning, not in 00.03, where +// the variable has moved on). void SimExecutor::arm(const std::string& after){ - size_t armed = 0; + std::vector now; for (const RowTrigger& trigger : story_triggers()){ if (trigger.row == m_row && trigger.after == after){ - m_armed.push_back(trigger); - armed++; + now.push_back(trigger); } } + for (const RowTrigger& trigger : now){ + std::erase_if(m_armed, [&](const RowTrigger& old){ + return old.var == trigger.var; + }); + } + m_armed.insert(m_armed.end(), now.begin(), now.end()); + const size_t armed = now.size(); const SimPlayer& player = m_sim.player(); if (armed > 0 && m_placed && on_grid(player.pos) && !player.dialog){ m_sim.place(setup(&m_sim.world()), nearest_tile(player.pos), player.facing); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index 3fd441eed5..8e34aed960 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -360,12 +360,14 @@ class SimStoryStepIO : public StoryStepIO{ }; // A scene's trigger the simulation fires from row `row` on, once the step -// `after` has run ("" from the row's start), on `map`'s `tiles`. +// `after` has run ("" from the row's start), on `map`'s `tiles`, while its +// story variable `var` holds the value it waits for. struct RowTrigger{ std::string row; std::string after; std::string map; SimTrigger trigger; + std::string var = {}; }; // When a story variable holds the value its coord events wait for: from From ac497f76dff2aedb77b8c4197bf57d3276b872de Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 17:56:42 -0800 Subject: [PATCH 115/166] BDSP AutoStory sim: the early-scene sweep covers a route, a step onto the trigger, then the scene Also the route plans golden for into_moms_call. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Data/route_plans.golden.txt | 6 ++-- ...PokemonBDSP_AutoStory_FaultSweep_Tests.cpp | 29 +++++++++++++++---- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt index 43c45d0b61..6a1a41556b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt @@ -125,13 +125,13 @@ anchor); 0 from one start tile. 1. north 1 (open) -> PlayerHouse1F (6, 8) totals: 1 legs, 0 turns, 1 open, 0 localization -== 00.04 around_mom (costs: route) +== 00.04 into_moms_call (costs: route) from: PlayerHouse1F (11, 8) facing south (tile) - target: PlayerHouse1F (6, 9) facing south (tile) + target: PlayerHouse1F (7, 9) facing west (tile) start candidates: PlayerHouse1F (11, 8) 1. west 1 (open) -> PlayerHouse1F (10, 8) 2. south 1 (open) -> PlayerHouse1F (10, 9) - 3. west 4 (open) -> PlayerHouse1F (6, 9) + 3. west 3 (open) -> PlayerHouse1F (7, 9) totals: 3 legs, 2 turns, 3 open, 0 localization == 00.04 short_of_the_catch_tutorial (costs: route) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp index 4d10cef347..02dac8a3bb 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp @@ -18,7 +18,8 @@ * Route 201, each replan back through the grass, "too many plans"). * SimWorldKnobs::grass. One variant a row: the whole row so. * - SCENE_EARLY: a scene starts early, on the last tiles of the route walk - * before its step: its trigger lies on the way (00.04's Mom's call on + * before its step, or before the plain step onto its trigger: the + * trigger lies on the way, not where the decomp has it (00.04's Mom's call on * (6, 9), lab-B 2026-11-09 17:29: the walk took it for a trainer and * pressed through it). A variant also fails when the walk fights it. * SimWorldKnobs::scene_at_walk_end. @@ -310,16 +311,34 @@ UnitTestResult sweep_grass_battles(Logger& logger, const StoryCheckpoint& row){ return sweep_result(logger, FaultClass::GRASS_BATTLES, row.id, 1, failures); } -// Row `row` with the scene of each scene step after a route walk starting -// on that walk's target, one at a time. +// The route before scene step `c` of `steps`, right before it or before +// the plain step onto its trigger; none if there is none. +std::optional route_before_scene(const std::vector& steps, size_t c){ + if (steps[c].kind != StoryStepKind::MASH || c == 0){ + return std::nullopt; + } + if (steps[c - 1].kind == StoryStepKind::ROUTE){ + return c - 1; + } + const StoryStep& step = steps[c - 1]; + const bool onto_trigger = step.kind == StoryStepKind::STEP && step.variant.empty() && !step.pose_after; + if (onto_trigger && c >= 2 && steps[c - 2].kind == StoryStepKind::ROUTE){ + return c - 2; + } + return std::nullopt; +} + +// Row `row` with the scene of each scene step after a route starting on +// that route's target, one at a time. UnitTestResult sweep_scene_early(Logger& logger, const StoryCheckpoint& row){ std::vector failures; size_t variants = 0; for (size_t c = 1; c < row.steps.size(); c++){ - const StoryStep& walk = row.steps[c - 1]; - if (row.steps[c].kind != StoryStepKind::MASH || walk.kind != StoryStepKind::ROUTE){ + const std::optional w = route_before_scene(row.steps, c); + if (!w){ continue; } + const StoryStep& walk = row.steps[*w]; SimWorldKnobs knobs; knobs.scene_at_walk_end = [id = row.id, name = walk.name](const std::string& r, const std::string& s){ return r == id && s == name; From eb60b276eace3589d910933672adb257abc9307c Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 17:57:19 -0800 Subject: [PATCH 116/166] BDSP AutoStory: a route before a step onto a scene's trigger hands an early scene over too The step onto the trigger is then not taken: the scene holds us where it started (00.04 on 2026-11-04: that step, pressed in Mom's call, moved nobody). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 35 +++++++++++++++++-- .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 11 +++--- 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index 37a27c4756..8bca01481a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -120,10 +120,25 @@ void StoryWalkSteps::begin_attempt(const std::string& row, const std::vector= 2 && onto_trigger(steps[c - 1]) && route(steps[c - 2])){ + m_scene_next.insert(steps[c - 2].name); + } } } @@ -166,7 +181,7 @@ Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep RouteEnd end = walk_route_to_warp(m_io.route(), *maps, start, trainers, plan); sights = std::move(trainers.sights); m_warp = std::move(end.warp); - m_scene_started = end.scene; + m_scene_open = end.scene; std::vector local; for (const TilePos& pos : end.tiles){ const std::optional tile = story_to_local(*maps, goal.map, pos); @@ -185,7 +200,7 @@ Outcome StoryWalkSteps::route(RunState& state, const StoryStep& step){ } const Pose end = walk_to(state.pose, *step.target, step); // The next step's scene started on the way: its step plays it. - if (step.legs.empty() || m_scene_started){ + if (step.legs.empty() || m_scene_open){ return Pokemon::outcome_ok(end); } return run_to_dialogue(step); @@ -513,6 +528,7 @@ Outcome StoryWalkSteps::counted_wall(const Pose& from, const StoryStep& step){ Outcome StoryWalkSteps::legs(RunState& state, const StoryStep& step){ m_warp = {}; + m_scene_open = false; if (step.variant == "counted_wall"){ return counted_wall(state.pose, step); } @@ -571,6 +587,17 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ m_io.settle(BUTTON_B, label_of(step), !seen.any(), banner); return Pokemon::outcome_ok(); } + return one_step(state, step); +} + +// A plain D-pad step: onto a scene's trigger, mostly. Not taken when the +// route before ran into that scene already (RouteEnd::scene): it holds us +// where it started. +Outcome StoryWalkSteps::one_step(const RunState& state, const StoryStep& step){ + if (std::exchange(m_scene_open, false)){ + log(std::format("[{}] {}: its scene started on the walk before; no step.", m_row, step.name)); + return Pokemon::outcome_ok(state.pose); + } turn(step.direction); const WalkResult walk = m_io.route().walk_taps(step.direction, 1, step.name); if (walk.wild_battles > 0){ @@ -586,6 +613,7 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ Outcome StoryWalkSteps::talk(RunState& state, const StoryStep& step){ m_warp = {}; + m_scene_open = false; // Face whom we talk to: a route ends facing its last leg, not its goal // (r40 reached Mom facing north). They block the tile, so the tap only turns. if (const std::optional facing = Pokemon::facing_of(state.pose)){ @@ -603,6 +631,7 @@ Outcome StoryWalkSteps::talk(RunState& state, const StoryStep& step){ Outcome StoryWalkSteps::mash(RunState& state, const StoryStep& step){ m_warp = {}; + m_scene_open = false; // The step before may have played the scene already (a door step settles // its arrival scene), so its first line is not required. if (!m_io.route().dialog_within(15000ms, COLOR_CYAN)){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index 09ab7b1118..0e64151fb7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -66,8 +66,9 @@ class StoryWalkSteps{ // A new attempt of the row `row`: every trainer can see us again, and // the pace is the row's save's (a run after the Running Shoes). With - // the row's `steps`, a route followed by a scene hands a dialogue that - // starts on the way to that scene (RouteWalkPlan::scene_next). + // the row's `steps`, a route followed by a scene, or by a plain step onto + // the scene's trigger, hands a dialogue that starts on the way to that + // scene (RouteWalkPlan::scene_next). void begin_attempt(const std::string& row, const std::vector& steps = {}); // Whether the player has the Running Shoes: the pace routes are timed at. bool can_run() const{ @@ -100,6 +101,7 @@ class StoryWalkSteps{ Pokemon::Outcome measured_legs(const Pokemon::Pose& from, const Pokemon::StoryStep& step); Pokemon::Outcome run_to_dialogue(const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_map(const Pokemon::StoryStep& step); + Pokemon::Outcome one_step(const Pokemon::RunState& state, const Pokemon::StoryStep& step); Pokemon::Outcome tap_to_banner(const Pokemon::Pose& from, const Pokemon::StoryStep& step); bool through_already(const Pokemon::StoryStep& step); WarpSeen door_from_beside(const Pokemon::StoryStep& step, const WarpSeen& seen, Milliseconds timeout, const std::string& banner); @@ -118,8 +120,9 @@ class StoryWalkSteps{ WarpSeen m_warp; // The row's steps followed by a scene (begin_attempt()). std::set m_scene_next; - // The last route ended in the next step's scene (RouteEnd::scene). - bool m_scene_started = false; + // The last route ended in the scene of the step after it, or after the + // plain step onto its trigger (RouteEnd::scene); that step is not taken. + bool m_scene_open = false; }; From cb8694c1c3f7165ab5fa0855ae0df3d9d128d21a Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 18:00:30 -0800 Subject: [PATCH 117/166] BDSP AutoStory sim: an early scene spends the trigger next to it; the old Mom walk now hands her call over Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_GridSim.cpp | 1 + .../PokemonBDSP_AutoStory_GridSim.h | 7 +++++- .../PokemonBDSP_AutoStory_OldStorySteps.h | 3 ++- ...onBDSP_AutoStory_SimFailureCases_Tests.cpp | 22 +++++++++++-------- .../PokemonBDSP_AutoStory_StorySim.cpp | 13 +++++++++++ 5 files changed, 35 insertions(+), 11 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp index f6837d4ee2..e752f0f721 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -256,6 +256,7 @@ std::optional GridSim::arrive(){ const bool fired = std::find(m_player.fired.begin(), m_player.fired.end(), trigger.name) != m_player.fired.end(); if (!fired && std::find(trigger.tiles.begin(), trigger.tiles.end(), tile) != trigger.tiles.end()){ m_player.fired.push_back(trigger.name); + m_player.fired.insert(m_player.fired.end(), trigger.spends.begin(), trigger.spends.end()); m_player.dialog = true; m_player.scene = trigger.name; return SimStop::DIALOG; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h index d6ec6eafff..087cf2c981 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h @@ -59,10 +59,12 @@ Pokemon::TilePos nearest_tile(const SimPos& pos); std::string to_string(const SimPos& pos); // A scene that starts when the player steps onto one of `tiles` (a coord -// event): its dialogue opens and the player stops. It fires once. +// event): its dialogue opens and the player stops. It fires once, and +// spends the triggers named in `spends` with it: the same scene's. struct SimTrigger{ std::string name; std::vector tiles; + std::vector spends = {}; }; // Where the simulated player walks: the world (which must outlive the @@ -153,6 +155,9 @@ class GridSim{ void add_trigger(SimTrigger trigger){ m_world.triggers.push_back(std::move(trigger)); } + const std::vector& triggers() const{ + return m_world.triggers; + } // A new step starts: the warp a step before stepped onto is not this one's. void forget_warp(){ m_player.warped.reset(); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h index 8913f73f17..2013ebfcd6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h @@ -55,7 +55,8 @@ Pokemon::StoryStep old_west_along_the_field(); // 00.04's old walk round Mom to (6, 9) and step south onto the mat (6, 10) // for her call: her call fired on (6, 9) at the walk's end, the walk took // it for a trainer and pressed through it, the step went out of the door, -// and her hat scene saw no fade (lab-B 2026-11-09 17:29). +// and her hat scene saw no fade (lab-B 2026-11-09 17:29). The walker now +// hands such a scene to its step; the table runs into her call instead. std::vector old_round_mom_to_the_mat(); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp index c38954a49e..c9d95c3443 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -485,10 +485,12 @@ UnitTestResult moms_call_above_the_mat(Logger& logger){ } return true; } -// 00.04's old walk round Mom to (6, 9) and step onto the mat, as on the -// console: the walk fights her call, the step goes out of the door, and -// her hat scene sees no fade. -UnitTestResult old_walk_fights_moms_call(Logger& logger){ +// 00.04's old walk round Mom to (6, 9) and step onto the mat. On the +// console the walk fought her call, the step went out of the door and her +// hat scene saw no fade. A route before a step onto a scene's trigger now +// hands a scene that starts on the way to the scene's step, and the step +// onto the trigger is not taken. +UnitTestResult old_walk_hands_moms_call_over(Logger& logger){ std::vector rows = story_checkpoints(); for (StoryCheckpoint& checkpoint : rows){ if (checkpoint.id != "00.04"){ @@ -507,11 +509,13 @@ UnitTestResult old_walk_fights_moms_call(Logger& logger){ checkpoint.steps = std::move(steps); } SimExecutor executor(logger, {.fade = {}, .banner = {}}, {}); - run_rows_on(executor, logger, {.from = "00.04", .to = "00.04"}, rows); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = "00.04", .to = "00.04"}, rows); const SimRun& run = executor.result(); - if (run.failed_step != "00.04 moms_hat" || run.scenes_fought.empty()){ - return std::format("the old walk no longer goes wrong as on the console: failed in \"{}\" ({}), scenes fought: {}", - run.failed_step, run.error, fought(run)); + if (!report.completed){ + return std::format("stopped in {}: {}", run.failed_step, run.error); + } + if (!run.scenes_fought.empty()){ + return "a walk fought a scene: " + fought(run); } return true; } @@ -599,7 +603,7 @@ const FailureCase AUTO_STORY_FAILURE_CASES[] = { {.input = {"00.03 the walk into Rowan's scene routes onto his row and stops on his trigger mid-run", rowans_scene_from_each_start}, .expectation = {}}, {.input = {"00.03 the walk into Sandgem stops on Dawn's trigger mid-run", dawns_scene_mid_run}, .expectation = {}}, {.input = {"00.04 Mom's call fires above the mat, on (6, 9): the walk ends in it, her hat scene plays it (lab-B 2026-11-09 17:29)", moms_call_above_the_mat}, .expectation = {}}, - {.input = {"00.04 the old walk round Mom fights her call on (6, 9); her hat scene then sees no fade (lab-B 2026-11-09 17:29)", old_walk_fights_moms_call}, .expectation = {}}, + {.input = {"00.04 the old walk round Mom to (6, 9) runs into her call: it hands it to her hat scene, not fights it (lab-B 2026-11-09 17:29)", old_walk_hands_moms_call_over}, .expectation = {}}, {.input = {"00.04 to the ledge column with a wild battle on each pass through Route 201's grass (lab-B 2026-11-09 16:14)", [](Logger& logger){ return passes(ledge_walk_in_grass(logger, {})); }}, .expectation = {}}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index e22a8700d0..fe22384226 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -5,6 +5,7 @@ */ #include +#include #include #include #include "Common/Cpp/Exceptions.h" @@ -575,6 +576,18 @@ void SimExecutor::start_scene_at_end(const StoryStep& step){ trigger.tiles.push_back(story_to_world(m_sim.world(), end->map, tile)); }catch (const InternalProgramError&){} } + // It is the scene of the trigger next to it, which then does not fire + // again (00.05b's president, a row up). + const auto next_to = [&](const TilePos& tile){ + return std::ranges::any_of(trigger.tiles, [&](const TilePos& early){ + return std::abs(early.x - tile.x) + std::abs(early.y - tile.y) == 1; + }); + }; + for (const SimTrigger& other : m_sim.triggers()){ + if (std::ranges::any_of(other.tiles, next_to)){ + trigger.spends.push_back(other.name); + } + } m_logger.log(std::format("[{}] {}: the next scene starts on its end, {}.", m_row, step.name, Pokemon::to_string(*end))); m_sim.add_trigger(std::move(trigger)); } From e3c548908d484ac88ffc78b0dd9fb8b3f4711aaf Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 18:05:55 -0800 Subject: [PATCH 118/166] BDSP AutoStory: code health for the early-scene hand-over The hand-over sits in unknown_trainer() (PlannedRoute.cpp's 1000 lines); walk_waypoints(), unused since f1bd5ac3a, goes. GridSim's and SimStoryStepIO's additions become free functions. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../PokemonBDSP_AutoStory_GridSim.cpp | 16 ++++++ .../PokemonBDSP_AutoStory_GridSim.h | 26 +++++---- .../PokemonBDSP_AutoStory_StorySim.cpp | 13 ++--- .../PokemonBDSP_AutoStory_StorySim.h | 14 ++--- .../PokemonBDSP_AutoStory_PlannedRoute.cpp | 54 ++++--------------- .../PokemonBDSP_AutoStory_PlannedRoute.h | 18 ------- 6 files changed, 53 insertions(+), 88 deletions(-) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp index e752f0f721..39cc5907b4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -200,6 +200,22 @@ const std::vector& sim_wanderers(const GridSim& sim){ return sim.m_wanderers; } +void sim_add_trigger(GridSim& sim, SimTrigger trigger){ + sim.m_world.triggers.push_back(std::move(trigger)); +} +const std::vector& sim_triggers(const GridSim& sim){ + return sim.m_world.triggers; +} +void sim_forget_warp(GridSim& sim){ + sim.m_player.warped.reset(); +} +void sim_fight(GridSim& sim){ + if (sim.m_player.scene){ + sim.m_player.scenes_fought.push_back(*sim.m_player.scene); + } + sim.end_dialogue(); +} + bool GridSim::wanderer_at(const TilePos& pos) const{ for (const SimWanderer& wanderer : m_wanderers){ if (wanderer.pos == pos){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h index 087cf2c981..f6f89245bc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h @@ -122,6 +122,8 @@ struct SimPlayer{ std::optional trainer; // The scene (SimTrigger) whose dialogue is open, if one is. std::optional scene; + // Scenes whose dialogue was fought as a trainer's (sim_fight()). + std::vector scenes_fought = {}; // The door the last warp stepped onto. std::optional warped; std::vector fought = {}; @@ -151,17 +153,6 @@ class GridSim{ void end_dialogue(); // Puts the player on `start` of `world`: after a warp or a scene. void place(SimWorld world, const Pokemon::TilePos& start, std::optional facing); - // A scene's trigger on the world the player is on, from now on. - void add_trigger(SimTrigger trigger){ - m_world.triggers.push_back(std::move(trigger)); - } - const std::vector& triggers() const{ - return m_world.triggers; - } - // A new step starts: the warp a step before stepped onto is not this one's. - void forget_warp(){ - m_player.warped.reset(); - } const SimPlayer& player() const{ return m_player; @@ -173,6 +164,10 @@ class GridSim{ private: friend void sim_advance_time(GridSim& sim, Milliseconds time); friend const std::vector& sim_wanderers(const GridSim& sim); + friend void sim_add_trigger(GridSim& sim, SimTrigger trigger); + friend const std::vector& sim_triggers(const GridSim& sim); + friend void sim_forget_warp(GridSim& sim); + friend void sim_fight(GridSim& sim); SimMove advance(Pokemon::Direction direction, int distance); std::optional enter_next(Pokemon::Direction direction, int part, int& moved); @@ -191,6 +186,15 @@ class GridSim{ void sim_advance_time(GridSim& sim, Milliseconds time); // The wandering NPCs on the simulation's world. const std::vector& sim_wanderers(const GridSim& sim); +// A scene's trigger on the world the player is on, from now on. +void sim_add_trigger(GridSim& sim, SimTrigger trigger); +// The scene triggers on the world the player is on. +const std::vector& sim_triggers(const GridSim& sim); +// A new step starts: the warp a step before stepped onto is not this one's. +void sim_forget_warp(GridSim& sim); +// The open dialogue is fought as a trainer's: a scene's is noted in +// SimPlayer::scenes_fought, as it is pressed through under a walk. +void sim_fight(GridSim& sim); // Whether the player could take a step toward `direction` from where they stand. bool sim_can_step(const GridSim& sim, Pokemon::Direction direction); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index fe22384226..4880edf3dc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -583,13 +583,13 @@ void SimExecutor::start_scene_at_end(const StoryStep& step){ return std::abs(early.x - tile.x) + std::abs(early.y - tile.y) == 1; }); }; - for (const SimTrigger& other : m_sim.triggers()){ + for (const SimTrigger& other : sim_triggers(m_sim)){ if (std::ranges::any_of(other.tiles, next_to)){ trigger.spends.push_back(other.name); } } m_logger.log(std::format("[{}] {}: the next scene starts on its end, {}.", m_row, step.name, Pokemon::to_string(*end))); - m_sim.add_trigger(std::move(trigger)); + sim_add_trigger(m_sim, std::move(trigger)); } void SimExecutor::land(const std::string& step){ @@ -829,7 +829,7 @@ Outcome SimExecutor::run(RunState& state, const StoryStep& step){ Outcome outcome; m_passed_over = false; m_step = step.name; - m_sim.forget_warp(); + sim_forget_warp(m_sim); show_before(step); try{ outcome = run_step(state, step); @@ -862,9 +862,10 @@ Outcome SimExecutor::run(RunState& state, const StoryStep& step){ m_result.error = m_row + " " + Pokemon::to_string(outcome); m_result.failed_step = m_row + " " + step.name; } - for (const std::string& scene : m_io.take_scenes_fought()){ - m_logger.log(std::format("[{}] {}: the walk fought {}'s dialogue as a trainer's.", m_row, step.name, scene)); - m_result.scenes_fought.push_back(std::format("{} {}: {}", m_row, step.name, scene)); + const std::vector& fought = m_sim.player().scenes_fought; + for (; m_scenes_fought < fought.size(); m_scenes_fought++){ + m_logger.log(std::format("[{}] {}: the walk fought {}'s dialogue as a trainer's.", m_row, step.name, fought[m_scenes_fought])); + m_result.scenes_fought.push_back(std::format("{} {}: {}", m_row, step.name, fought[m_scenes_fought])); } m_result.world = m_placed ? &m_sim.world() : nullptr; m_result.end = nearest_tile(m_sim.player().pos); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index 8e34aed960..01a959cacd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -282,16 +282,9 @@ class SimStoryStepIO : public StoryStepIO{ return m_route; } // A scene's dialogue fought as a trainer's is pressed through under the - // walk, not its own step: noted (take_scenes_fought()). + // walk, not its own step: noted (sim_fight()). virtual void fight(const std::string&) override{ - if (m_sim.player().scene){ - m_scenes_fought.push_back(*m_sim.player().scene); - } - m_sim.end_dialogue(); - } - // The scenes fought since the last call. - std::vector take_scenes_fought(){ - return std::exchange(m_scenes_fought, {}); + sim_fight(m_sim); } virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; @@ -356,7 +349,6 @@ class SimStoryStepIO : public StoryStepIO{ const SimWorldKnobs& m_knobs; std::function m_far_side; const std::string& m_step; - std::vector m_scenes_fought; }; // A scene's trigger the simulation fires from row `row` on, once the step @@ -491,6 +483,8 @@ class SimExecutor : public Pokemon::TableExecutor{ SimStepGuard m_guard; Pokemon::StoryActionTable m_table; Pokemon::StoryInterrupts m_interrupts; + // The scenes fought so far that SimRun::scenes_fought has. + size_t m_scenes_fought = 0; // A dialog popped up (SimWorldKnobs::dialog_before) and is still up; // it rose since the last look. bool m_dialog_up = false; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp index 42eb7353e8..360686a403 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.cpp @@ -259,8 +259,6 @@ class RouteWalker{ void check_banners(LegWalk& walk); LegNext after_leg(LegWalk& walk); std::vector watching_trainers(const std::vector>& paths) const; - std::vector stopped_anywhere(const LegWalk& walk, const std::vector>& paths) const; - LegNext scene_started(const LegWalk& walk, const std::vector>& paths); LegNext unknown_trainer(LegWalk& walk, const std::vector>& paths); LegNext known_trainer(LegWalk& walk, const std::vector>& paths, const std::vector& watching); @@ -305,8 +303,7 @@ RouteEnd RouteWalker::run(std::vector from){ next = walk_leg(legs[number - 1], number, legs.size()); } if (next != LegNext::REPLAN){ - const bool early = next == LegNext::ARRIVED_EARLY || next == LegNext::SCENE; - return {early ? m_from : arrive(), m_warp, next == LegNext::SCENE}; + return {next == LegNext::NEXT_LEG ? arrive() : m_from, m_warp, next == LegNext::SCENE}; } } fail(m_io, m_plan.label + ": too many plans."); @@ -710,9 +707,6 @@ LegNext RouteWalker::after_leg(LegWalk& walk){ log_leg_done(m_io, m_maps, m_plan.label, walk.planned, walk.result.wild_battles); return LegNext::NEXT_LEG; } - if (watching.empty() && m_plan.scene_next){ - return scene_started(walk, paths); - } if (watching.empty()){ return unknown_trainer(walk, paths); } @@ -736,9 +730,10 @@ std::vector RouteWalker::watching_trainers(const std::vector RouteWalker::stopped_anywhere(const LegWalk& walk, const std::vector>& paths) const{ +// A trainer the map does not have. Fight, then plan again from anywhere +// the leg could have stopped. The next step's scene (RouteWalkPlan::scene_next) +// is not fought: the walk ends there, its dialogue open, for that step. +LegNext RouteWalker::unknown_trainer(LegWalk& walk, const std::vector>& paths){ std::vector anywhere; const size_t moved = std::min(walk.planned.leg.tiles, walk.result.moved_chunks + walk.turn_moved); if (walk.result.stop == WalkStop::DIALOG && moved > 0){ @@ -755,22 +750,12 @@ std::vector RouteWalker::stopped_anywhere(const LegWalk& walk, const st anywhere.insert(anywhere.end(), path.begin(), path.end()); } } - return sorted_unique(std::move(anywhere)); -} - -// The next step's scene, started on the way: the walk ends with its -// dialogue open, for that step to play. -LegNext RouteWalker::scene_started(const LegWalk& walk, const std::vector>& paths){ - m_from = stopped_anywhere(walk, paths); - m_io.note("[Route] " + walk.label + ": the next step's scene started on the way, at " + - describe(m_maps, m_from) + "; handing over.", RouteNote::WARNING); - return LegNext::SCENE; -} - -// A trainer the map does not have. Fight, then plan again from anywhere -// the leg could have stopped. -LegNext RouteWalker::unknown_trainer(LegWalk& walk, const std::vector>& paths){ - std::vector anywhere = stopped_anywhere(walk, paths); + anywhere = sorted_unique(std::move(anywhere)); + if (m_plan.scene_next){ + m_from = std::move(anywhere); + m_io.note(walk.label + ": the next step's scene started on the way; handing it over.", RouteNote::WARNING); + return LegNext::SCENE; + } // A scene the map lacks (r14: Barry's Route 201 warning, then the row that // pulls us back) would replan into it forever: give up after the second. if (++m_unexplained_talks > 2){ @@ -894,23 +879,6 @@ RouteEnd walk_route_to_warp( return RouteWalker(io, maps, trainers, plan).run(std::move(from)); } -std::vector walk_waypoints( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, std::vector from, - RouteTrainers& trainers, const WaypointWalkPlan& plan -){ - for (size_t i = 0; i < plan.waypoints.size(); i++){ - const TilePos goal = plan.waypoints[i]; - from = walk_route(stream, context, escape, maps, from, trainers, { - .goal = [goal](const TilePos& pos){ return pos == goal; }, - .label = plan.label + " (" + std::to_string(i + 1) + "/" + std::to_string(plan.waypoints.size()) + - ", to " + describe(maps, goal) + ")", - .avoid = {}, - .costs = plan.costs, - }); - } - return from; -} void talk_to_npc( VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h index 29d9692969..fef294ac21 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h @@ -94,24 +94,6 @@ RouteEnd walk_route_to_warp( RouteTrainers& trainers, const RouteWalkPlan& plan ); -// The corners of a line a human walked, and the costs to plan each -// stretch with. -struct WaypointWalkPlan{ - std::vector waypoints; - std::string label; - RobustPlanCosts costs = waypoint_plan_costs(); -}; - -// Walks `from` to each of `plan.waypoints` in turn, with walk_route() for -// every stretch, and returns where the last one ended: the plan is the -// line, with the walker's handling of trainers and blocks on each stretch -// (Route 204 North, 2026-10-31). -std::vector walk_waypoints( - VideoStream& stream, ProControllerContext& context, const WildBattleEscape& escape, - const StoryWorld& maps, std::vector from, - RouteTrainers& trainers, const WaypointWalkPlan& plan -); - // Whom talk_to_npc() talks to: the NPC on world tile `npc`, from the sides // in `sides` (the side of the NPC to stand on), in order. struct NpcTalk{ From 8b3a21ee6ee6f6516be134ba53bfed15e3c73e1e Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 18:43:34 -0800 Subject: [PATCH 119/166] BDSP AutoStory: route bench with a shared route scorer Pokemon::score_route() walks a plan on a tile grid from every start tile: legs to a wall land exactly, taps move whole tiles, held open legs may end open_error + n/5 tiles off and that window must be safe (no grass, ledge, warp, trigger or wanderer). It charges wild encounters, wanderers and trainer sight by chance times their recovery, replans where a lost tap is not absorbed by the plan's own walls, and fails a plan whose recovery leads back to itself (STRAND) or needs more than 3 recoveries in a row. The BDSP bench scores every story table ROUTE step's plan as RouteWalker walks it, the user's routes for three 00.04 steps, and human ratios against the user's route or a shortest-safe-run stand-in, against Data/route_bench.golden.txt: no route may score worse. The story table's route extraction moves unchanged from the StoryTable test into PokemonBDSP_AutoStory_TableRoutes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../ComputerPrograms_UnitTestRunner.cpp | 2 +- .../Navigation/Pokemon_Navigation_Tests.h | 2 + .../Navigation/Pokemon_RouteScorer.cpp | 457 ++++++++++++++ .../Pokemon/Navigation/Pokemon_RouteScorer.h | 135 ++++ .../Navigation/Pokemon_RouteScorer_Tests.cpp | 351 +++++++++++ .../Source/PokemonBDSP/PokemonBDSP_Tests.cpp | 2 + .../AutoStory/Data/route_bench.golden.txt | 67 ++ ...PokemonBDSP_AutoStory_RouteBench_Tests.cpp | 591 ++++++++++++++++++ .../PokemonBDSP_AutoStory_RouteBench_Tests.h | 25 + ...PokemonBDSP_AutoStory_StoryTable_Tests.cpp | 85 +-- .../PokemonBDSP_AutoStory_TableRoutes.cpp | 97 +++ .../PokemonBDSP_AutoStory_TableRoutes.h | 60 ++ SerialPrograms/cmake/SourceFiles.cmake | 7 + 13 files changed, 1796 insertions(+), 85 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_bench.golden.txt create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.h diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 49809884ff..ba88e2b23e 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -56,7 +56,6 @@ namespace ComputerPrograms{ UnitTestDatabase make_UNIT_TESTS_ALL(){ UnitTestDatabase ret; - add_tests_QtEventThreadPool(ret, GlobalThreadPools::computation_normal()); add_tests_Sockets(ret, GlobalThreadPools::unlimited_normal()); add_tests_BlackBorderDetector(ret); @@ -79,6 +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_RouteScorer(ret); Pokemon::add_tests_ScreenEvents(ret); Pokemon::add_tests_Interrupts(ret); Pokemon::add_tests_Transitions(ret); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h index 0bb989df00..0f73c13600 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h @@ -26,6 +26,8 @@ void add_tests_WallRecovery(UnitTestDatabase& database); void add_tests_MapData(UnitTestDatabase& database); // Registers route logging formatting unit tests. void add_tests_RouteLog(UnitTestDatabase& database); +// Registers route scorer unit tests. +void add_tests_RouteScorer(UnitTestDatabase& database); // (name, JSON text) of each map in Pokemon/Navigation/TestMaps/, built into // the program by pa_embed_text_files() (cmake/EmbedTextFiles.cmake). diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.cpp new file mode 100644 index 0000000000..ece9550da3 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.cpp @@ -0,0 +1,457 @@ +/* Route Scorer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Pokemon_RouteScorer.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string to_string(const ScoredLeg& leg){ + const char* how = "taps"; + switch (leg.kind){ + case ScoredLegKind::TO_WALL: + how = leg.run ? "run to wall" : "walk to wall"; + break; + case ScoredLegKind::OPEN_HOLD: + how = leg.run ? "run, open" : "walk, open"; + break; + case ScoredLegKind::TAPS: + break; + } + return std::format("{} {} ({})", direction_name(leg.direction), leg.tiles, how); +} + +const char* verdict_name(RouteVerdict verdict){ + switch (verdict){ + case RouteVerdict::PASS: + return "PASS"; + case RouteVerdict::FAIL: + return "FAIL"; + case RouteVerdict::STRAND: + return "STRAND"; + case RouteVerdict::RETRIES: + return "RETRIES"; + } + return "?"; +} + + +namespace{ + +size_t distance(const TilePos& a, const TilePos& b){ + return (size_t)(std::abs(a.x - b.x) + std::abs(a.y - b.y)); +} + +bool stops_on(TileRisk risk){ + return risk == TileRisk::WARP || risk == TileRisk::TRIGGER; +} + +// One leg walked from one tile, nothing interrupting. +struct LegWalk{ + std::vector path; // tiles surely walked, in order, the first after the start + std::vector ends; // where the leg may end + long long ms = 0; + bool stop = false; // ended at a wall (a re-localization) + size_t taps = 0; + std::string unsafe; // why the leg may end somewhere it must not +}; + +// Steps from `from` until stopped, at most `most` steps; stops on a warp +// or a trigger. +std::vector walk_steps(const ScoreMap& map, const TilePos& from, Direction direction, size_t most){ + std::vector path; + TilePos at = from; + while (path.size() < most){ + const std::optional next = map.step(at, direction); + if (!next){ + break; + } + path.push_back(*next); + at = *next; + if (stops_on(map.risk(at))){ + break; + } + } + return path; +} + +size_t path_tiles(const TilePos& from, const std::vector& path){ + size_t tiles = 0; + TilePos at = from; + for (const TilePos& pos : path){ + tiles += distance(at, pos); + at = pos; + } + return tiles; +} + +LegWalk walk_to_wall(const ScoreMap& map, const TilePos& from, const ScoredLeg& leg, const RoutePaces& paces){ + LegWalk walk; + walk.path = walk_steps(map, from, leg.direction, (size_t)-1); + walk.ends = {walk.path.empty() ? from : walk.path.back()}; + walk.stop = walk.path.empty() || !stops_on(map.risk(walk.path.back())); + walk.ms = paces.start_ms + (long long)path_tiles(from, walk.path) * paces.ms_per_tile(leg.direction, leg.run) + + (walk.stop ? paces.stop_ms : 0); + return walk; +} + +LegWalk walk_taps(const ScoreMap& map, const TilePos& from, const ScoredLeg& leg, const RoutePaces& paces){ + LegWalk walk; + walk.path = walk_steps(map, from, leg.direction, leg.tiles); + walk.ends = {walk.path.empty() ? from : walk.path.back()}; + const bool blocked = walk.path.size() < leg.tiles && (walk.path.empty() || !stops_on(map.risk(walk.path.back()))); + // A blocked walk of taps ends after two taps that move nothing. + walk.taps = walk.path.size() + (blocked ? 2 : 0); + walk.ms = (long long)walk.taps * paces.tap_ms; + return walk; +} + +// Why a tile in a held leg's uncertain end must not be reached, or "". +std::string unsafe_overshoot(const ScoreMap& map, const TilePos& before, const TilePos& pos, + const std::function& goal +){ + if (distance(before, pos) > 1){ + return "a ledge hop at " + to_string(pos); + } + switch (map.risk(pos)){ + case TileRisk::NONE: + return ""; + case TileRisk::TRIGGER: + return goal(pos) ? "" : "a trigger at " + to_string(pos); + case TileRisk::WARP: + return goal(pos) ? "" : "a warp at " + to_string(pos); + case TileRisk::ENCOUNTER: + return "grass at " + to_string(pos); + case TileRisk::WANDERER: + return "a wanderer's tile at " + to_string(pos); + case TileRisk::SIGHT: + return "a trainer's sight at " + to_string(pos); + } + return ""; +} + +LegWalk walk_open_hold(const ScoreMap& map, const TilePos& from, const ScoredLeg& leg, + const RoutePaces& paces, const InterruptModel& model, const std::function& goal +){ + const size_t error = (size_t)model.open_error + leg.tiles / (size_t)std::max(1, model.open_error_per); + const size_t fewest = leg.tiles > error ? leg.tiles - error : 0; + const std::vector all = walk_steps(map, from, leg.direction, leg.tiles + error); + LegWalk walk; + walk.path.assign(all.begin(), all.begin() + std::min(fewest, all.size())); + for (size_t k = fewest; k <= all.size(); k++){ + walk.ends.push_back(k == 0 ? from : all[k - 1]); + if (k > fewest && walk.unsafe.empty()){ + walk.unsafe = unsafe_overshoot(map, k == 1 ? from : all[k - 2], all[k - 1], goal); + } + } + walk.ms = paces.start_ms + (long long)leg.tiles * paces.ms_per_tile(leg.direction, leg.run); + return walk; +} + +LegWalk walk_leg(const ScoreMap& map, const TilePos& from, const ScoredLeg& leg, + const RoutePaces& paces, const InterruptModel& model, const std::function& goal +){ + LegWalk walk; + switch (leg.kind){ + case ScoredLegKind::TO_WALL: + walk = walk_to_wall(map, from, leg, paces); + break; + case ScoredLegKind::TAPS: + walk = walk_taps(map, from, leg, paces); + break; + case ScoredLegKind::OPEN_HOLD: + walk = walk_open_hold(map, from, leg, paces, model, goal); + break; + } + walk.ms += paces.press_ms; + return walk; +} + + +// One way the walk may have gone so far, from one start tile. +struct Branch{ + TilePos pos; + long long ms = 0; + double weight = 0; // chance of this branch, the starts equally likely + bool sighted = false; // a trainer has seen us (and been fought) +}; + +// Where an interruption may happen, and what it costs. +struct Interruption{ + size_t leg; + size_t steps; // steps of the leg walked when it happens + TilePos from; // where the leg started + TilePos at; + double chance; + long long cost_ms; + double weight; +}; + +// The plan from where an interruption leaves the player on: the rest of +// the interrupted leg, then the legs after it. +std::vector rest_of_plan(const std::vector& legs, const Interruption& stop){ + const ScoredLeg& leg = legs[stop.leg]; + std::vector rest; + if (leg.kind == ScoredLegKind::TO_WALL || stop.steps < leg.tiles){ + ScoredLeg left = leg; + left.tiles = leg.kind == ScoredLegKind::TO_WALL ? leg.tiles : leg.tiles - stop.steps; + rest.push_back(left); + } + rest.insert(rest.end(), legs.begin() + stop.leg + 1, legs.end()); + return rest; +} + +// The tiles an interruption on a leg without a wall may leave us on: a +// tap lost or one too many either way. +std::vector unsure_tiles(const ScoreMap& map, const ScoredLeg& leg, const Interruption& stop){ + std::vector tiles{stop.at}; + if (leg.kind == ScoredLegKind::TO_WALL){ + return tiles; + } + const std::vector back = walk_steps(map, stop.at, Direction((int(leg.direction) + 2) % 4), 1); + const std::vector ahead = walk_steps(map, stop.at, leg.direction, 1); + tiles.insert(tiles.end(), back.begin(), back.end()); + tiles.insert(tiles.end(), ahead.begin(), ahead.end()); + return tiles; +} + +std::string key_of(std::vector tiles){ + std::sort(tiles.begin(), tiles.end(), [](const TilePos& a, const TilePos& b){ + return a.y != b.y ? a.y < b.y : a.x < b.x; + }); + std::string key; + for (const TilePos& pos : tiles){ + key += to_string(pos); + } + return key; +} + + +// What a nominal walk of a plan gives: the branches at its end, the +// interruptions it may meet, and how it may fail. +struct PlanWalk{ + std::vector branches; + std::vector interruptions; + size_t stops = 0; + size_t presses = 0; + std::string fail; +}; + +class Scorer{ +public: + Scorer(const ScoreMap& map, const std::function& goal, + const RoutePaces& paces, const InterruptModel& model, const RouteReplanner& replan + ) + : m_map(map), m_goal(goal), m_paces(paces), m_model(model), m_replan(replan) + {} + + RouteScore score(const std::vector& from, const std::vector& legs, size_t depth); + +private: + PlanWalk walk_plan(const std::vector& from, const std::vector& legs) const; + void walk_branch(PlanWalk& out, const Branch& branch, size_t index, const ScoredLeg& leg, + bool last, std::map& next) const; + void add_interruptions(PlanWalk& out, Branch& branch, size_t index, const TilePos& from, const LegWalk& walk) const; + void recover(RouteScore& score, const std::vector& legs, const Interruption& stop, size_t depth); + RouteScore recovery_score(const std::vector& unsure, size_t depth); + static void fail(RouteScore& score, RouteVerdict verdict, const std::string& why); + + const ScoreMap& m_map; + const std::function& m_goal; + const RoutePaces& m_paces; + const InterruptModel& m_model; + const RouteReplanner& m_replan; + std::map m_done; + std::set m_open; +}; + +void Scorer::fail(RouteScore& score, RouteVerdict verdict, const std::string& why){ + if (score.verdict == RouteVerdict::PASS){ + score.verdict = verdict; + score.why = why; + } +} + +void Scorer::add_interruptions(PlanWalk& out, Branch& branch, size_t index, const TilePos& from, const LegWalk& walk) const{ + for (size_t k = 0; k < walk.path.size(); k++){ + const TilePos& at = walk.path[k]; + Interruption stop{.leg = index, .steps = k + 1, .from = from, .at = at, .chance = 0, .cost_ms = 0, .weight = branch.weight}; + switch (m_map.risk(at)){ + case TileRisk::ENCOUNTER: + stop.chance = m_model.encounter_per_tile; + stop.cost_ms = m_model.encounter_ms; + break; + case TileRisk::WANDERER: + stop.chance = m_model.wanderer_per_tile; + stop.cost_ms = m_model.wanderer_ms; + break; + case TileRisk::SIGHT: + stop.chance = branch.sighted ? 0 : 1; + stop.cost_ms = m_model.trainer_ms; + branch.sighted = true; + break; + default: + break; + } + if (stop.chance > 0){ + out.interruptions.push_back(stop); + } + } +} + +void Scorer::walk_branch(PlanWalk& out, const Branch& branch, size_t index, const ScoredLeg& leg, + bool last, std::map& next +) const{ + const LegWalk walk = walk_leg(m_map, branch.pos, leg, m_paces, m_model, m_goal); + if (!walk.unsafe.empty() && out.fail.empty()){ + out.fail = std::format("leg {} ({}) from {} may overshoot onto {}", index + 1, to_string(leg), to_string(branch.pos), walk.unsafe); + } + for (const TilePos& pos : walk.path){ + if (m_map.risk(pos) == TileRisk::WARP && !(last && pos == walk.path.back() && m_goal(pos)) && out.fail.empty()){ + out.fail = std::format("leg {} ({}) from {} walks into the warp at {}", index + 1, to_string(leg), to_string(branch.pos), to_string(pos)); + } + } + Branch walked = branch; + walked.ms += walk.ms; + add_interruptions(out, walked, index, branch.pos, walk); + for (const TilePos& end : walk.ends){ + Branch b = walked; + b.pos = end; + b.weight = walked.weight / (double)walk.ends.size(); + auto [it, added] = next.try_emplace(key_of({end}), b); + if (!added){ + it->second.weight += b.weight; + it->second.ms = std::max(it->second.ms, b.ms); + } + } +} + +PlanWalk Scorer::walk_plan(const std::vector& from, const std::vector& legs) const{ + PlanWalk out; + for (const TilePos& pos : from){ + out.branches.push_back({.pos = pos, .ms = 0, .weight = 1.0 / (double)from.size(), .sighted = false}); + } + for (size_t i = 0; i < legs.size(); i++){ + std::map next; + for (const Branch& branch : out.branches){ + walk_branch(out, branch, i, legs[i], i + 1 == legs.size(), next); + } + out.branches.clear(); + for (auto& item : next){ + out.branches.push_back(item.second); + } + if (out.branches.size() > m_model.max_spread && out.fail.empty()){ + out.fail = std::format("after leg {} the player may be on {} tiles", i + 1, out.branches.size()); + } + out.presses += legs[i].kind == ScoredLegKind::TAPS ? legs[i].tiles : 1; + out.stops += legs[i].kind == ScoredLegKind::TO_WALL ? 1 : 0; + } + for (const Branch& branch : out.branches){ + if (!m_goal(branch.pos) && out.fail.empty()){ + out.fail = "may end on " + to_string(branch.pos) + ", off the goal"; + } + } + return out; +} + +RouteScore Scorer::recovery_score(const std::vector& unsure, size_t depth){ + RouteScore score; + const std::string key = key_of(unsure); + if (m_open.contains(key)){ + fail(score, RouteVerdict::STRAND, "the recovery from " + key + " leads back to itself"); + return score; + } + const auto done = m_done.find(key); + if (done != m_done.end()){ + return done->second; + } + if (depth > m_model.max_recoveries){ + fail(score, RouteVerdict::RETRIES, std::format("more than {} recoveries in a row, at {}", m_model.max_recoveries, key)); + return score; + } + const std::optional> legs = m_replan ? m_replan(unsure) : std::nullopt; + if (!legs){ + fail(score, RouteVerdict::FAIL, "no recovery from " + key); + return score; + } + m_open.insert(key); + score = this->score(unsure, *legs, depth); + m_open.erase(key); + if (score.verdict != RouteVerdict::PASS){ + score.why = "recovery from " + key + ": " + score.why; + } + m_done[key] = score; + return score; +} + +void Scorer::recover(RouteScore& score, const std::vector& legs, const Interruption& stop, size_t depth){ + score.recoveries++; + const ScoredLeg& leg = legs[stop.leg]; + const std::vector rest = rest_of_plan(legs, stop); + const PlanWalk resumed_exact = walk_plan({stop.at}, rest); + const long long rest_ms = resumed_exact.branches.empty() ? 0 : resumed_exact.branches.front().ms; + const std::vector unsure = unsure_tiles(m_map, leg, stop); + const PlanWalk resumed = walk_plan(unsure, rest); + long long extra_ms = m_paces.start_ms + m_paces.press_ms; + long long extra_worst = extra_ms; + if (!resumed.fail.empty()){ + score.replans++; + const RouteScore again = recovery_score(unsure, depth + 1); + if (again.verdict != RouteVerdict::PASS){ + fail(score, again.verdict, std::format("leg {} interrupted at {}: {}", stop.leg + 1, to_string(stop.at), again.why)); + return; + } + extra_ms = std::max(0, m_model.replan_ms + (long long)again.expected_ms - rest_ms); + extra_worst = std::max(0, m_model.replan_ms + again.worst_ms - rest_ms); + } + score.expected_ms += stop.weight * stop.chance * (double)(stop.cost_ms + extra_ms); + score.worst_ms = std::max(score.worst_ms, score.nominal_ms + stop.cost_ms + extra_worst); +} + +RouteScore Scorer::score(const std::vector& from, const std::vector& legs, size_t depth){ + RouteScore score; + const PlanWalk walk = walk_plan(from, legs); + score.stops = walk.stops; + score.presses = walk.presses; + for (const Branch& branch : walk.branches){ + score.nominal_ms = std::max(score.nominal_ms, branch.ms); + score.expected_ms += branch.weight * (double)branch.ms; + } + score.worst_ms = score.nominal_ms; + if (!walk.fail.empty()){ + fail(score, RouteVerdict::FAIL, walk.fail); + return score; + } + for (const Interruption& stop : walk.interruptions){ + recover(score, legs, stop, depth); + } + return score; +} + +} // namespace + + +RouteScore score_route( + const ScoreMap& map, const std::vector& from, + const std::function& goal, + const std::vector& legs, + const RoutePaces& paces, const InterruptModel& model, + const RouteReplanner& replan +){ + Scorer scorer(map, goal, paces, model, replan); + return scorer.score(from, legs, 0); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.h new file mode 100644 index 0000000000..d27a82e9ca --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.h @@ -0,0 +1,135 @@ +/* Route Scorer + * + * From: https://github.com/PokemonAutomation/ + * + * Scores a walk plan on a tile grid: how long it takes on the game's + * measured paces, from every tile the player may start on, and whether it + * can go wrong. A leg held to a wall ends where the wall stops it; a leg of + * taps moves exactly its taps; a held open leg may end a few tiles short or + * long, and those tiles must be safe. Interruptions on the way (a wild + * battle in grass, someone walking about, a trainer's sight) are charged by + * their chance times the recovery they need, and a recovery that can lead + * back into itself strands the player: the plan fails. + * + * Game-neutral: the game supplies the step rules, the tile risks, the paces + * and, for recoveries, its replanner. + * + */ + +#ifndef PokemonAutomation_Pokemon_RouteScorer_H +#define PokemonAutomation_Pokemon_RouteScorer_H + +#include +#include +#include +#include +#include +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What walking onto a tile risks. +enum class TileRisk{ + NONE, + ENCOUNTER, // tall grass: a wild battle may start + WANDERER, // someone walking about may stand in the way + SIGHT, // a trainer sees the player and walks over + WARP, // a door or warp: walking onto it leaves the map + TRIGGER, // a scene starts here and stops the player +}; + +// The grid a plan is scored on. +struct ScoreMap{ + // Where one step from a tile lands (a ledge hop lands two tiles on), or + // nothing if the player is stopped. A warp's tile is landed on. + std::function(const TilePos&, Direction)> step; + std::function risk; +}; + +// How a leg is walked. +enum class ScoredLegKind{ + TO_WALL, // held until the player stops: lands exactly + TAPS, // one D-pad tap per tile: lands exactly + OPEN_HOLD, // held for its tiles' time: may land a few tiles off +}; +// One leg of a plan. +struct ScoredLeg{ + Direction direction = Direction::NORTH; + size_t tiles = 0; + ScoredLegKind kind = ScoredLegKind::TAPS; + bool run = false; // held at a run (B), not a walk +}; +// "west 16 (taps)", "south 33 (run to wall)". +std::string to_string(const ScoredLeg& leg); + +// The game's measured times. +struct RoutePaces{ + // Time per tile held in a direction, walking or running. + std::function ms_per_tile; + long long start_ms = 250; // from pressing to the first step + long long tap_ms = 800; // one tap and its release + long long press_ms = 100; // a leg's overhead: the turn, the watch + long long stop_ms = 1000; // confirming a stop at a wall (a re-localization) +}; + +// How interruptions are charged. +struct InterruptModel{ + double encounter_per_tile = 0.1; + long long encounter_ms = 12000; // a wild battle run from + double wanderer_per_tile = 0.25; + long long wanderer_ms = 2500; // waiting for them to move on + long long trainer_ms = 45000; // a trainer battle + long long replan_ms = 2000; // a stop and a new plan + // A held open leg of n tiles may end open_error + n / open_error_per + // tiles short or long. + int open_error = 1; + int open_error_per = 5; + // Most recoveries in a row before the plan counts as stuck. + size_t max_recoveries = 3; + // Most tiles the player may be on at once, before a plan is too loose. + size_t max_spread = 32; +}; + +// A new plan from where an interruption left the player, or nothing if +// none exists. Null: a recovery that needs a new plan fails. +using RouteReplanner = std::function>(const std::vector& from)>; + +// Whether a plan gets there, from every start and through every recovery. +enum class RouteVerdict{ + PASS, + FAIL, // may end off the goal, overshoot onto a hazard, or never arrive + STRAND, // a recovery can lead back into itself + RETRIES, // more recoveries in a row than InterruptModel::max_recoveries +}; +// "PASS", "FAIL", "STRAND", "RETRIES". +const char* verdict_name(RouteVerdict verdict); + +// A plan's score. +struct RouteScore{ + RouteVerdict verdict = RouteVerdict::PASS; + std::string why; // for a verdict other than PASS + long long nominal_ms = 0; // slowest start, nothing interrupting + double expected_ms = 0; // average start, interruptions by their chance + long long worst_ms = 0; // slowest start and the costliest single interruption + size_t stops = 0; // legs that end on a wall: each re-localizes + size_t presses = 0; // legs plus taps + size_t recoveries = 0; // places an interruption may happen + size_t replans = 0; // of those, the ones the plan's own legs cannot absorb +}; + +// Scores `legs` walked from any of `from` toward tiles `goal` accepts. +RouteScore score_route( + const ScoreMap& map, const std::vector& from, + const std::function& goal, + const std::vector& legs, + const RoutePaces& paces, const InterruptModel& model, + const RouteReplanner& replan = nullptr +); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp new file mode 100644 index 0000000000..e449a0d3ee --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp @@ -0,0 +1,351 @@ +/* Route Scorer Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The scorer on small made-up grids. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_Navigation_Tests.h" +#include "Pokemon_RouteScorer.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// '#' wall, '.' floor, '"' tall grass, 'D' a warp, 'T' a scene's trigger, +// 'w' a wanderer's tile, 's' a trainer's sight, 'v' a ledge hopped south. +class ToyMap{ +public: + explicit ToyMap(std::vector rows) + : m_rows(std::move(rows)) + {} + + char at(const TilePos& pos) const{ + if (pos.y < 0 || pos.y >= (int)m_rows.size() || pos.x < 0 || pos.x >= (int)m_rows[pos.y].size()){ + return '#'; + } + return m_rows[pos.y][pos.x]; + } + ScoreMap score_map() const{ + return { + .step = [this](const TilePos& from, Direction direction) -> std::optional{ + const TilePos next = from.next(direction); + if (at(next) == 'v'){ + return direction == Direction::SOUTH ? std::optional(next.next(direction)) : std::nullopt; + } + return at(next) == '#' ? std::nullopt : std::optional(next); + }, + .risk = [this](const TilePos& pos){ + switch (at(pos)){ + case '"': + return TileRisk::ENCOUNTER; + case 'D': + return TileRisk::WARP; + case 'T': + return TileRisk::TRIGGER; + case 'w': + return TileRisk::WANDERER; + case 's': + return TileRisk::SIGHT; + default: + return TileRisk::NONE; + } + }, + }; + } + +private: + std::vector m_rows; +}; + +RoutePaces toy_paces(){ + return { + .ms_per_tile = [](Direction, bool run){ return run ? 100LL : 250LL; }, + .start_ms = 250, .tap_ms = 800, .press_ms = 100, .stop_ms = 1000, + }; +} + +std::function exactly(const TilePos& goal){ + return [goal](const TilePos& pos){ return pos == goal; }; +} + +RouteScore score(const ToyMap& toy, const std::vector& from, const TilePos& goal, + const std::vector& legs, const RouteReplanner& replan = nullptr, const InterruptModel& model = InterruptModel() +){ + return score_route(toy.score_map(), from, exactly(goal), legs, toy_paces(), model, replan); +} + +// "" if `got` has `verdict`, else why not. +std::string expect(const RouteScore& got, RouteVerdict verdict, const std::string& what){ + if (got.verdict != verdict){ + return std::format("{}: expected {}, got {} ({})", what, verdict_name(verdict), verdict_name(got.verdict), got.why); + } + return ""; +} + +// Passes if every check is "". +UnitTestResult all_of(std::initializer_list checks){ + for (const std::string& check : checks){ + if (!check.empty()){ + return check; + } + } + return true; +} + +UnitTestResult test_taps_time(){ + const ToyMap toy({"......"}); + const RouteScore got = score(toy, {{0, 0}}, {4, 0}, {{.direction = Direction::EAST, .tiles = 4, .kind = ScoredLegKind::TAPS}}); + if (got.verdict != RouteVerdict::PASS || got.nominal_ms != 4 * 800 + 100 || got.presses != 4 || got.stops != 0){ + return std::format("4 taps: {} {} ms, {} presses, {} stops", verdict_name(got.verdict), got.nominal_ms, got.presses, got.stops); + } + return true; +} + +UnitTestResult test_run_to_wall_beats_taps(){ + const ToyMap toy({"......#"}); + const RouteScore taps = score(toy, {{0, 0}}, {5, 0}, {{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}); + const RouteScore run = score(toy, {{0, 0}}, {5, 0}, {{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TO_WALL, .run = true}}); + if (run.verdict != RouteVerdict::PASS || run.nominal_ms != 250 + 500 + 1000 + 100 || run.stops != 1){ + return std::format("run: {} {} ms ({})", verdict_name(run.verdict), run.nominal_ms, run.why); + } + return run.expected_ms < taps.expected_ms ? UnitTestResult(true) : UnitTestResult("the run is not faster than the taps"); +} + +UnitTestResult test_wall_collapses_a_set(){ + // Three columns, all stopped by row 2's wall, then taps west. + const ToyMap toy({".....", ".....", "#####"}); + const RouteScore got = score(toy, {{2, 0}}, {0, 1}, { + {.direction = Direction::EAST, .tiles = 2, .kind = ScoredLegKind::OPEN_HOLD, .run = true}, + {.direction = Direction::SOUTH, .tiles = 1, .kind = ScoredLegKind::TO_WALL}, + {.direction = Direction::WEST, .tiles = 4, .kind = ScoredLegKind::TO_WALL}, + }); + return all_of({expect(got, RouteVerdict::PASS, "open run east, then walls south and west")}); +} + +UnitTestResult test_open_hold_off_the_goal(){ + const ToyMap toy({"........"}); + const RouteScore got = score(toy, {{0, 0}}, {3, 0}, {{.direction = Direction::EAST, .tiles = 3, .kind = ScoredLegKind::OPEN_HOLD}}); + return all_of({expect(got, RouteVerdict::FAIL, "an open hold with nothing to stop it")}); +} + +UnitTestResult test_open_hold_into_grass(){ + const ToyMap toy({"....\"\"\"#"}); + const RouteScore got = score(toy, {{0, 0}}, {6, 0}, { + {.direction = Direction::EAST, .tiles = 3, .kind = ScoredLegKind::OPEN_HOLD}, + {.direction = Direction::EAST, .tiles = 3, .kind = ScoredLegKind::TO_WALL}, + }); + return all_of({expect(got, RouteVerdict::FAIL, "an open hold whose overshoot reaches grass")}); +} + +UnitTestResult test_open_hold_onto_a_ledge(){ + const ToyMap toy({".", ".", ".", "v", ".", "#"}); + const RouteScore got = score(toy, {{0, 0}}, {0, 4}, { + {.direction = Direction::SOUTH, .tiles = 2, .kind = ScoredLegKind::OPEN_HOLD}, + {.direction = Direction::SOUTH, .tiles = 2, .kind = ScoredLegKind::TO_WALL}, + }); + return all_of({expect(got, RouteVerdict::FAIL, "an open hold whose overshoot hops a ledge")}); +} + +UnitTestResult test_open_hold_before_a_wall(){ + const ToyMap toy({".....#"}); + const RouteScore got = score(toy, {{0, 0}}, {4, 0}, {{.direction = Direction::EAST, .tiles = 4, .kind = ScoredLegKind::OPEN_HOLD, .run = true}}); + return all_of({ + expect(got, RouteVerdict::FAIL, "an open hold that may stop a tile short"), + expect(score(toy, {{0, 0}}, {4, 0}, {{.direction = Direction::EAST, .tiles = 3, .kind = ScoredLegKind::OPEN_HOLD, .run = true}, + {.direction = Direction::EAST, .tiles = 2, .kind = ScoredLegKind::TO_WALL, .run = true}}), + RouteVerdict::PASS, "an open hold that overshoots only toward a wall, then the wall"), + }); +} + +UnitTestResult test_wall_leg_through_a_warp(){ + const ToyMap toy({"..D..#"}); + const RouteScore got = score(toy, {{0, 0}}, {4, 0}, {{.direction = Direction::EAST, .tiles = 4, .kind = ScoredLegKind::TO_WALL}}); + return all_of({ + expect(got, RouteVerdict::FAIL, "a hold that walks into a warp"), + expect(score(toy, {{0, 0}}, {2, 0}, {{.direction = Direction::EAST, .tiles = 2, .kind = ScoredLegKind::TO_WALL}}), + RouteVerdict::PASS, "a hold that ends in the warp it is for"), + }); +} + +UnitTestResult test_trigger_stops_a_run(){ + const ToyMap toy({"..T...."}); + return all_of({expect(score(toy, {{0, 0}}, {2, 0}, {{.direction = Direction::EAST, .tiles = 2, .kind = ScoredLegKind::TO_WALL, .run = true}}), + RouteVerdict::PASS, "a run that the goal's trigger stops")}); +} + +UnitTestResult test_grass_charges_interruptions(){ + const ToyMap toy({".\"\"\"..#"}); + const RouteScore got = score(toy, {{0, 0}}, {5, 0}, {{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TO_WALL}}); + if (got.verdict != RouteVerdict::PASS || got.recoveries != 3 || got.replans != 0){ + return std::format("{}: {} recoveries, {} replans ({})", verdict_name(got.verdict), got.recoveries, got.replans, got.why); + } + if (got.expected_ms <= (double)got.nominal_ms || got.worst_ms <= got.nominal_ms){ + return std::format("expected {} ms, worst {} ms, nominal {} ms", got.expected_ms, got.worst_ms, got.nominal_ms); + } + return true; +} + +UnitTestResult test_taps_in_grass_need_a_replan(){ + // A lost tap in the grass leaves us a tile either way; the taps after it + // cannot tell, so without a replanner the plan fails. + const ToyMap toy({".\"\"\"...."}); + const std::vector taps{{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}; + const RouteScore failed = score(toy, {{0, 0}}, {5, 0}, taps); + // A replanner that goes east to the wall absorbs it. + const ToyMap walled({".\"\"\"..#"}); + const RouteReplanner to_wall = [](const std::vector&){ + return std::optional>({{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TO_WALL}}); + }; + const RouteScore replanned = score(walled, {{0, 0}}, {5, 0}, taps, to_wall); + if (replanned.replans != 3){ + return std::format("{} replans", replanned.replans); + } + return all_of({ + expect(failed, RouteVerdict::FAIL, "taps in grass without a replanner"), + expect(replanned, RouteVerdict::PASS, "taps in grass with a wall to replan to"), + }); +} + +UnitTestResult test_recovery_back_through_the_grass_strands(){ + // The recovery walks back to the west wall and taps east through the + // same grass: an interruption there leads to the same recovery again. + const ToyMap toy({"#.\"\"\"...."}); + const std::vector taps{{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}; + const RouteReplanner back = [](const std::vector&){ + return std::optional>({{.direction = Direction::WEST, .tiles = 4, .kind = ScoredLegKind::TO_WALL}, + {.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}); + }; + return all_of({expect(score(toy, {{1, 0}}, {6, 0}, taps, back), RouteVerdict::STRAND, "a recovery back through the grass")}); +} + +UnitTestResult test_too_many_recoveries(){ + const ToyMap toy({".\"\"\"..#"}); + const RouteReplanner to_wall = [](const std::vector&){ + return std::optional>({{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TO_WALL}}); + }; + InterruptModel model; + model.max_recoveries = 0; + return all_of({expect(score(toy, {{0, 0}}, {5, 0}, {{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}, to_wall, model), + RouteVerdict::RETRIES, "a replan with no recoveries allowed")}); +} + +UnitTestResult test_trainer_sight_once(){ + const ToyMap toy({".ss...#"}); + const RouteScore got = score(toy, {{0, 0}}, {5, 0}, {{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TO_WALL}}); + if (got.recoveries != 1 || got.expected_ms < (double)(got.nominal_ms + 45000)){ + return std::format("{} recoveries, expected {} ms", got.recoveries, got.expected_ms); + } + return true; +} + + +struct RouteScorerInput{ + std::string name; + UnitTestResult (*test)(); +}; + +struct RouteScorerExpectation{ + const char* description; +}; + +struct RouteScorerCase{ + RouteScorerInput input; + RouteScorerExpectation expectation; +}; + +class Test_RouteScorer : public UnitTest{ +public: + explicit Test_RouteScorer(RouteScorerCase scenario) + : UnitTest("Pokemon::Navigation - RouteScorer: " + scenario.input.name) + , m_case(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_case.input.test(); + } + +private: + RouteScorerCase m_case; +}; + +const RouteScorerCase ROUTE_SCORER_CASES[] = { + { + .input = {.name = "taps take a tap each", .test = test_taps_time}, + .expectation = {.description = "4 taps cost 4 taps and a press"}, + }, + { + .input = {.name = "a run to a wall beats taps", .test = test_run_to_wall_beats_taps}, + .expectation = {.description = "run to the wall is faster than the same tiles in taps"}, + }, + { + .input = {.name = "walls bring a set of tiles to one", .test = test_wall_collapses_a_set}, + .expectation = {.description = "PASS"}, + }, + { + .input = {.name = "an open hold with nothing to stop it fails", .test = test_open_hold_off_the_goal}, + .expectation = {.description = "FAIL: may end off the goal"}, + }, + { + .input = {.name = "an open hold may not overshoot into grass", .test = test_open_hold_into_grass}, + .expectation = {.description = "FAIL: overshoot onto grass"}, + }, + { + .input = {.name = "an open hold may not overshoot onto a ledge", .test = test_open_hold_onto_a_ledge}, + .expectation = {.description = "FAIL: overshoot over a ledge"}, + }, + { + .input = {.name = "an open hold may overshoot toward a wall", .test = test_open_hold_before_a_wall}, + .expectation = {.description = "FAIL when short of the goal, PASS with the wall after it"}, + }, + { + .input = {.name = "a hold may not walk into a warp", .test = test_wall_leg_through_a_warp}, + .expectation = {.description = "FAIL through a warp, PASS into the goal warp"}, + }, + { + .input = {.name = "the goal's trigger stops a run", .test = test_trigger_stops_a_run}, + .expectation = {.description = "PASS"}, + }, + { + .input = {.name = "grass charges interruptions", .test = test_grass_charges_interruptions}, + .expectation = {.description = "3 recoveries, expected and worst above nominal"}, + }, + { + .input = {.name = "taps in grass need a replan", .test = test_taps_in_grass_need_a_replan}, + .expectation = {.description = "FAIL without a replanner, PASS with 3 replans"}, + }, + { + .input = {.name = "a recovery back through the grass strands", .test = test_recovery_back_through_the_grass_strands}, + .expectation = {.description = "STRAND"}, + }, + { + .input = {.name = "recoveries in a row are capped", .test = test_too_many_recoveries}, + .expectation = {.description = "RETRIES"}, + }, + { + .input = {.name = "a trainer sees us once", .test = test_trainer_sight_once}, + .expectation = {.description = "one trainer battle charged"}, + }, +}; + +} // namespace + + +void add_tests_RouteScorer(UnitTestDatabase& database){ + for (const auto& scenario : ROUTE_SCORER_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index b6f5197ac7..6432ab7c74 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -23,6 +23,7 @@ #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h" #include "Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h" @@ -41,6 +42,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_Maps(database); add_tests_AutoStory_StoryWorld(database); add_tests_AutoStory_RoutePlanner(database); + add_tests_AutoStory_RouteBench(database); add_tests_AutoStory_StoryMaps(database); add_tests_AutoStory_Segment00(database); add_tests_AutoStory_StorySimulation(database); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_bench.golden.txt b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_bench.golden.txt new file mode 100644 index 0000000000..84ad6a6b40 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_bench.golden.txt @@ -0,0 +1,67 @@ +BDSP AutoStory: the route bench. Each ROUTE step of the story table, its +plan scored by Pokemon::score_route() as RouteWalker walks it (wall legs +held, at a run after 00.03; open legs tapped), then the user's routes for +three of them (TARGET). Written by the test "Route bench: no route scores +worse than Data/route_bench.golden.txt"; rerun it with PA_UPDATE_ROUTE_BENCH=1 +to rewrite this file. A route is worse when its verdict leaves PASS, its +expected time grows or one of its human ratios grows. +columns: case | expected ms (interruptions by chance) | worst ms (slowest start and +the costliest single interruption) | nominal ms (slowest start, none) | stops (wall +re-localizations) | recoveries (places an interruption may happen) | replans (of those, +the ones the plan cannot absorb) | slower than human (expected / human ms) | riskier +than human ((recoveries + 1) / (human's + 1)) | more backtracking than human ((stops + +replans + 1) / (human's stops + 1)) | the human's ms (the user's route, a recorded run, +or the stand-in: the shortest safe walk run with no stops) | verdict (why). A ratio +above 1.5 is flagged "!". + +00.01 below_the_flute | 4090 | 4090 | 4090 | 1 | 0 | 0 | 5.84! | 1.00 | 2.00! | 700 ms (stand-in) | PASS +00.01 above_the_door | 7230 | 7230 | 7230 | 1 | 0 | 0 | 4.66! | 1.00 | 2.00! | 1550 ms (stand-in) | PASS +00.01 short_of_barrys_door | 11950 | 11950 | 11950 | 1 | 0 | 0 | 4.35! | 1.00 | 2.00! | 2750 ms (stand-in) | PASS +00.01 above_barrys_door | 8200 | 8200 | 8200 | 0 | 0 | 0 | 5.29! | 1.00 | 1.00 | 1550 ms (stand-in) | PASS +00.03 into_rowans_scene | 3030 | 3030 | 3030 | 1 | 0 | 0 | 2.33! | 1.00 | 2.00! | 1300 ms (stand-in) | PASS +00.03 into_dawns_scene | 61510 | 46690 | 34340 | 4 | 22 | 0 | 5.37! | 1.15 | 5.00! | 11450 ms (stand-in) | PASS +00.04 onto_the_path | 4050 | 4050 | 4050 | 2 | 0 | 0 | 5.79! | 1.00 | 3.00! | 700 ms (stand-in) | PASS +00.04 to_ledge_column | 3850 | 3850 | 3850 | 1 | 0 | 0 | 3.21! | 1.00 | 2.00! | 1200 ms (stand-in) | PASS +00.04 along_route_201_road | 36400 | 36400 | 36400 | 0 | 0 | 0 | 2.96! | 1.00 | 0.33 | 12300 ms (user's route) | PASS +00.04 into_twinleaf | 26500 | 26500 | 26500 | 0 | 0 | 0 | 2.60! | 1.00 | 0.50 | 10200 ms (user's route) | PASS +00.04 to_moms_doorstep | 4100 | 4100 | 4100 | 0 | 0 | 0 | 5.47! | 1.00 | 1.00 | 750 ms (stand-in) | PASS +00.04 beside_mom | 900 | 900 | 900 | 0 | 0 | 0 | 2.25! | 1.00 | 1.00 | 400 ms (stand-in) | PASS +00.04 into_moms_call | 4300 | 4300 | 4300 | 0 | 0 | 0 | 5.38! | 1.00 | 1.00 | 800 ms (stand-in) | PASS +00.04 short_of_the_catch_tutorial | 84001 | 81950 | 49900 | 6 | 19 | 7 | 4.73! | 1.00 | 14.00! | 17750 ms (stand-in) | PASS +00.04b to_catch_grass | 9683 | 18650 | 6300 | 2 | 34 | 1 | 14.90! | 17.50! | 4.00! | 650 ms (stand-in) | STRAND (leg 3 interrupted at (115, 25): recovery from (114, 25)(115, 25)(116, 25): leg 2 interrupted at (115, 25): the recovery from (114, 25)(115, 25)(116, 25) leads back to itself) +00.04b into_sandgem | 9520 | 19400 | 7050 | 3 | 12 | 0 | 2.93! | 4.33! | 4.00! | 3250 ms (stand-in) | PASS +00.04b to_center_sign | 12300 | 12300 | 12300 | 0 | 0 | 0 | 6.00! | 1.00 | 1.00 | 2050 ms (stand-in) | PASS +00.04d north_to_jubilife | 73653 | 64350 | 33200 | 6 | 35 | 5 | 7.22! | 1.24 | 12.00! | 10200 ms (stand-in) | STRAND (leg 9 interrupted at (119, 5): recovery from (118, 5)(119, 5)(120, 5): leg 2 interrupted at (119, 5): the recovery from (118, 5)(119, 5)(120, 5) leads back to itself) +00.05 to_the_school | 9700 | 9700 | 9700 | 0 | 0 | 0 | 6.69! | 1.00 | 1.00 | 1450 ms (stand-in) | PASS +00.05b below_the_presidents_trigger | 4900 | 4900 | 4900 | 0 | 0 | 0 | 5.76! | 1.00 | 1.00 | 850 ms (stand-in) | PASS +00.05b below_the_tv_clown | 21463 | 23600 | 20750 | 1 | 1 | 0 | 4.57! | 2.00! | 2.00! | 4700 ms (stand-in) | PASS +00.05b below_the_company_clown | 21900 | 21900 | 21900 | 0 | 0 | 0 | 6.74! | 1.00 | 1.00 | 3250 ms (stand-in) | PASS +00.05c to_main_boulevard | 2500 | 2500 | 2500 | 0 | 0 | 0 | 3.57! | 1.00 | 1.00 | 700 ms (stand-in) | PASS +00.05c along_main_boulevard | 24100 | 24100 | 24100 | 0 | 0 | 0 | 7.42! | 1.00 | 1.00 | 3250 ms (stand-in) | PASS +00.05c beside_the_president | 10500 | 10500 | 10500 | 0 | 0 | 0 | 4.77! | 1.00 | 1.00 | 2200 ms (stand-in) | PASS +00.05c to_the_route_203_street | 21000 | 21000 | 21000 | 0 | 0 | 0 | 6.00! | 1.00 | 1.00 | 3500 ms (stand-in) | PASS +01.01 west_of_barrys_trigger | 7300 | 7300 | 7300 | 0 | 0 | 0 | 6.35! | 1.00 | 1.00 | 1150 ms (stand-in) | PASS +01.02 by_the_gate | 26465 | 27700 | 15350 | 1 | 9 | 0 | 3.84! | 1.00 | 2.00! | 6900 ms (stand-in) | PASS +01.02 west_of_the_hikers_trigger | 3950 | 3950 | 3950 | 2 | 0 | 0 | 8.78! | 1.00 | 3.00! | 450 ms (stand-in) | PASS +01.02 past_curtis | 10500 | 10500 | 10500 | 0 | 0 | 0 | 6.77! | 1.00 | 1.00 | 1550 ms (stand-in) | PASS +01.02 by_the_east_mouth | 4900 | 4900 | 4900 | 0 | 0 | 0 | 5.76! | 1.00 | 1.00 | 850 ms (stand-in) | PASS +01.02 west_of_the_welcome | 8550 | 8550 | 8550 | 2 | 0 | 0 | 9.00! | 1.00 | 3.00! | 950 ms (stand-in) | PASS +01.02b below_the_centers_door | 6663 | 8800 | 5950 | 2 | 1 | 0 | 2.38! | 2.00! | 3.00! | 2800 ms (stand-in) | PASS +01.03 above_the_mine | 16350 | 16350 | 16350 | 3 | 0 | 0 | 2.75! | 1.00 | 4.00! | 5950 ms (stand-in) | PASS +01.05 east_of_barrys_trigger | 26050 | 26050 | 26050 | 3 | 0 | 0 | 7.44! | 1.00 | 4.00! | 3500 ms (stand-in) | PASS +01.05 through_the_gate | 12050 | 12050 | 12050 | 5 | 0 | 0 | 4.92! | 1.00 | 6.00! | 2450 ms (stand-in) | PASS +01.06 up_jubilifes_road | 65760 | 70700 | 58350 | 3 | 10 | 4 | 5.77! | 2.20! | 8.00! | 11400 ms (stand-in) | STRAND (leg 4 interrupted at (98, 22): recovery from (97, 22)(98, 22)(99, 22): leg 2 interrupted at (116, 22): recovery from (115, 22)(116, 22)(117, 22): leg 2 interrupted at (116, 22): the recovery from (115, 22)(116, 22)(117, 22) leads back to itself) +01.06 below_rowans_trigger | 1950 | 1950 | 1950 | 1 | 0 | 0 | 2.29! | 1.00 | 2.00! | 850 ms (stand-in) | PASS +01.08 below_the_ravaged_path | 27098 | 25150 | 12800 | 3 | 12 | 0 | 4.52! | 1.30 | 4.00! | 6000 ms (stand-in) | PASS +01.09 west_of_the_rock | 7400 | 7400 | 7400 | 0 | 0 | 0 | 4.93! | 1.00 | 1.00 | 1500 ms (stand-in) | PASS +01.09 above_the_way_out | 4550 | 4550 | 4550 | 2 | 0 | 0 | 4.14! | 1.00 | 3.00! | 1100 ms (stand-in) | PASS +01.10 line_1 | 900 | 900 | 900 | 0 | 0 | 0 | 2.25! | 1.00 | 1.00 | 400 ms (stand-in) | PASS +01.10 line_2 | 7300 | 7300 | 7300 | 0 | 0 | 0 | 6.35! | 1.00 | 1.00 | 1150 ms (stand-in) | PASS +01.10 line_3 | 4100 | 4100 | 4100 | 0 | 0 | 0 | 4.10! | 1.00 | 1.00 | 1000 ms (stand-in) | PASS +01.10 line_4 | 6500 | 6500 | 6500 | 0 | 0 | 0 | 6.19! | 1.00 | 1.00 | 1050 ms (stand-in) | PASS +01.10 line_5 | 20388 | 39400 | 8100 | 0 | 6 | 6 | 10.46! | 1.17 | 7.00! | 1950 ms (stand-in) | PASS +01.10 line_6 | 6500 | 6500 | 6500 | 0 | 0 | 0 | 6.19! | 1.00 | 1.00 | 1050 ms (stand-in) | PASS +00.04 into_moms_call + the tap into her call | 5200 | 5200 | 5200 | 0 | 0 | 0 | 2.04! | 1.00 | 0.50 | 2550 ms (user's route) | PASS +TARGET 00.04 along_route_201_road | 11333 | 12300 | 12300 | 2 | 0 | 0 | 0.92 | 1.00 | 1.00 | 12300 ms (user's route) | FAIL (may end on (41, 56), off the goal) +TARGET 00.04 into_twinleaf | 10200 | 10200 | 10200 | 1 | 0 | 0 | 1.00 | 1.00 | 1.00 | 10200 ms (user's route) | PASS +TARGET 00.04 into_moms_call + the tap into her call | 2550 | 2550 | 2550 | 1 | 0 | 0 | 1.00 | 1.00 | 1.00 | 2550 ms (user's route) | PASS diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.cpp new file mode 100644 index 0000000000..ace057b60a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.cpp @@ -0,0 +1,591 @@ +/* BDSP AutoStory - Route Bench Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Scores the plan of every ROUTE step of the story table with the shared + * route scorer (Pokemon_RouteScorer.h), and the routes the user asked for + * on three of them, and checks that no route scores worse than + * Data/route_bench.golden.txt. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Filesystem/FileIO.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/Navigation/Pokemon_RouteScorer.h" +#include "Data/PokemonBDSP_AutoStory_WallRecovery.h" +#include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP_AutoStory_TableRoutes.h" +#include "PokemonBDSP_AutoStory_RouteBench_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using Pokemon::Direction; +using Pokemon::RouteScore; +using Pokemon::ScoredLeg; +using Pokemon::ScoredLegKind; +using Pokemon::TilePos; + +// A tap of walk_tiles_dpad(): it allows 800 ms a tile, and the console +// taps took about that (00.04's "west 16 (open)" took 12.8 s). +constexpr long long TAP_MS = 800; +// Confirming a stop at a wall: walk_until_dpad() watches a still screen. +constexpr long long WALL_STOP_MS = 1000; + +// One route to score: the plan the program walks today, or one hand-written. +struct BenchCase{ + std::string name; + const StoryWorld* world; + std::vector from; + std::vector goal; + std::vector triggers; // a scene starts here and stops the player + std::vector legs; + bool run = false; + std::optional costs; + bool planned = true; // false: no plan exists + // A human's route for this case (the user's, or a recorded run's), the + // bar the plan is measured against; none: the stand-in. + std::optional> human = std::nullopt; + std::string human_source = ""; +}; + +Pokemon::ScoreMap bench_map(const BenchCase& bench){ + const StoryWorld& world = *bench.world; + return { + .step = [&world](const TilePos& from, Direction direction) -> std::optional{ + const std::optional next = step(world, from, direction); + if (!next && world.tile(from.next(direction)) == Pokemon::TileKind::DOOR){ + return from.next(direction); + } + return next; + }, + .risk = [&world, &bench](const TilePos& pos){ + if (std::find(bench.triggers.begin(), bench.triggers.end(), pos) != bench.triggers.end()){ + return Pokemon::TileRisk::TRIGGER; + } + const std::optional tile = world.tile(pos); + if (tile == Pokemon::TileKind::DOOR){ + return Pokemon::TileRisk::WARP; + } + if (tile == Pokemon::TileKind::TALL_GRASS){ + return Pokemon::TileRisk::ENCOUNTER; + } + return wandering_hazard(world, pos) ? Pokemon::TileRisk::WANDERER : Pokemon::TileRisk::NONE; + }, + }; +} + +Pokemon::RoutePaces bench_paces(){ + return { + .ms_per_tile = [](Direction direction, bool run){ + return (long long)route_ms_per_tile(direction, run ? MoveSpeed::RUN : MoveSpeed::WALK).count(); + }, + .start_ms = ROUTE_START_DELAY.count(), + .tap_ms = TAP_MS, + .press_ms = ROUTE_TURN_TAP.count() * 2, + .stop_ms = WALL_STOP_MS, + }; +} + +// The legs as RouteWalker walks them: legs to a wall held (at a run once +// the Running Shoes are ours), open legs tapped. +std::vector walked_legs(const std::vector& legs, bool run){ + std::vector out; + for (const PlannedLeg& planned : legs){ + out.push_back({.direction = planned.leg.direction, .tiles = planned.leg.tiles, + .kind = planned.leg.ends_at_wall ? ScoredLegKind::TO_WALL : ScoredLegKind::TAPS, .run = run}); + } + return out; +} + +RouteScore score_case(const BenchCase& bench){ + if (!bench.planned){ + return {.verdict = Pokemon::RouteVerdict::FAIL, .why = "no plan"}; + } + const std::vector& targets = bench.goal; + const std::function goal = [&targets](const TilePos& pos){ + return std::find(targets.begin(), targets.end(), pos) != targets.end(); + }; + const Pokemon::RouteReplanner replan = [&](const std::vector& from) -> std::optional>{ + const std::optional> legs = plan_recovered_route(*bench.world, from, goal, bench.costs.value_or(RobustPlanCosts())); + if (!legs){ + return std::nullopt; + } + return walked_legs(*legs, bench.run); + }; + return Pokemon::score_route(bench_map(bench), bench.from, goal, bench.legs, bench_paces(), Pokemon::InterruptModel(), replan); +} + + +// The table's ROUTE steps from a known place, as the program plans them. +std::vector table_cases(){ + std::vector cases; + std::map seen; + for (const TableRoute& route : table_routes()){ + if (route.world == nullptr){ + continue; + } + std::string name = route.row + " " + route.step->name; + const size_t repeat = seen[name]++; + if (repeat > 0){ + name += std::format(" #{}", repeat + 1); + } + const RouteStepPlan plan = plan_table_route(route); + const bool run = route.row > std::string(RUNNING_SHOES_ROW); + cases.push_back({ + .name = name, .world = route.world, .from = plan.start, + .goal = world_tiles(*route.world, *route.step->target), .triggers = {}, + .legs = plan.legs ? walked_legs(*plan.legs, run) : std::vector{}, + .run = run, .costs = story_route_costs(route.step->variant), .planned = plan.legs.has_value(), + }); + } + return cases; +} + +size_t case_index(const std::vector& cases, const std::string& name){ + for (size_t i = 0; i < cases.size(); i++){ + if (cases[i].name == name){ + return i; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No table route " + name + "."); +} + +TilePos wall_from(const StoryWorld& world, const TilePos& from, Direction direction){ + return slide_to_wall(world, from, direction).stop; +} + +ScoredLeg taps(Direction direction, size_t tiles){ + return {.direction = direction, .tiles = tiles, .kind = ScoredLegKind::TAPS, .run = true}; +} +ScoredLeg run_to_wall(Direction direction, size_t tiles){ + return {.direction = direction, .tiles = tiles, .kind = ScoredLegKind::TO_WALL, .run = true}; +} +ScoredLeg run_open(Direction direction, size_t tiles){ + return {.direction = direction, .tiles = tiles, .kind = ScoredLegKind::OPEN_HOLD, .run = true}; +} + +// 00.04 "along_route_201_road": the console tapped "west 16 (open)" along +// Route 201's road at 800 ms a tile (lab-B 2026-11-09, step 9 of 00.04). +// The user's route: run west into the funnel of columns 36 to 39, whose +// walls stop a run north on row 9; run north, then west to the wall at +// column 13, a tap east onto column 15 and taps south over the ledge. +BenchCase road_target(const BenchCase& current){ + const StoryWorld& world = *current.world; + const TilePos start = current.from.front(); + const TilePos funnel = story_to_world(world, "Route201", {38, 14}); + const TilePos row9 = wall_from(world, funnel, Direction::NORTH); + const TilePos west = wall_from(world, row9, Direction::WEST); + const TilePos goal = current.goal.front(); + BenchCase target = current; + target.name = "TARGET " + current.name; + target.legs = { + run_open(Direction::WEST, (size_t)(start.x - funnel.x)), + run_to_wall(Direction::NORTH, (size_t)(funnel.y - row9.y)), + run_to_wall(Direction::WEST, (size_t)(row9.x - west.x)), + taps(Direction::EAST, (size_t)(goal.x - west.x)), + taps(Direction::SOUTH, 4), + }; + return target; +} + +// 00.04 "into_twinleaf": the console tapped "south 33 (open)" for 26 s +// (lab-B 2026-11-09, step 10 of 00.04), where the column ends at a wall. +// The user's route: run south to that wall, then tap back north. +BenchCase twinleaf_target(const BenchCase& current){ + const StoryWorld& world = *current.world; + const TilePos start = current.from.front(); + const TilePos wall = wall_from(world, start, Direction::SOUTH); + const TilePos goal = current.goal.front(); + BenchCase target = current; + target.name = "TARGET " + current.name; + target.legs = {run_to_wall(Direction::SOUTH, (size_t)(wall.y - start.y))}; + if (wall.y > goal.y){ + target.legs.push_back(taps(Direction::NORTH, (size_t)(wall.y - goal.y))); + } + return target; +} + +// 00.04 "into_moms_call": from the room's east corner the plan walks round +// Mom to (7, 9), then taps west into her call on (6, 9) (lab-B 2026-11-09 +// 17:29, step 17 of 00.04). Scored to the trigger: the route's legs and +// the tap after them. +BenchCase moms_call_current(const BenchCase& route){ + const StoryWorld& world = *route.world; + BenchCase current = route; + current.name = "00.04 into_moms_call + the tap into her call"; + current.goal = {story_to_world(world, "PlayerHouse1F", {6, 9})}; + current.triggers = current.goal; + current.legs.push_back(taps(Direction::WEST, 1)); + return current; +} + +// The user's route: down to row 9, whose wall row 10 does not stop us, so +// a tap; then run west along row 9 until her call stops us on (6, 9). +BenchCase moms_call_target(const BenchCase& current){ + BenchCase target = current; + target.name = "TARGET " + current.name; + target.legs = {taps(Direction::WEST, 1), taps(Direction::SOUTH, 1), run_to_wall(Direction::WEST, 4)}; + return target; +} + +// A human run recorded on the console, as legs: replaces a case's stand-in. +struct RecordedHumanRun{ + std::string case_name; + std::vector legs; + std::string source; // the run's log +}; +// The hook for recorded human runs (a log of a human playing, turned into +// legs). None recorded yet. +std::vector recorded_human_runs(){ + return {}; +} + +// Adds `target` after the case it improves, and makes it that case's human +// route: the user described each of them. +void add_target(std::vector& cases, const std::string& name, const std::function& make){ + BenchCase& current = cases[case_index(cases, name)]; + BenchCase target = make(current); + current.human = target.legs; + current.human_source = "user's route"; + target.human = target.legs; + target.human_source = "user's route"; + cases.push_back(std::move(target)); +} + +std::vector bench_cases(){ + std::vector cases = table_cases(); + cases.push_back(moms_call_current(cases[case_index(cases, "00.04 into_moms_call")])); + add_target(cases, "00.04 along_route_201_road", road_target); + add_target(cases, "00.04 into_twinleaf", twinleaf_target); + add_target(cases, "00.04 into_moms_call + the tap into her call", moms_call_target); + for (const RecordedHumanRun& run : recorded_human_runs()){ + BenchCase& bench = cases[case_index(cases, run.case_name)]; + bench.human = run.legs; + bench.human_source = "recorded: " + run.source; + } + return cases; +} + + +constexpr const char* BENCH_HEADER = + "BDSP AutoStory: the route bench. Each ROUTE step of the story table, its\r\n" + "plan scored by Pokemon::score_route() as RouteWalker walks it (wall legs\r\n" + "held, at a run after 00.03; open legs tapped), then the user's routes for\r\n" + "three of them (TARGET). Written by the test \"Route bench: no route scores\r\n" + "worse than Data/route_bench.golden.txt\"; rerun it with PA_UPDATE_ROUTE_BENCH=1\r\n" + "to rewrite this file. A route is worse when its verdict leaves PASS, its\r\n" + "expected time grows or one of its human ratios grows.\r\n" + "columns: case | expected ms (interruptions by chance) | worst ms (slowest start and\r\n" + "the costliest single interruption) | nominal ms (slowest start, none) | stops (wall\r\n" + "re-localizations) | recoveries (places an interruption may happen) | replans (of those,\r\n" + "the ones the plan cannot absorb) | slower than human (expected / human ms) | riskier\r\n" + "than human ((recoveries + 1) / (human's + 1)) | more backtracking than human ((stops +\r\n" + "replans + 1) / (human's stops + 1)) | the human's ms (the user's route, a recorded run,\r\n" + "or the stand-in: the shortest safe walk run with no stops) | verdict (why). A ratio\r\n" + "above 1.5 is flagged \"!\".\r\n" + "\r\n"; + +// The bar a case's plan is measured against: a human's walk of it. +struct HumanBaseline{ + long long ms = 0; + size_t risk_tiles = 0; // places an interruption may happen + size_t stops = 0; // re-localization stops + std::string source; +}; + +// A step of the stand-in's search: tiles walked, grass and wanderer tiles +// avoided where a way round exists. +struct StandInNode{ + long long cost; + long long ms; + size_t risk; + TilePos pos; + bool operator>(const StandInNode& other) const{ + return cost > other.cost; + } +}; + +using StandInQueue = std::priority_queue, std::greater>; + +bool in_goal(const BenchCase& bench, const TilePos& pos){ + return std::find(bench.goal.begin(), bench.goal.end(), pos) != bench.goal.end(); +} + +// Queues the steps from `node` the stand-in may take: not through a warp +// or a trigger off the goal, and round grass and wanderers where it can. +void push_steps(StandInQueue& open, const BenchCase& bench, const Pokemon::ScoreMap& map, + const Pokemon::RoutePaces& paces, const StandInNode& node +){ + for (Direction direction : Pokemon::ALL_DIRECTIONS){ + const std::optional next = map.step(node.pos, direction); + if (!next){ + continue; + } + const Pokemon::TileRisk risk = map.risk(*next); + if ((risk == Pokemon::TileRisk::WARP || risk == Pokemon::TileRisk::TRIGGER) && !in_goal(bench, *next)){ + continue; + } + const long long tiles = std::abs(next->x - node.pos.x) + std::abs(next->y - node.pos.y); + const bool risky = risk == Pokemon::TileRisk::ENCOUNTER || risk == Pokemon::TileRisk::WANDERER; + open.push({node.cost + tiles + (risky ? 1000 : 0), node.ms + tiles * paces.ms_per_tile(direction, true), + node.risk + (risky ? 1 : 0), *next}); + } +} + +// The shortest safe walk from `start` to the goal, run the whole way. +std::optional stand_in_from(const BenchCase& bench, const TilePos& start){ + const Pokemon::ScoreMap map = bench_map(bench); + const Pokemon::RoutePaces paces = bench_paces(); + StandInQueue open; + std::set> done; + open.push({0, paces.start_ms, 0, start}); + while (!open.empty() && done.size() < 100000){ + const StandInNode node = open.top(); + open.pop(); + if (!done.insert({node.pos.x, node.pos.y}).second){ + continue; + } + if (in_goal(bench, node.pos)){ + return HumanBaseline{node.ms, node.risk, 0, "stand-in"}; + } + push_steps(open, bench, map, paces, node); + } + return std::nullopt; +} + +// For a case with no human route: the shortest safe walk from its slowest +// start, run the whole way, with no stops (as a player who sees the map +// walks). Nothing if no walk reaches the goal. +std::optional stand_in(const BenchCase& bench){ + std::optional slowest; + for (const TilePos& start : bench.from){ + const std::optional walk = stand_in_from(bench, start); + if (walk && (!slowest || slowest->ms < walk->ms)){ + slowest = walk; + } + } + return slowest; +} + +std::optional human_baseline(const BenchCase& bench){ + if (!bench.human){ + return stand_in(bench); + } + BenchCase human = bench; + human.legs = *bench.human; + const RouteScore score = score_case(human); + return HumanBaseline{score.nominal_ms, score.recoveries, score.stops, bench.human_source}; +} + +// "1.23", with "!" past 1.5: a plan that far behind the human is flagged. +std::string ratio_text(double ratio){ + return std::format("{:.2f}{}", ratio, ratio > 1.5 ? "!" : ""); +} + +// slower | riskier | more backtracking than the human, and the human's time. +std::string human_columns(const RouteScore& score, const std::optional& human){ + if (!human || human->ms <= 0){ + return "- | - | - | no human baseline"; + } + const double slower = score.expected_ms / (double)human->ms; + const double riskier = (double)(score.recoveries + 1) / (double)(human->risk_tiles + 1); + const double backtracking = (double)(score.stops + score.replans + 1) / (double)(human->stops + 1); + return std::format("{} | {} | {} | {} ms ({})", ratio_text(slower), ratio_text(riskier), ratio_text(backtracking), + human->ms, human->source); +} + +std::string bench_line(const BenchCase& bench, const RouteScore& score){ + std::string line = std::format("{} | {} | {} | {} | {} | {} | {} | {} | {}", bench.name, (long long)(score.expected_ms + 0.5), + score.worst_ms, score.nominal_ms, score.stops, score.recoveries, score.replans, + human_columns(score, human_baseline(bench)), Pokemon::verdict_name(score.verdict)); + return score.why.empty() ? line : line + " (" + score.why + ")"; +} + +std::string bench_text(){ + std::string out = BENCH_HEADER; + for (const BenchCase& bench : bench_cases()){ + out += bench_line(bench, score_case(bench)) + "\r\n"; + } + return out; +} + +// A bench line's columns. +std::vector bench_fields(const std::string& line){ + std::vector fields; + size_t begin = 0; + while (true){ + const size_t end = line.find(" | ", begin); + fields.push_back(line.substr(begin, end == std::string::npos ? std::string::npos : end - begin)); + if (end == std::string::npos){ + return fields; + } + begin = end + 3; + } +} + +// A bench line's expected time and whether it passed. +struct GoldenRow{ + long long expected_ms; + bool pass; + std::vector ratios; // slower, riskier, backtracking; empty without a human +}; +// The rows of a bench text, by case name. +std::map golden_rows(const std::string& text){ + std::map rows; + size_t begin = 0; + bool body = false; // past the header's blank line + while (begin < text.size()){ + const size_t end = std::min(text.find('\n', begin), text.size()); + std::string line = text.substr(begin, end - begin); + begin = end + 1; + std::erase(line, '\r'); + const size_t first = line.find(" | "); + if (!body || first == std::string::npos){ + body = body || line.empty(); + continue; + } + const std::vector fields = bench_fields(line); + GoldenRow row{std::atoll(fields[1].c_str()), line.find(" | PASS") != std::string::npos, {}}; + for (size_t i = 7; i < 10 && i < fields.size() && fields[i] != "-"; i++){ + row.ratios.push_back(std::atof(fields[i].c_str())); + } + rows[fields[0]] = std::move(row); + } + return rows; +} + +std::string bench_golden_path(){ + const char* path = std::getenv("PA_ROUTE_BENCH_GOLDEN"); + if (path != nullptr && path[0] != '\0'){ + return path; + } + const std::string self = __FILE__; + const size_t slash = self.find_last_of("/\\"); + return (slash == std::string::npos ? std::string() : self.substr(0, slash + 1)) + "Data/route_bench.golden.txt"; +} + +// Whether any of `now`'s human ratios grew from `was`'s. +bool ratio_grew(const GoldenRow& was, const GoldenRow& now){ + for (size_t i = 0; i < std::min(was.ratios.size(), now.ratios.size()); i++){ + if (now.ratios[i] > was.ratios[i] + 0.005){ + return true; + } + } + return false; +} + +// Each route of `now` that scores worse than in `golden`. +std::string worse_routes(const std::string& golden, const std::string& now){ + const std::map before = golden_rows(golden); + std::string out; + for (const auto& [name, row] : golden_rows(now)){ + const auto was = before.find(name); + if (was == before.end()){ + continue; + } + if ((was->second.pass && !row.pass) || row.expected_ms > was->second.expected_ms || ratio_grew(was->second, row)){ + out += std::format("\n {}: {} ms{} -> {} ms{}", name, was->second.expected_ms, was->second.pass ? "" : " (not PASS)", + row.expected_ms, row.pass ? "" : " (not PASS)"); + } + } + return out; +} + +UnitTestResult test_route_bench(Logger& logger){ + const std::string path = bench_golden_path(); + const std::string now = bench_text(); + logger.log("Route bench:\n" + now); + const char* update = std::getenv("PA_UPDATE_ROUTE_BENCH"); + if (update != nullptr && update[0] != '\0' && update[0] != '0'){ + FileIO file; + if (!file.open(path, FileMode::WRITE | FileMode::BINARY) || file.write(now) != now.size()){ + return "Could not write " + path + "."; + } + logger.log("Wrote " + path + "."); + return true; + } + std::string golden; + if (!file_to_string(path, golden)){ + return "Could not read " + path + " (set PA_ROUTE_BENCH_GOLDEN to its path)."; + } + const std::string worse = worse_routes(golden, now); + if (worse.empty()){ + return true; + } + return "Routes score worse than " + path + " (rerun with PA_UPDATE_ROUTE_BENCH=1 if meant):" + worse; +} + + +struct RouteBenchInput{ + std::string name; + UnitTestResult (*test)(Logger&); +}; + +struct RouteBenchExpectation{ + const char* description; +}; + +struct RouteBenchCase{ + RouteBenchInput input; + RouteBenchExpectation expectation; +}; + +class Test_AutoStoryRouteBench : public UnitTest{ +public: + explicit Test_AutoStoryRouteBench(RouteBenchCase scenario) + : UnitTest("PokemonBDSP::AutoStory - Route bench: " + scenario.input.name) + , m_case(std::move(scenario)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.test(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + RouteBenchCase m_case; +}; + +const RouteBenchCase ROUTE_BENCH_CASES[] = { + { + .input = {.name = "no route scores worse than Data/route_bench.golden.txt", .test = test_route_bench}, + .expectation = {.description = "every route's verdict and expected time at least as good as the golden file's"}, + }, +}; + +} // namespace + + +void add_tests_AutoStory_RouteBench(UnitTestDatabase& database){ + for (const auto& scenario : ROUTE_BENCH_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.h new file mode 100644 index 0000000000..ef237aaaa4 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.h @@ -0,0 +1,25 @@ +/* BDSP AutoStory - Route Bench Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RouteBench_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RouteBench_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// The route bench: every story table route's plan scored, against a golden file. +void add_tests_AutoStory_RouteBench(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index c35f269f68..983820c256 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -27,6 +27,7 @@ #include "Actions/PokemonBDSP_AutoStory_Events.h" #include "PokemonBDSP_AutoStory_StoryExecutor.h" #include "PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_TableRoutes.h" #include "PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_StoryTable_Tests.h" #include "PokemonBDSP_AutoStory_StoryWalkSteps.h" @@ -254,90 +255,6 @@ UnitTestResult test_line_5_recovery_pins_the_wall_nearest_the_goal(Logger& logge return true; } -// A ROUTE step of the table, and where the steps before it in its row leave -// the player: the row's start, then each step's target or pose_after. A LEGS -// or STEP step that does not say where it ends leaves the start unknown. -struct TableRoute{ - std::string row; - const Pokemon::StoryStep* step; - std::optional from; - // The world the step is planned on; none if the start is unknown or no - // world joins its map and the target's. - const StoryWorld* world; -}; - -std::optional pose_after_step(const std::optional& at, const Pokemon::StoryStep& step){ - if (step.kind == StoryStepKind::ROUTE){ - return step.target; - } - if (step.pose_after){ - return step.pose_after; - } - return step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP ? std::nullopt : at; -} - -// A ROUTE step after a "measured" LEGS step plans from the one tile the -// taps measured: one TableRoute for each tile of `at`. -void add_measured_routes(std::vector& routes, const std::string& row, const Pokemon::StoryStep& step, const Pokemon::Pose& at){ - for (const TilePos& pos : Pokemon::tiles_of(at)){ - const Pokemon::Pose one = Pokemon::tile_pose(at.map, {pos}, Pokemon::facing_of(at)); - routes.push_back({row, &step, one, story_plan_world(at.map, step.target->map)}); - } -} - -std::vector table_routes(){ - std::vector routes; - for (const StoryCheckpoint& row : story_checkpoints()){ - std::optional at = row.start; - bool measured = false; - for (const Pokemon::StoryStep& step : row.steps){ - const bool known = at && !Pokemon::tiles_of(*at).empty(); - if (step.kind == StoryStepKind::ROUTE && known && std::exchange(measured, false)){ - add_measured_routes(routes, row.id, step, *at); - }else if (step.kind == StoryStepKind::ROUTE){ - routes.push_back({row.id, &step, at, known ? story_plan_world(at->map, step.target->map) : nullptr}); - } - measured = false; - if (step.kind == StoryStepKind::LEGS && step.variant == "measured" && known && !step.pose_after){ - at = measured_ends(*at, step); - measured = at.has_value(); - continue; - } - at = pose_after_step(at, step); - } - } - return routes; -} - -std::vector world_tiles(const StoryWorld& world, const Pokemon::Pose& pose){ - std::vector tiles; - for (const TilePos& pos : Pokemon::tiles_of(pose)){ - tiles.push_back(story_to_world(world, pose.map, pos)); - } - return tiles; -} - -// The legs a table ROUTE step plans, as walk_route() plans them: the step's -// costs, then the default ones; no legs if neither plans. -struct RouteStepPlan{ - std::vector start; - std::optional> legs; - bool default_costs = false; // the step's own costs found no plan -}; - -RouteStepPlan plan_table_route(const TableRoute& route){ - const StoryWorld& world = *route.world; - const std::vector targets = world_tiles(world, *route.step->target); - const auto goal = [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }; - RouteStepPlan plan{.start = world_tiles(world, *route.from)}; - plan.legs = plan_recovered_route(world, plan.start, goal, *story_route_costs(route.step->variant)); - if (!plan.legs){ - plan.legs = plan_recovered_route(world, plan.start, goal, RobustPlanCosts()); - plan.default_costs = plan.legs.has_value(); - } - return plan; -} - // Why `planned` may slide into a door or a warp, or "": an open leg (not to // a wall) that may end on the tile before one, walking toward it. A part of // a tile too far takes the warp (lab-B 2026-11-08 15:31 to 15:54: 01.05's diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.cpp new file mode 100644 index 0000000000..2d28dc76c2 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.cpp @@ -0,0 +1,97 @@ +/* BDSP AutoStory - Table Routes + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Data/PokemonBDSP_AutoStory_WallRecovery.h" +#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_TableRoutes.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + + +namespace{ + +std::optional pose_after_step(const std::optional& at, const Pokemon::StoryStep& step){ + if (step.kind == StoryStepKind::ROUTE){ + return step.target; + } + if (step.pose_after){ + return step.pose_after; + } + return step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP ? std::nullopt : at; +} + +// A ROUTE step after a "measured" LEGS step plans from the one tile the +// taps measured: one TableRoute for each tile of `at`. +void add_measured_routes(std::vector& routes, const std::string& row, const Pokemon::StoryStep& step, const Pokemon::Pose& at){ + for (const TilePos& pos : Pokemon::tiles_of(at)){ + const Pokemon::Pose one = Pokemon::tile_pose(at.map, {pos}, Pokemon::facing_of(at)); + routes.push_back({row, &step, one, story_plan_world(at.map, step.target->map)}); + } +} + +} // namespace + + +std::vector table_routes(){ + std::vector routes; + for (const StoryCheckpoint& row : story_checkpoints()){ + std::optional at = row.start; + bool measured = false; + for (const Pokemon::StoryStep& step : row.steps){ + const bool known = at && !Pokemon::tiles_of(*at).empty(); + if (step.kind == StoryStepKind::ROUTE && known && std::exchange(measured, false)){ + add_measured_routes(routes, row.id, step, *at); + }else if (step.kind == StoryStepKind::ROUTE){ + routes.push_back({row.id, &step, at, known ? story_plan_world(at->map, step.target->map) : nullptr}); + } + measured = false; + if (step.kind == StoryStepKind::LEGS && step.variant == "measured" && known && !step.pose_after){ + at = measured_ends(*at, step); + measured = at.has_value(); + continue; + } + at = pose_after_step(at, step); + } + } + return routes; +} + +std::vector world_tiles(const StoryWorld& world, const Pokemon::Pose& pose){ + std::vector tiles; + for (const TilePos& pos : Pokemon::tiles_of(pose)){ + tiles.push_back(story_to_world(world, pose.map, pos)); + } + return tiles; +} + +RouteStepPlan plan_table_route(const TableRoute& route){ + const StoryWorld& world = *route.world; + const std::vector targets = world_tiles(world, *route.step->target); + const auto goal = [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }; + RouteStepPlan plan{.start = world_tiles(world, *route.from)}; + plan.legs = plan_recovered_route(world, plan.start, goal, *story_route_costs(route.step->variant)); + if (!plan.legs){ + plan.legs = plan_recovered_route(world, plan.start, goal, RobustPlanCosts()); + plan.default_costs = plan.legs.has_value(); + } + return plan; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.h new file mode 100644 index 0000000000..35553d0bd2 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.h @@ -0,0 +1,60 @@ +/* BDSP AutoStory - Table Routes + * + * From: https://github.com/PokemonAutomation/ + * + * The story table's ROUTE steps, each from where the steps before it in + * its row leave the player, and the legs the program plans for them: what + * the route tests and the route bench check. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_TableRoutes_H +#define PokemonAutomation_PokemonBDSP_AutoStory_TableRoutes_H + +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_StorySteps.h" +#include "Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "Data/PokemonBDSP_AutoStory_StoryWorld.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// A ROUTE step of the table, and where the steps before it in its row leave +// the player: the row's start, then each step's target or pose_after. A LEGS +// or STEP step that does not say where it ends leaves the start unknown. +struct TableRoute{ + std::string row; + const Pokemon::StoryStep* step; + std::optional from; + // The world the step is planned on; none if the start is unknown or no + // world joins its map and the target's. + const StoryWorld* world; +}; + +// Every ROUTE step of the story table, in table order. +std::vector table_routes(); + +// The world tiles of `pose` on `world`. +std::vector world_tiles(const StoryWorld& world, const Pokemon::Pose& pose); + +// The legs a table ROUTE step plans, as walk_route() plans them: the step's +// costs, then the default ones; no legs if neither plans. +struct RouteStepPlan{ + std::vector start; + std::optional> legs; + bool default_costs = false; // the step's own costs found no plan +}; + +// Plans `route`, which must have a world. +RouteStepPlan plan_table_route(const TableRoute& route); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 165cf4edb2..04e96fea00 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1475,6 +1475,9 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_RouteLog.cpp Source/Pokemon/Navigation/Pokemon_RouteLog.h Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp + Source/Pokemon/Navigation/Pokemon_RouteScorer.cpp + Source/Pokemon/Navigation/Pokemon_RouteScorer.h + Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp Source/Pokemon/Options/Pokemon_BoxSortingTable.cpp Source/Pokemon/Options/Pokemon_BoxSortingTable.h Source/Pokemon/Options/Pokemon_EncounterBotOptions.h @@ -1762,6 +1765,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.h Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.h Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.cpp @@ -1793,6 +1798,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp From e5fa8bb0c47074bbaf553e6c979316aa9b9e127f Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 18:54:35 -0800 Subject: [PATCH 120/166] BDSP AutoStory sim: Mom's call verify runs as evidence for (6, 9) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp index 4880edf3dc..314d254659 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -355,6 +355,8 @@ std::vector console_triggers(){ // it went out of the door, where the same step on 2026-11-04 12:20, // pressed inside her scene, moved nobody. The map has the mat (6, 10) // (r45, r46: her line came after that step was pressed). + // Verify runs 1-3 (lab-B 2026-11-09 18:19, 18:30, 18:41): from (7, 9) + // west, her call stopped us after at most 1 tile, on (6, 9) each time. {.map = "PlayerHouse1F", .name = "moms_call", .tiles = {{6, 9}}}, }; } From c3f7bd282686706a3af16e96af8c4e74101da3ed Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 9 Nov 2026 18:59:49 -0800 Subject: [PATCH 121/166] BDSP AutoStory: a leg record per walked leg, and a route diff against the sim Each leg the story's walks take writes one "[Leg] {json}" line: checkpoint, event, leg, the plan (direction, tiles, open/wall/tile end, the tiles it may end on), the taps that moved, chunks and held time, where it ended and how that is known, and its interruptions. The record and its tracer are shared (Pokemon_LegTrace); BDSP writes them through a RouteIO wrapper in StoryWalkSteps, so the console and the simulation write the same records: the planned route walker's legs are read from its own route lines, the story's tap, wall and dialogue legs mark theirs. devtools/maps/leg_trace.py replays a log into a trace (from the records, or from an older log's route lines) and grades it against the simulation's, leg by leg: OK, drift (re-synced by a later wall or count), LARGE, or masked after an interruption until the route re-syncs. It exits 1 only on LARGE. 00.04's simulation trace is checked in, with tests that the simulation writes it and writes the same every run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013VUubhHeYSMGSSDXZkKZss --- .../Pokemon/Navigation/Pokemon_LegTrace.cpp | 266 ++++++++++++ .../Pokemon/Navigation/Pokemon_LegTrace.h | 165 ++++++++ .../Navigation/Pokemon_LegTrace_Tests.cpp | 167 ++++++++ .../Navigation/Pokemon_Navigation_Tests.h | 2 + .../Navigation/Pokemon_RouteLog_Tests.cpp | 2 + .../PokemonBDSP_AutoStory_StoryWalkSteps.cpp | 103 +++-- .../PokemonBDSP_AutoStory_StoryWalkSteps.h | 7 + .../PokemonBDSP_AutoStory_LegTrace_Tests.cpp | 190 +++++++++ .../PokemonBDSP_AutoStory_LegTrace_Tests.h | 25 ++ .../PokemonBDSP_AutoStory_StorySim.h | 5 + .../PokemonBDSP_AutoStory_StorySim_Tests.cpp | 2 + .../Simulation/leg_trace_00.04.golden.json | 39 ++ .../PokemonBDSP_AutoStory_LegTraceIO.cpp | 118 ++++++ .../Utils/PokemonBDSP_AutoStory_LegTraceIO.h | 72 ++++ SerialPrograms/cmake/SourceFiles.cmake | 7 + devtools/maps/README.md | 19 + devtools/maps/leg_trace.py | 387 ++++++++++++++++++ devtools/maps/tests/test_leg_trace.py | 199 +++++++++ 18 files changed, 1751 insertions(+), 24 deletions(-) create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.h create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/leg_trace_00.04.golden.json create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegTraceIO.cpp create mode 100644 SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegTraceIO.h create mode 100644 devtools/maps/leg_trace.py create mode 100644 devtools/maps/tests/test_leg_trace.py diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace.cpp new file mode 100644 index 0000000000..9e2a6cbfd5 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace.cpp @@ -0,0 +1,266 @@ +/* Leg Trace + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon_LegTrace.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const char* leg_end_kind_name(LegEndKind kind){ + switch (kind){ + case LegEndKind::OPEN: + return "open"; + case LegEndKind::WALL: + return "wall"; + case LegEndKind::TILE: + return "tile"; + } + return "?"; +} + +const char* leg_end_known_name(LegEndKnown known){ + switch (known){ + case LegEndKnown::WALL: + return "wall"; + case LegEndKnown::FADE: + return "fade"; + case LegEndKnown::DIALOGUE: + return "dialogue"; + case LegEndKnown::COUNTED: + return "counted"; + case LegEndKnown::DEAD_RECKONED: + return "dead_reckoned"; + case LegEndKnown::SEEN: + return "seen"; + case LegEndKnown::UNKNOWN: + return "unknown"; + } + return "?"; +} + +const char* leg_interrupt_name(LegInterrupt interrupt){ + switch (interrupt){ + case LegInterrupt::WILD_BATTLE: + return "wild_battle"; + case LegInterrupt::TRAINER: + return "trainer"; + case LegInterrupt::SCENE: + return "scene"; + case LegInterrupt::DIALOGUE: + return "dialogue"; + } + return "?"; +} + + +namespace{ + +// [["Route 202", 23, 25], ...] +JsonArray tiles_json(const std::vector& tiles){ + JsonArray out; + for (const RouteTile& tile : tiles){ + JsonArray entry; + entry.push_back(tile.map); + entry.push_back((int64_t)tile.pos.x); + entry.push_back((int64_t)tile.pos.y); + out.push_back(std::move(entry)); + } + return out; +} + +} // namespace + +std::string leg_trace_json(const LegRecord& record){ + JsonObject out; + out["checkpoint"] = record.checkpoint; + out["event"] = record.event; + out["leg"] = (int64_t)record.leg; + out["dir"] = direction_name(record.plan.direction); + out["tiles"] = (int64_t)record.plan.tiles; + out["end_kind"] = leg_end_kind_name(record.plan.end_kind); + out["planned_end"] = tiles_json(record.plan.ends); + if (record.moved){ + out["moved"] = (int64_t)*record.moved; + } + out["chunks"] = (int64_t)record.chunks; + out["ms"] = record.walked_ms; + out["end"] = tiles_json(record.end); + out["known"] = leg_end_known_name(record.known); + JsonArray interrupts; + for (LegInterrupt interrupt : record.interrupts){ + interrupts.push_back(leg_interrupt_name(interrupt)); + } + out["interrupts"] = std::move(interrupts); + if (!record.note.empty()){ + out["note"] = record.note; + } + return out.dump(-1); +} + +std::string leg_trace_line(const LegRecord& record){ + return LEG_TRACE_TAG + leg_trace_json(record); +} + + +namespace{ + +std::optional parse_int(std::string_view text){ + int value = 0; + const char* end = text.data() + text.size(); + const auto result = std::from_chars(text.data(), end, value); + if (result.ec != std::errc() || result.ptr != end){ + return std::nullopt; + } + return value; +} + +// "Route 202 (23, 25)". +std::optional parse_route_tile(std::string_view text){ + const size_t open = text.rfind(" ("); + const size_t comma = text.rfind(", "); + if (open == std::string_view::npos || comma == std::string_view::npos || comma < open || !text.ends_with(")")){ + return std::nullopt; + } + const std::optional x = parse_int(text.substr(open + 2, comma - open - 2)); + const std::optional y = parse_int(text.substr(comma + 2, text.size() - comma - 3)); + if (open == 0 || !x || !y){ + return std::nullopt; + } + return RouteTile{std::string(text.substr(0, open)), TilePos{*x, *y}}; +} + +std::optional parse_direction(std::string_view text){ + for (Direction direction : ALL_DIRECTIONS){ + if (text == direction_name(direction)){ + return direction; + } + } + return std::nullopt; +} + +} // namespace + +std::vector parse_route_tiles(std::string_view text){ + std::vector out; + while (!text.empty()){ + // Each tile ends at its ")"; ", " separates them. + const size_t close = text.find(')'); + if (close == std::string_view::npos){ + return {}; + } + const std::optional tile = parse_route_tile(text.substr(0, close + 1)); + if (!tile){ + return {}; + } + out.push_back(*tile); + text.remove_prefix(close + 1); + if (text.starts_with(", ")){ + text.remove_prefix(2); + }else if (!text.empty()){ + return {}; + } + } + return out; +} + +std::optional parse_route_leg_line(std::string_view text){ + // "Leg /: () to " + if (!text.starts_with("Leg ")){ + return std::nullopt; + } + const size_t colon = text.find(": "); + if (colon == std::string_view::npos){ + return std::nullopt; + } + text.remove_prefix(colon + 2); + const size_t space = text.find(' '); + const size_t open = text.find(" ("); + const size_t close = text.find(") to "); + if (space == std::string_view::npos || open == std::string_view::npos || close == std::string_view::npos + || !(space <= open && open < close)){ + return std::nullopt; + } + const std::optional direction = parse_direction(text.substr(0, space)); + const std::optional tiles = parse_int(text.substr(space + 1, open - space - 1)); + const std::string_view end = text.substr(open + 2, close - open - 2); + if (!direction || !tiles || *tiles < 0){ + return std::nullopt; + } + LegPlan plan{.direction = *direction, .tiles = (size_t)*tiles}; + if (end == "to wall"){ + plan.end_kind = LegEndKind::WALL; + }else if (end == "warp"){ + plan.end_kind = LegEndKind::TILE; + }else if (end == "open"){ + plan.end_kind = LegEndKind::OPEN; + }else{ + return std::nullopt; + } + plan.ends = parse_route_tiles(text.substr(close + 5)); + return plan; +} + + +void LegTracer::begin_event(const std::string& checkpoint, const std::string& event){ + end_event(); + m_checkpoint = checkpoint; + m_event = event; + m_legs = 0; +} + +void LegTracer::end_event(){ + if (m_leg){ + end_leg({}, LegEndKnown::UNKNOWN); + } +} + +void LegTracer::begin_leg(LegPlan plan){ + end_event(); + m_leg = LegRecord{.checkpoint = m_checkpoint, .event = m_event, .leg = ++m_legs, .plan = std::move(plan)}; +} + +void LegTracer::walked(const LegWalk& walk){ + if (!m_leg){ + return; + } + m_leg->chunks += walk.chunks; + m_leg->walked_ms += walk.walked_ms; + for (size_t i = 0; i < walk.wild_battles; i++){ + m_leg->interrupts.push_back(LegInterrupt::WILD_BATTLE); + } + if (walk.tapped){ + m_leg->moved = m_leg->moved.value_or(0) + *walk.tapped; + } +} + +void LegTracer::interrupted(LegInterrupt interrupt){ + if (m_leg){ + m_leg->interrupts.push_back(interrupt); + } +} + +void LegTracer::end_leg(std::vector end, LegEndKnown known, std::string note){ + if (!m_leg){ + return; + } + LegRecord record = std::move(*m_leg); + m_leg.reset(); + record.end = std::move(end); + record.known = known; + record.note = std::move(note); + m_emit(leg_trace_line(record)); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace.h new file mode 100644 index 0000000000..ac450f7f19 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace.h @@ -0,0 +1,165 @@ +/* Leg Trace + * + * From: https://github.com/PokemonAutomation/ + * + * One structured record per walked leg, shared by the games' walkers and + * their simulations, so a console run's route can be compared leg by leg + * with the simulation's (devtools/maps/leg_trace.py). Each leg is one log + * line beside the free-text route lines: + * + * [Leg] {"checkpoint":"00.04","event":"to_the_signs_row","leg":1, + * "dir":"north","tiles":1,"end_kind":"tile","moved":1,...} + * + * A record holds what was planned (direction, tiles, how the leg ends and + * the tiles it may end on), what was measured (taps that moved, the + * walk's moved chunks and held time), where the leg ended and how that is + * known, and what interrupted it. + * + */ + +#ifndef PokemonAutomation_Pokemon_LegTrace_H +#define PokemonAutomation_Pokemon_LegTrace_H + +#include +#include +#include +#include +#include +#include +#include +#include "Pokemon_Grid.h" +#include "Pokemon_RouteLog.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Prefix tag of a leg record's log line. +inline constexpr const char* LEG_TRACE_TAG = "[Leg] "; + +// How a leg is planned to end. +enum class LegEndKind{ + OPEN, // timed or tapped into the open + WALL, // held until a wall stops it + TILE, // counted taps onto an exact tile +}; +// "open", "wall", "tile". +const char* leg_end_kind_name(LegEndKind kind); + +// How the end of a leg is known. +enum class LegEndKnown{ + WALL, // a wall stopped the walk + FADE, // a warp's fade or banner ended it + DIALOGUE, // a dialogue stopped it + COUNTED, // taps that moved, counted against the map + DEAD_RECKONED, // taken to have ended as planned + SEEN, // stopped short, where the walker found itself + UNKNOWN, // not known: the leg was cut off +}; +// "wall", "fade", "dialogue", "counted", "dead_reckoned", "seen", "unknown". +const char* leg_end_known_name(LegEndKnown known); + +// What stopped or delayed a leg on the way. +enum class LegInterrupt{ + WILD_BATTLE, + TRAINER, + SCENE, + DIALOGUE, +}; +// "wild_battle", "trainer", "scene", "dialogue". +const char* leg_interrupt_name(LegInterrupt interrupt); + +// What a leg is planned to do. +struct LegPlan{ + Direction direction = Direction::NORTH; + size_t tiles = 0; + LegEndKind end_kind = LegEndKind::OPEN; + // Every tile the leg may end on; empty where the plan does not say. + std::vector ends; +}; + +// One walked leg. +struct LegRecord{ + std::string checkpoint; + std::string event; + // 1-based, counted through the event, replans included. + size_t leg = 0; + LegPlan plan; + // The taps that moved, where the leg counts them. + std::optional moved; + // What the walks of the leg report: chunks of screen movement, and the + // time the direction was held. + size_t chunks = 0; + int64_t walked_ms = 0; + // The tiles the leg ended on, as the walker knows them. + std::vector end; + LegEndKnown known = LegEndKnown::UNKNOWN; + std::vector interrupts; + // Why the leg ended other than as planned ("replan", "warp"), or "". + std::string note; +}; + +// The record as one line of compact JSON, keys sorted. +std::string leg_trace_json(const LegRecord& record); +// LEG_TRACE_TAG and the record's JSON. +std::string leg_trace_line(const LegRecord& record); + + +// The route log's text read back: "Route 202 (23, 25), Route 202 (30, 26)". +// Nothing for text that is not a list of tiles. +std::vector parse_route_tiles(std::string_view text); +// A route_leg_line() read back: "Leg 1/2: east 15 (to wall) to ". +// A warp leg ends at its tiles, as a tile leg. +std::optional parse_route_leg_line(std::string_view text); + + +// What one walk of a leg reports. +struct LegWalk{ + // Chunks of screen movement, and the time the direction was held. + size_t chunks = 0; + int64_t walked_ms = 0; + size_t wild_battles = 0; + // The taps that moved, for a walk of taps. + std::optional tapped; +}; + +// Builds a walker's leg records from what it does, and hands each, as its +// log line, to `emit` once the leg ends. A leg still open when the next +// starts, or when its event ends, is emitted with its end unknown. +class LegTracer{ +public: + explicit LegTracer(std::function emit) + : m_emit(std::move(emit)) + {} + + // The legs from here on are `event`'s of `checkpoint`. + void begin_event(const std::string& checkpoint, const std::string& event); + // Emits the leg still open, if one is. + void end_event(); + + // A leg starts. + void begin_leg(LegPlan plan); + // The open leg's plan; null if no leg is open. + const LegPlan* open_leg() const{ + return m_leg ? &m_leg->plan : nullptr; + } + // A walk of the open leg ended. A leg can take several (a walk on to + // the wall after a battle); they add up. + void walked(const LegWalk& walk); + void interrupted(LegInterrupt interrupt); + // The open leg ended on `end`, known by `known`; emits it. + void end_leg(std::vector end, LegEndKnown known, std::string note = ""); + +private: + std::function m_emit; + std::string m_checkpoint; + std::string m_event; + size_t m_legs = 0; + std::optional m_leg; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace_Tests.cpp new file mode 100644 index 0000000000..f032c7e5ae --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace_Tests.cpp @@ -0,0 +1,167 @@ +/* Leg Trace Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The leg record's line word for word, the route log's leg lines read + * back, and the tracer's records for a leg that ends, one cut off by the + * next, and one with a wild battle on the way. + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_LegTrace.h" +#include "Pokemon_Navigation_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +struct LegTraceInput{ + std::string name; + std::function actual; +}; +struct LegTraceExpectation{ + std::string expected; +}; +struct LegTraceTestCase{ + LegTraceInput input; + LegTraceExpectation expectation; +}; + +class Test_LegTrace : public UnitTest{ +public: + explicit Test_LegTrace(LegTraceTestCase scenario) + : UnitTest("Pokemon::LegTrace - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string actual = m_scenario.input.actual(); + if (actual == m_scenario.expectation.expected){ + return true; + } + return "expected:\n" + m_scenario.expectation.expected + "\ngot:\n" + actual; + } + +private: + LegTraceTestCase m_scenario; +}; + +std::string tiles_text(const std::vector& tiles){ + return tiles.empty() ? "none" : describe(tiles); +} + +std::string plan_text(const std::optional& plan){ + if (!plan){ + return "none"; + } + return std::string(direction_name(plan->direction)) + " " + std::to_string(plan->tiles) + " " + + leg_end_kind_name(plan->end_kind) + " -> " + tiles_text(plan->ends); +} + +// The lines a tracer emits for `script`, one a line. +std::string traced(const std::function& script){ + std::string out; + LegTracer tracer([&](const std::string& line){ out += line + "\n"; }); + script(tracer); + return out; +} + +const LegTraceTestCase CASES[] = { + { + .input = {.name = "a tap leg's line", .actual = []{ + LegRecord record{ + .checkpoint = "00.04", .event = "to_the_signs_row", .leg = 1, + .plan = {.direction = Direction::NORTH, .tiles = 1, .end_kind = LegEndKind::TILE, + .ends = {{"Route 201", {57, 4}}}}, + .moved = 1, .chunks = 1, .walked_ms = 800, + .end = {{"Route 201", {57, 4}}}, .known = LegEndKnown::COUNTED, + }; + return leg_trace_line(record); + }}, + .expectation = {.expected = + "[Leg] {\"checkpoint\":\"00.04\",\"chunks\":1,\"dir\":\"north\",\"end\":[[\"Route 201\",57,4]]," + "\"end_kind\":\"tile\",\"event\":\"to_the_signs_row\",\"interrupts\":[],\"known\":\"counted\"," + "\"leg\":1,\"moved\":1,\"ms\":800,\"planned_end\":[[\"Route 201\",57,4]],\"tiles\":1}"}, + }, + { + .input = {.name = "tiles read back", .actual = []{ + return tiles_text(parse_route_tiles("Route 202 (23, 25), Mom's House (30, -1)")); + }}, + .expectation = {.expected = "Route 202 (23, 25), Mom's House (30, -1)"}, + }, + { + .input = {.name = "no tiles in other text", .actual = []{ + return tiles_text(parse_route_tiles("an unknown tile")); + }}, + .expectation = {.expected = "none"}, + }, + { + .input = {.name = "a wall leg line read back", .actual = []{ + return plan_text(parse_route_leg_line("Leg 1/2: east 15 (to wall) to Route 202 (23, 25), Route 202 (30, 26)")); + }}, + .expectation = {.expected = "east 15 wall -> Route 202 (23, 25), Route 202 (30, 26)"}, + }, + { + .input = {.name = "an open leg line read back", .actual = []{ + return plan_text(parse_route_leg_line("Leg 3/3: west 1 (open) to Twinleaf Town (7, 9)")); + }}, + .expectation = {.expected = "west 1 open -> Twinleaf Town (7, 9)"}, + }, + { + .input = {.name = "not a leg line", .actual = []{ + return plan_text(parse_route_leg_line("[Route] Turning west.")); + }}, + .expectation = {.expected = "none"}, + }, + { + .input = {.name = "a leg cut off by the next, and by its event's end", .actual = []{ + return traced([](LegTracer& tracer){ + tracer.begin_event("00.04", "beside_mom"); + tracer.begin_leg({.direction = Direction::WEST, .tiles = 2, .end_kind = LegEndKind::OPEN}); + tracer.begin_leg({.direction = Direction::NORTH, .tiles = 1, .end_kind = LegEndKind::WALL}); + tracer.walked({.chunks = 3, .walked_ms = 640}); + tracer.begin_event("00.04", "mom"); + }); + }}, + .expectation = {.expected = + "[Leg] {\"checkpoint\":\"00.04\",\"chunks\":0,\"dir\":\"west\",\"end\":[],\"end_kind\":\"open\"," + "\"event\":\"beside_mom\",\"interrupts\":[],\"known\":\"unknown\",\"leg\":1,\"ms\":0,\"planned_end\":[],\"tiles\":2}\n" + "[Leg] {\"checkpoint\":\"00.04\",\"chunks\":3,\"dir\":\"north\",\"end\":[],\"end_kind\":\"wall\"," + "\"event\":\"beside_mom\",\"interrupts\":[],\"known\":\"unknown\",\"leg\":2,\"ms\":640,\"planned_end\":[],\"tiles\":1}\n"}, + }, + { + .input = {.name = "a wild battle on the way, two walks to the wall", .actual = []{ + return traced([](LegTracer& tracer){ + tracer.begin_event("00.04b", "to_catch_grass"); + tracer.begin_leg({.direction = Direction::SOUTH, .tiles = 4, .end_kind = LegEndKind::WALL}); + tracer.walked({.chunks = 2, .walked_ms = 500, .wild_battles = 1}); + tracer.walked({.chunks = 2, .walked_ms = 400}); + tracer.end_leg({{"Route 202", {20, 27}}}, LegEndKnown::WALL); + tracer.end_event(); + }); + }}, + .expectation = {.expected = + "[Leg] {\"checkpoint\":\"00.04b\",\"chunks\":4,\"dir\":\"south\",\"end\":[[\"Route 202\",20,27]],\"end_kind\":\"wall\"," + "\"event\":\"to_catch_grass\",\"interrupts\":[\"wild_battle\"],\"known\":\"wall\",\"leg\":1,\"ms\":900,\"planned_end\":[],\"tiles\":4}\n"}, + }, +}; + +} // namespace + + +void add_tests_LegTrace(UnitTestDatabase& database){ + for (const auto& scenario : CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h index 0bb989df00..2492f761c2 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Navigation_Tests.h @@ -26,6 +26,8 @@ void add_tests_WallRecovery(UnitTestDatabase& database); void add_tests_MapData(UnitTestDatabase& database); // Registers route logging formatting unit tests. void add_tests_RouteLog(UnitTestDatabase& database); +// Registers leg trace record and tracer unit tests. +void add_tests_LegTrace(UnitTestDatabase& database); // (name, JSON text) of each map in Pokemon/Navigation/TestMaps/, built into // the program by pa_embed_text_files() (cmake/EmbedTextFiles.cmake). diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp index cc849dd187..54296f1ed7 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp @@ -195,6 +195,8 @@ void add_tests_RouteLog(UnitTestDatabase& database){ for (const auto& scenario : CASES){ database.add(scenario); } + // The leg records read the route lines back. + add_tests_LegTrace(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index 8bca01481a..6e89134b69 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -11,6 +11,7 @@ #include "Common/Cpp/Color.h" #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Pokemon/Navigation/Pokemon_LegTrace.h" #include "Pokemon/Navigation/Pokemon_MapData.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" @@ -35,6 +36,44 @@ using Pokemon::StoryStep; using Pokemon::TilePos; +namespace{ + +// The leg records of a step: its legs are this event's, and one still +// open when the step ends is written with its end unknown. +class EventTrace{ +public: + EventTrace(Pokemon::LegTracer& legs, const std::string& row, const std::string& step) + : m_legs(legs) + { + m_legs.begin_event(row, step); + } + ~EventTrace(){ + try{ + m_legs.end_event(); + }catch (...){} + } + EventTrace(const EventTrace&) = delete; + EventTrace& operator=(const EventTrace&) = delete; + +private: + Pokemon::LegTracer& m_legs; +}; + +// `tiles` of `map` as the route lines name them: by the story world's +// map names, where the map has a world. +std::vector traced_tiles(const std::string& map, const std::vector& tiles){ + const StoryWorld* world = story_plan_world(map, map); + std::vector out; + for (const TilePos& pos : tiles){ + const std::optional local = world == nullptr ? std::nullopt : world->to_local(story_to_world(*world, map, pos)); + out.push_back(local ? Pokemon::RouteTile{local->map, local->pos} : Pokemon::RouteTile{map, pos}); + } + return out; +} + +} // namespace + + namespace{ // "to_catch_grass" as "to catch grass", for the logs. @@ -143,18 +182,18 @@ void StoryWalkSteps::begin_attempt(const std::string& row, const std::vector costs = story_route_costs(step.variant); if (!costs){ @@ -178,7 +217,7 @@ Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }, label_of(step), {}, *costs, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK, m_scene_next.contains(step.name) }; - RouteEnd end = walk_route_to_warp(m_io.route(), *maps, start, trainers, plan); + RouteEnd end = walk_route_to_warp(m_route, *maps, start, trainers, plan); sights = std::move(trainers.sights); m_warp = std::move(end.warp); m_scene_open = end.scene; @@ -186,7 +225,7 @@ Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep for (const TilePos& pos : end.tiles){ const std::optional tile = story_to_local(*maps, goal.map, pos); if (!tile){ - fail(m_io.route(), std::format("{}: the walk ended off {}.", step.name, goal.map)); + fail(m_route, std::format("{}: the walk ended off {}.", step.name, goal.map)); } local.push_back(*tile); } @@ -194,6 +233,7 @@ Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep } Outcome StoryWalkSteps::route(RunState& state, const StoryStep& step){ + const EventTrace trace(m_legs, m_row, step.name); m_warp = {}; if (Pokemon::tiles_of(state.pose).empty()){ return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); @@ -217,7 +257,8 @@ Outcome StoryWalkSteps::route(RunState& state, const StoryStep& step){ Outcome StoryWalkSteps::run_to_dialogue(const StoryStep& step){ const Pokemon::StoryLeg& leg = step.legs.front(); const MoveSpeed speed = m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK; - const WalkResult walk = m_io.route().walk_to_wall({ + m_legs.begin_leg({.direction = leg.direction, .tiles = (size_t)leg.tiles, .end_kind = Pokemon::LegEndKind::OPEN}); + const WalkResult walk = m_route.walk_to_wall({ .direction = leg.direction, .limit = route_limit_for_tiles(speed, leg.tiles), .label = label_of(step), @@ -225,11 +266,12 @@ Outcome StoryWalkSteps::run_to_dialogue(const StoryStep& step){ }); log(std::format("[{}] {}: ran {} to a dialogue: {} moved chunks, {} tiles at most, {}, {} wild battle(s).", m_row, step.name, direction_name(leg.direction), walk.moved_chunks, leg.tiles, walk_stop_name(walk.stop), walk.wild_battles)); + m_legs.end_leg({}, walk.stop == WalkStop::DIALOG ? Pokemon::LegEndKnown::DIALOGUE : Pokemon::LegEndKnown::UNKNOWN); if (walk.stop == WalkStop::DIALOG){ return Pokemon::outcome_ok(); } // A scene can lock us before its first line: Dawn walks over first (r37). - if (m_io.route().dialog_within(10000ms, COLOR_CYAN)){ + if (m_route.dialog_within(10000ms, COLOR_CYAN)){ return Pokemon::outcome_ok(); } return Pokemon::outcome_failed("no_dialogue", std::format("{}: no dialogue in {} tiles {}", step.name, leg.tiles, direction_name(leg.direction))); @@ -310,7 +352,7 @@ WarpSeen StoryWalkSteps::door_from_beside(const StoryStep& step, const WarpSeen& } for (const Pokemon::StoryLeg& leg : step.legs){ turn(leg.direction); - const WalkResult walk = m_io.route().walk_taps(leg.direction, (size_t)leg.tiles, step.name); + const WalkResult walk = m_route.walk_taps(leg.direction, (size_t)leg.tiles, step.name); log(std::format("[{}] {}: no fade; {} {} taps {}, {}.", m_row, step.name, leg.tiles, direction_name(leg.direction), walk.moved_chunks, walk_stop_name(walk.stop))); if (walk.warp.any()){ @@ -332,7 +374,7 @@ bool StoryWalkSteps::through_already(const StoryStep& step){ } const std::string map = step.pose_after ? step.pose_after->map : ""; if (!through.banner.empty() && !location_banner_matches(through.banner, story_banner_name(map))){ - fail(m_io.route(), std::format("{}: the walk before went through a warp to \"{}\", not {}.", step.name, through.banner, map)); + fail(m_route, std::format("{}: the walk before went through a warp to \"{}\", not {}.", step.name, through.banner, map)); } log(std::format("[{}] {}: through already; the walk before saw {}.", m_row, step.name, describe(through))); return true; @@ -394,7 +436,7 @@ Pose StoryWalkSteps::recover_tapped_leg(const Pose& from, const std::vector& moved){ const StoryWorld* world = story_plan_world(from.map, from.map); if (world == nullptr){ - fail(m_io.route(), "interrupted leg has no recovery world: " + from.map); + fail(m_route, "interrupted leg has no recovery world: " + from.map); } std::vector global; for (const TilePos& at : starts){ @@ -409,7 +451,7 @@ Pose StoryWalkSteps::recover_tapped_leg(const Pose& from, const std::vectordirection); const size_t tiles = (size_t)leg->tiles; - const WalkResult walk = m_io.route().walk_taps(leg->direction, tiles, step.name); - log(std::format("[{}] {}: taps {} moved {} of {} tiles.", m_row, step.name, direction_name(leg->direction), walk.moved_chunks, tiles)); const auto next = counted_ends(at, *leg, policy); + m_legs.begin_leg({.direction = leg->direction, .tiles = tiles, .end_kind = Pokemon::LegEndKind::TILE, + .ends = traced_tiles(from.map, next)}); + const WalkResult walk = m_route.walk_taps(leg->direction, tiles, step.name); + log(std::format("[{}] {}: taps {} moved {} of {} tiles.", m_row, step.name, direction_name(leg->direction), walk.moved_chunks, tiles)); if (walk.wild_battles > 0){ if (walk.stop != WalkStop::LIMIT && walk.stop != WalkStop::BLOCKED){ return Pokemon::outcome_failed("interrupted_leg_unconfirmed", step.name); } const LegBattlePlace place = place_leg_battle(walk, tiles); - m_io.route().note(std::format("[{}] {}", m_row, leg_battle_line(step.name, walk, place)), RouteNote::LOG); + m_legs.end_leg({}, Pokemon::LegEndKnown::UNKNOWN, "recovery"); + m_route.note(std::format("[{}] {}", m_row, leg_battle_line(step.name, walk, place)), RouteNote::LOG); std::vector ends = next; for (auto rest = std::next(leg); rest != step.legs.end(); ++rest){ ends = counted_ends(ends, *rest, policy); @@ -458,6 +503,7 @@ Outcome StoryWalkSteps::tap_legs(const Pose& from, const StoryStep& step){ return Pokemon::outcome_failed("short_leg", std::format("{} {} moved {}", direction_name(leg->direction), tiles, walk.moved_chunks)); } at = next; + m_legs.end_leg(traced_tiles(from.map, at), Pokemon::LegEndKnown::COUNTED); } return Pokemon::outcome_ok(Pokemon::tile_pose(from.map, at, step.legs.back().direction)); } @@ -476,7 +522,8 @@ Outcome StoryWalkSteps::measured_legs(const Pose& from, const StoryStep& step){ for (const Pokemon::StoryLeg& leg : step.legs){ turn(leg.direction); const size_t tiles = (size_t)leg.tiles; - const WalkResult walk = m_io.route().walk_taps(leg.direction, tiles, step.name); + m_legs.begin_leg({.direction = leg.direction, .tiles = tiles, .end_kind = Pokemon::LegEndKind::TILE}); + const WalkResult walk = m_route.walk_taps(leg.direction, tiles, step.name); if (walk.wild_battles > 0){ return Pokemon::outcome_failed("interrupted_leg_unconfirmed", step.name); } @@ -494,6 +541,7 @@ Outcome StoryWalkSteps::measured_legs(const Pose& from, const StoryStep& step){ direction_name(leg.direction), walk.moved_chunks, Pokemon::to_string(from))); } at = std::move(next); + m_legs.end_leg(traced_tiles(from.map, at), Pokemon::LegEndKnown::COUNTED); } return Pokemon::outcome_ok(Pokemon::tile_pose(from.map, at, step.legs.back().direction)); } @@ -521,12 +569,15 @@ Outcome StoryWalkSteps::counted_wall(const Pose& from, const StoryStep& step){ std::format("{} {} where the map has {} to {}", direction_name(leg.direction), leg.tiles, fewest, most)); } turn(leg.direction); - walk_counted_wall_leg(m_io.route(), {.direction = leg.direction, .fewest = fewest, .most = most, + m_legs.begin_leg({.direction = leg.direction, .tiles = (size_t)leg.tiles, .end_kind = Pokemon::LegEndKind::WALL}); + walk_counted_wall_leg(m_route, {.direction = leg.direction, .fewest = fewest, .most = most, .speed = m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK, .label = label_of(step)}); + m_legs.end_leg({}, Pokemon::LegEndKnown::WALL); return Pokemon::outcome_ok(); } Outcome StoryWalkSteps::legs(RunState& state, const StoryStep& step){ + const EventTrace trace(m_legs, m_row, step.name); m_warp = {}; m_scene_open = false; if (step.variant == "counted_wall"){ @@ -536,8 +587,11 @@ Outcome StoryWalkSteps::legs(RunState& state, const StoryStep& step){ return measured_legs(state.pose, step); } if (step.variant == "to_wall"){ + // The walls end these legs; the step's pose_after says where. for (const Pokemon::StoryLeg& leg : step.legs){ + m_legs.begin_leg({.direction = leg.direction, .tiles = (size_t)leg.tiles, .end_kind = Pokemon::LegEndKind::WALL}); m_io.walk_until_stopped(leg.direction, (size_t)leg.tiles, label_of(step)); + m_legs.end_leg({}, Pokemon::LegEndKnown::WALL); } return Pokemon::outcome_ok(); } @@ -551,6 +605,7 @@ Outcome StoryWalkSteps::legs(RunState& state, const StoryStep& step){ } Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ + const EventTrace trace(m_legs, m_row, step.name); if (step.variant == "to_banner"){ turn(step.direction); return tap_to_banner(state.pose, step); @@ -558,7 +613,7 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ if (step.variant == "tap"){ // No separate turn tap first: at 1 tile from the door, a turn tap // steps onto the warp, causing walk_taps to take an extra step on the far map. - const WalkResult walk = m_io.route().walk_taps(step.direction, 1, step.name); + const WalkResult walk = m_route.walk_taps(step.direction, 1, step.name); if (walk.wild_battles > 0){ return Pokemon::outcome_failed("interrupted_step", step.name); } @@ -599,7 +654,7 @@ Outcome StoryWalkSteps::one_step(const RunState& state, const StoryStep& step){ return Pokemon::outcome_ok(state.pose); } turn(step.direction); - const WalkResult walk = m_io.route().walk_taps(step.direction, 1, step.name); + const WalkResult walk = m_route.walk_taps(step.direction, 1, step.name); if (walk.wild_battles > 0){ return Pokemon::outcome_failed("interrupted_step", step.name); } @@ -619,12 +674,12 @@ Outcome StoryWalkSteps::talk(RunState& state, const StoryStep& step){ if (const std::optional facing = Pokemon::facing_of(state.pose)){ turn(*facing); } - m_io.route().press({.kind = RouteInputKind::BUTTON_A, .direction = Direction::NORTH, .hold = 80ms, .release = 200ms, + m_route.press({.kind = RouteInputKind::BUTTON_A, .direction = Direction::NORTH, .hold = 80ms, .release = 200ms, .count = 1, .end = RouteInputEnd::DONE}); // Roark's first line in the mine comes after the camera zooms in on // us, which can take some seconds (r98; the old event waited 8 s). - if (!m_io.route().dialog_within(8000ms, COLOR_YELLOW)){ - fail(m_io.route(), label_of(step) + ": nobody answered."); + if (!m_route.dialog_within(8000ms, COLOR_YELLOW)){ + fail(m_route, label_of(step) + ": nobody answered."); } return Pokemon::outcome_ok(); } @@ -634,8 +689,8 @@ Outcome StoryWalkSteps::mash(RunState& state, const StoryStep& step){ m_scene_open = false; // The step before may have played the scene already (a door step settles // its arrival scene), so its first line is not required. - if (!m_io.route().dialog_within(15000ms, COLOR_CYAN)){ - m_io.route().note(label_of(step) + ": no line within 15 s; the step before played it.", RouteNote::WARNING); + if (!m_route.dialog_within(15000ms, COLOR_CYAN)){ + m_route.note(label_of(step) + ": no line within 15 s; the step before played it.", RouteNote::WARNING); } m_io.settle(step.variant == "a" ? BUTTON_A : BUTTON_B, label_of(step), step.pose_after && step.pose_after->map != state.pose.map && diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index 0e64151fb7..d8336b76b6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -20,6 +20,7 @@ #include "Pokemon/AutoStory/Pokemon_StorySteps.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegBattle.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegTraceIO.h" #include "PokemonBDSP_AutoStory_StoryStepIO.h" namespace PokemonAutomation{ @@ -62,6 +63,8 @@ class StoryWalkSteps{ public: explicit StoryWalkSteps(StoryStepIO& io) : m_io(io) + , m_legs(legs_to_log(io.route())) + , m_route(io.route(), m_legs) {} // A new attempt of the row `row`: every trainer can see us again, and @@ -109,6 +112,10 @@ class StoryWalkSteps{ void log(const std::string& text); StoryStepIO& m_io; + // The leg records of the walks, written to m_io's route log. + Pokemon::LegTracer m_legs; + // m_io's route walker console, telling m_legs of each leg walked. + LegTraceRouteIO m_route; std::string m_row; bool m_can_run = false; // The trainers who can still see us on each story_plan_world() world, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.cpp new file mode 100644 index 0000000000..926f060437 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.cpp @@ -0,0 +1,190 @@ +/* BDSP AutoStory Leg Trace Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The leg records (Pokemon_LegTrace.h) the story's walks write when a row + * runs on the simulation are the route the console should walk too: + * devtools/maps/leg_trace.py compares a console log's records with them. + * The golden copy is checked in beside this file, so a change to the + * route shows as its diff in review. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Filesystem/FileIO.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/Navigation/Pokemon_LegTrace.h" +#include "PokemonBDSP_AutoStory_LegTrace_Tests.h" +#include "PokemonBDSP_AutoStory_StorySim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +namespace{ + +// The rows with a golden trace. +constexpr const char* TRACED_ROW = "00.04"; + +// The leg records' JSON of row `row` run alone on the simulation, or the +// run's failure. +struct SimTrace{ + std::vector legs; + std::string error; +}; +SimTrace sim_leg_trace(Logger& logger, const std::string& row){ + SimExecutor executor(logger); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = row, .to = row}); + SimTrace out; + if (!report.completed){ + out.error = "the row failed on the simulation: " + executor.result().error; + } + const std::string tag = Pokemon::LEG_TRACE_TAG; + for (const std::string& note : executor.notes()){ + if (note.starts_with(tag)){ + out.legs.push_back(note.substr(tag.size())); + } + } + return out; +} + +// The trace file's text, a leg a line, as devtools/maps/leg_trace.py reads +// it ({"about", "legs"}). +std::string trace_text(const std::string& row, const std::vector& legs){ + std::string out = "{\n"; + out += std::format(" \"about\": \"Leg records of BDSP AutoStory row {} run on the grid simulation " + "(Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.cpp). Rewrite with PA_UPDATE_LEG_TRACE=1.\",\n", row); + out += " \"legs\": [\n"; + for (size_t i = 0; i < legs.size(); i++){ + out += " " + legs[i] + (i + 1 < legs.size() ? ",\n" : "\n"); + } + return out + " ]\n}\n"; +} + +// The golden file, beside this file. +std::string golden_path(const std::string& row){ + const std::string self = __FILE__; + const size_t slash = self.find_last_of("/\\"); + return (slash == std::string::npos ? std::string() : self.substr(0, slash + 1)) + "leg_trace_" + row + ".golden.json"; +} + +// The first line where `a` and `b` differ, both without carriage returns. +std::string first_difference(const std::string& golden, const std::string& traced){ + size_t line = 1; + size_t begin = 0; + while (begin < golden.size() || begin < traced.size()){ + const size_t end_a = std::min(golden.find('\n', begin), golden.size()); + const size_t end_b = std::min(traced.find('\n', begin), traced.size()); + const std::string a = begin < golden.size() ? golden.substr(begin, end_a - begin) : ""; + const std::string b = begin < traced.size() ? traced.substr(begin, end_b - begin) : ""; + if (a != b){ + return std::format("line {}:\n--- golden: {}\n+++ traced: {}", line, a, b); + } + begin = end_a + 1; + line++; + } + return ""; +} + +UnitTestResult test_golden_trace(Logger& logger){ + const SimTrace trace = sim_leg_trace(logger, TRACED_ROW); + if (!trace.error.empty()){ + return trace.error; + } + if (trace.legs.empty()){ + return std::format("row {} wrote no leg records.", TRACED_ROW); + } + const std::string text = trace_text(TRACED_ROW, trace.legs); + const std::string path = golden_path(TRACED_ROW); + const char* update = std::getenv("PA_UPDATE_LEG_TRACE"); + if (update != nullptr && update[0] != '\0' && update[0] != '0'){ + std::string crlf; + for (char ch : text){ + crlf += ch == '\n' ? std::string("\r\n") : std::string(1, ch); + } + FileIO file; + if (!file.open(path, FileMode::WRITE | FileMode::BINARY) || file.write(crlf) != crlf.size()){ + return "Could not write " + path + "."; + } + logger.log("Wrote " + path + "."); + return true; + } + std::string golden; + if (!file_to_string(path, golden)){ + return "Could not read " + path + "."; + } + std::erase(golden, '\r'); + const std::string difference = first_difference(golden, text); + if (difference.empty()){ + return true; + } + return "The simulation's leg records differ from " + path + ". If the route change is meant, rerun with " + "PA_UPDATE_LEG_TRACE=1 and review the file's diff. First difference at " + difference; +} + +UnitTestResult test_stable_trace(Logger& logger){ + const SimTrace first = sim_leg_trace(logger, TRACED_ROW); + const SimTrace second = sim_leg_trace(logger, TRACED_ROW); + if (first.legs == second.legs){ + return true; + } + return "Two runs of the same row wrote different leg records: " + first_difference( + trace_text(TRACED_ROW, first.legs), trace_text(TRACED_ROW, second.legs)); +} + + +struct LegTraceInput{ + std::string name; + std::function body; +}; +struct LegTraceExpectation{ +}; +struct LegTraceCase{ + LegTraceInput input; + LegTraceExpectation expectation; +}; + +class Test_AutoStoryLegTrace : public UnitTest{ +public: + explicit Test_AutoStoryLegTrace(LegTraceCase test_case) + : UnitTest("PokemonBDSP::AutoStory - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + LegTraceCase m_case; +}; + +const LegTraceCase LEG_TRACE_CASES[] = { + {.input = {"Leg trace: 00.04 on the simulation writes leg_trace_00.04.golden.json", test_golden_trace}, .expectation = {}}, + {.input = {"Leg trace: 00.04 on the simulation writes the same records every run", test_stable_trace}, .expectation = {}}, +}; + +} // namespace + + +void add_tests_AutoStory_LegTrace(UnitTestDatabase& database){ + for (const auto& item : LEG_TRACE_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.h new file mode 100644 index 0000000000..3d457733a8 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.h @@ -0,0 +1,25 @@ +/* BDSP AutoStory Leg Trace Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_LegTrace_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_LegTrace_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// The simulation's leg records of a row, against a golden copy beside this +// file, and the same on every run. +void add_tests_AutoStory_LegTrace(UnitTestDatabase& database); + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h index 01a959cacd..0fb7bcb5e6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -406,6 +406,11 @@ class SimExecutor : public Pokemon::TableExecutor{ const SimRun& result() const{ return m_result; } + // Every line the walks wrote, the route walker's and the leg records + // ("[Leg] ...") among them. + const std::vector& notes() const{ + return m_notes; + } // The story's actions as the simulation binds them. const Pokemon::StoryActionTable& actions() const{ return m_table; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp index 00c31523ee..c05d56e6f3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -41,6 +41,7 @@ #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_LegTrace_Tests.h" #include "PokemonBDSP_AutoStory_OldStorySteps.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" @@ -376,6 +377,7 @@ void add_tests_AutoStory_StorySim(UnitTestDatabase& database){ database.add(item); } add_tests_AutoStoryResources(database); + add_tests_AutoStory_LegTrace(database); } } // namespace PokemonBDSP diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/leg_trace_00.04.golden.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/leg_trace_00.04.golden.json new file mode 100644 index 0000000000..6a175f3fdf --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/leg_trace_00.04.golden.json @@ -0,0 +1,39 @@ +{ + "about": "Leg records of BDSP AutoStory row 00.04 run on the grid simulation (Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.cpp). Rewrite with PA_UPDATE_LEG_TRACE=1.", + "legs": [ + {"checkpoint":"00.04","chunks":3,"dir":"east","end":[["Sandgem Town",29,11],["Sandgem Town",29,12]],"end_kind":"wall","event":"onto_the_path","interrupts":[],"known":"wall","leg":1,"ms":1350,"planned_end":[["Sandgem Town",29,11],["Sandgem Town",29,12]],"tiles":3}, + {"checkpoint":"00.04","chunks":0,"dir":"north","end":[["Sandgem Town",29,11]],"end_kind":"wall","event":"onto_the_path","interrupts":[],"known":"wall","leg":2,"ms":1050,"planned_end":[["Sandgem Town",29,11]],"tiles":1}, + {"checkpoint":"00.04","chunks":1,"dir":"south","end":[["Sandgem Town",29,12]],"end_kind":"open","event":"onto_the_path","interrupts":[],"known":"dead_reckoned","leg":3,"moved":1,"ms":800,"planned_end":[["Sandgem Town",29,12]],"tiles":1}, + {"checkpoint":"00.04","chunks":1,"dir":"north","end":[["Route 201",57,4],["Route 201",58,4],["Route 201",59,4],["Route 201",60,4],["Route 201",61,4],["Route 201",62,4],["Route 201",63,4]],"end_kind":"tile","event":"to_the_signs_row","interrupts":[],"known":"counted","leg":1,"moved":1,"ms":800,"planned_end":[["Route 201",57,4],["Route 201",58,4],["Route 201",59,4],["Route 201",60,4],["Route 201",61,4],["Route 201",62,4],["Route 201",63,4]],"tiles":1}, + {"checkpoint":"00.04","chunks":4,"dir":"west","end":[["Route 201",56,4]],"end_kind":"wall","event":"to_ledge_column","interrupts":[],"known":"wall","leg":1,"ms":1450,"planned_end":[["Route 201",56,4]],"tiles":7}, + {"checkpoint":"00.04","chunks":1,"dir":"south","end":[["Route 201",56,5]],"end_kind":"open","event":"to_ledge_column","interrupts":[],"known":"dead_reckoned","leg":2,"moved":1,"ms":800,"planned_end":[["Route 201",56,5]],"tiles":1}, + {"checkpoint":"00.04","chunks":1,"dir":"west","end":[["Route 201",55,5]],"end_kind":"open","event":"to_ledge_column","interrupts":[],"known":"dead_reckoned","leg":3,"moved":1,"ms":800,"planned_end":[["Route 201",55,5]],"tiles":1}, + {"checkpoint":"00.04","chunks":8,"dir":"south","end":[["Route 201",55,13]],"end_kind":"tile","event":"over_the_ledge","interrupts":[],"known":"counted","leg":1,"moved":8,"ms":6400,"planned_end":[["Route 201",55,13]],"tiles":8}, + {"checkpoint":"00.04","chunks":16,"dir":"west","end":[["Route 201",39,14]],"end_kind":"open","event":"along_route_201_road","interrupts":[],"known":"dead_reckoned","leg":1,"moved":16,"ms":12800,"planned_end":[["Route 201",39,14]],"tiles":16}, + {"checkpoint":"00.04","chunks":3,"dir":"north","end":[["Route 201",39,11]],"end_kind":"open","event":"along_route_201_road","interrupts":[],"known":"dead_reckoned","leg":2,"moved":3,"ms":2400,"planned_end":[["Route 201",39,11]],"tiles":3}, + {"checkpoint":"00.04","chunks":24,"dir":"west","end":[["Route 201",15,11]],"end_kind":"open","event":"along_route_201_road","interrupts":[],"known":"dead_reckoned","leg":3,"moved":24,"ms":19200,"planned_end":[["Route 201",15,11]],"tiles":24}, + {"checkpoint":"00.04","chunks":2,"dir":"south","end":[["Route 201",15,14]],"end_kind":"open","event":"along_route_201_road","interrupts":[],"known":"dead_reckoned","leg":4,"moved":2,"ms":1600,"planned_end":[["Route 201",15,14]],"tiles":2}, + {"checkpoint":"00.04","chunks":33,"dir":"south","end":[["Twinleaf Town",15,22]],"end_kind":"open","event":"into_twinleaf","interrupts":[],"known":"dead_reckoned","leg":1,"moved":33,"ms":26400,"planned_end":[["Twinleaf Town",15,22]],"tiles":33}, + {"checkpoint":"00.04","chunks":5,"dir":"east","end":[["Twinleaf Town",20,22]],"end_kind":"open","event":"to_moms_doorstep","interrupts":[],"known":"dead_reckoned","leg":1,"moved":5,"ms":4000,"planned_end":[["Twinleaf Town",20,22]],"tiles":5}, + {"checkpoint":"00.04","chunks":1,"dir":"north","end":[["PlayerHouse1F",6,8]],"end_kind":"open","event":"beside_mom","interrupts":[],"known":"dead_reckoned","leg":1,"moved":1,"ms":800,"planned_end":[["PlayerHouse1F",6,8]],"tiles":1}, + {"checkpoint":"00.04","chunks":0,"dir":"north","end":[],"end_kind":"wall","event":"into_the_east_corner","interrupts":[],"known":"wall","leg":1,"ms":0,"planned_end":[],"tiles":4}, + {"checkpoint":"00.04","chunks":0,"dir":"east","end":[],"end_kind":"wall","event":"into_the_east_corner","interrupts":[],"known":"wall","leg":2,"ms":0,"planned_end":[],"tiles":6}, + {"checkpoint":"00.04","chunks":0,"dir":"south","end":[],"end_kind":"wall","event":"into_the_east_corner","interrupts":[],"known":"wall","leg":3,"ms":0,"planned_end":[],"tiles":4}, + {"checkpoint":"00.04","chunks":1,"dir":"west","end":[["PlayerHouse1F",10,8]],"end_kind":"open","event":"into_moms_call","interrupts":[],"known":"dead_reckoned","leg":1,"moved":1,"ms":800,"planned_end":[["PlayerHouse1F",10,8]],"tiles":1}, + {"checkpoint":"00.04","chunks":1,"dir":"south","end":[["PlayerHouse1F",10,9]],"end_kind":"open","event":"into_moms_call","interrupts":[],"known":"dead_reckoned","leg":2,"moved":1,"ms":800,"planned_end":[["PlayerHouse1F",10,9]],"tiles":1}, + {"checkpoint":"00.04","chunks":3,"dir":"west","end":[["PlayerHouse1F",7,9]],"end_kind":"open","event":"into_moms_call","interrupts":[],"known":"dead_reckoned","leg":3,"moved":3,"ms":2400,"planned_end":[["PlayerHouse1F",7,9]],"tiles":3}, + {"checkpoint":"00.04","chunks":1,"dir":"west","end":[],"end_kind":"open","event":"into_moms_call","interrupts":[],"known":"dialogue","leg":4,"ms":350,"planned_end":[],"tiles":1}, + {"checkpoint":"00.04","chunks":0,"dir":"west","end":[],"end_kind":"wall","event":"to_twinleafs_west_wall","interrupts":[],"known":"wall","leg":1,"ms":0,"planned_end":[],"tiles":16}, + {"checkpoint":"00.04","chunks":18,"dir":"north","end":[["Twinleaf Town",6,4]],"end_kind":"wall","event":"short_of_the_catch_tutorial","interrupts":[],"known":"wall","leg":1,"ms":3750,"planned_end":[["Twinleaf Town",6,4]],"tiles":19}, + {"checkpoint":"00.04","chunks":8,"dir":"east","end":[["Twinleaf Town",14,4]],"end_kind":"open","event":"short_of_the_catch_tutorial","interrupts":[],"known":"dead_reckoned","leg":2,"moved":8,"ms":6400,"planned_end":[["Twinleaf Town",14,4]],"tiles":8}, + {"checkpoint":"00.04","chunks":16,"dir":"north","end":[["Route 201",14,13]],"end_kind":"wall","event":"short_of_the_catch_tutorial","interrupts":[],"known":"wall","leg":3,"ms":3450,"planned_end":[["Route 201",14,13]],"tiles":16}, + {"checkpoint":"00.04","chunks":43,"dir":"east","end":[["Route 201",57,13]],"end_kind":"wall","event":"short_of_the_catch_tutorial","interrupts":[],"known":"wall","leg":4,"ms":5350,"planned_end":[["Route 201",57,13]],"tiles":43}, + {"checkpoint":"00.04","chunks":7,"dir":"west","end":[["Route 201",50,13]],"end_kind":"open","event":"short_of_the_catch_tutorial","interrupts":[],"known":"dead_reckoned","leg":5,"moved":7,"ms":5600,"planned_end":[["Route 201",50,13]],"tiles":7}, + {"checkpoint":"00.04","chunks":7,"dir":"north","end":[["Route 201",50,6]],"end_kind":"open","event":"short_of_the_catch_tutorial","interrupts":[],"known":"dead_reckoned","leg":6,"moved":7,"ms":5600,"planned_end":[["Route 201",50,6]],"tiles":7}, + {"checkpoint":"00.04","chunks":43,"dir":"east","end":[["Sandgem Town",29,13]],"end_kind":"wall","event":"short_of_the_catch_tutorial","interrupts":[],"known":"wall","leg":7,"ms":5350,"planned_end":[["Sandgem Town",29,13]],"tiles":43}, + {"checkpoint":"00.04","chunks":5,"dir":"west","end":[["Sandgem Town",24,13]],"end_kind":"open","event":"short_of_the_catch_tutorial","interrupts":[],"known":"dead_reckoned","leg":8,"moved":5,"ms":4000,"planned_end":[["Sandgem Town",24,13]],"tiles":5}, + {"checkpoint":"00.04","chunks":21,"dir":"north","end":[["Route 202",25,24]],"end_kind":"wall","event":"short_of_the_catch_tutorial","interrupts":[],"known":"wall","leg":9,"ms":4200,"planned_end":[["Route 202",25,24]],"tiles":21}, + {"checkpoint":"00.04","chunks":3,"dir":"west","end":[["Route 202",22,24]],"end_kind":"wall","event":"short_of_the_catch_tutorial","interrupts":[],"known":"wall","leg":10,"ms":1350,"planned_end":[["Route 202",22,24]],"tiles":3}, + {"checkpoint":"00.04","chunks":3,"dir":"south","end":[["Route 202",22,27]],"end_kind":"open","event":"short_of_the_catch_tutorial","interrupts":[],"known":"dead_reckoned","leg":11,"moved":3,"ms":2400,"planned_end":[["Route 202",22,27]],"tiles":3} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegTraceIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegTraceIO.cpp new file mode 100644 index 0000000000..6fc1b5ebec --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegTraceIO.cpp @@ -0,0 +1,118 @@ +/* BDSP AutoStory - Leg Trace IO + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "PokemonBDSP_AutoStory_LegTraceIO.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::LegEndKind; +using Pokemon::LegEndKnown; +using Pokemon::LegInterrupt; + + +Pokemon::LegTracer legs_to_log(RouteIO& io){ + return Pokemon::LegTracer([&io](const std::string& line){ io.note(line, RouteNote::LOG); }); +} + +void LegTraceRouteIO::walked(const WalkResult& result){ + m_tracer.walked({.chunks = result.moved_chunks, .walked_ms = result.walked.count(), .wild_battles = result.wild_battles}); +} + +WalkResult LegTraceRouteIO::walk_to_wall(const RouteWallWalk& walk){ + const WalkResult result = m_inner.walk_to_wall(walk); + walked(result); + return result; +} + +WalkResult LegTraceRouteIO::walk_taps(Pokemon::Direction direction, size_t tiles, const std::string& label){ + const WalkResult result = m_inner.walk_taps(direction, tiles, label); + m_tracer.walked({.chunks = result.moved_chunks, .walked_ms = result.walked.count(), + .wild_battles = result.wild_battles, .tapped = result.moved_chunks}); + return result; +} + +void LegTraceRouteIO::note(const std::string& text, RouteNote kind){ + if (kind == RouteNote::FAILURE){ + // A failure does not return: the leg ends here, unknown. + m_tracer.end_event(); + m_inner.note(text, kind); + return; + } + m_inner.note(text, kind); + read_route_line(text); +} + +namespace{ + +// The text between `after` and `before` in `text`, both searched from the +// end; empty if either is missing. +std::string_view between_last(std::string_view text, std::string_view after, std::string_view before){ + const size_t end = text.rfind(before); + if (end == std::string_view::npos){ + return {}; + } + const size_t begin = text.rfind(after, end); + if (begin == std::string_view::npos){ + return {}; + } + return text.substr(begin + after.size(), end - begin - after.size()); +} + +} // namespace + +// The planned route walker's lines (PokemonBDSP_AutoStory_PlannedRoute.cpp, +// Pokemon_RouteLog.h): +// Leg 1/2: east 15 (to wall) to Route 202 (23, 25) +// [Route]