diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index b9eacc3ad3..97e85e6e14 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -11,13 +11,16 @@ #include "Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_SimulatedRoute_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_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/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" #include "Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h" #include "PokemonBDSP_Tests.h" @@ -33,6 +36,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_Actions(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_StoryData(database); @@ -41,6 +45,8 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_WildBattlePolicy(database); add_tests_AutoStory_PlannedRoute(database); add_tests_AutoStory_SimulatedRoute(database); + add_tests_AutoStory_WallBattleSim(database); + add_tests_AutoStory_StoryActions(database); add_tests_StarterRng(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp new file mode 100644 index 0000000000..e998679547 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp @@ -0,0 +1,465 @@ +/* BDSP AutoStory Route Planner Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The route planner (Data/PokemonBDSP_AutoStory_RoutePlanner.h) on small + * synthetic maps: walks to a wall, plans that end on walls, robust plans + * that bring several possible tiles together, and trainers' sight lines. + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/PokemonBDSP_AutoStory_RobustRoute.h" +#include "Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "Data/PokemonBDSP_AutoStory_TrainerSight.h" +#include "Data/PokemonBDSP_AutoStory_WalkRules.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{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using Pokemon::Direction; +using Pokemon::TilePos; + +// 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(), {}}; + for (const std::string& row : rows){ + for (char glyph : row){ + 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; +} + +std::string describe(const std::vector& legs){ + std::string text; + for (const PlannedLeg& leg : legs){ + text += (text.empty() ? "" : "; ") + to_string(leg); + } + return text; +} + + +struct WallCase{ + std::string name; + std::vector rows; + TilePos from = {}; + Direction direction = Direction::EAST; + TilePos stop = {}; + size_t tiles = 0; + bool anchored = false; +}; + +UnitTestResult test_walk_to_wall(Logger&){ + const std::vector cases{ + {.name = "to a wall", .rows = {"....#"}, .stop = {3, 0}, .tiles = 3, .anchored = true}, + {.name = "off the map", .rows = {"...."}, .stop = {3, 0}, .tiles = 3, .anchored = false}, + {.name = "into a door", .rows = {"..D"}, .stop = {1, 0}, .tiles = 1, .anchored = false}, + {.name = "over a ledge, which counts 2", .rows = {".", "v", ".", "#"}, .direction = Direction::SOUTH, + .stop = {0, 2}, .tiles = 2, .anchored = true}, + }; + for (const WallCase& item : cases){ + const WallHit hit = slide_to_wall(make_world(item.rows), item.from, item.direction); + if (!(hit.stop == item.stop) || hit.tiles != item.tiles || hit.anchored != item.anchored){ + return std::format("{}: stops at {} after {} tiles, anchored {}; expected {} after {}, anchored {}.", item.name, + Pokemon::to_string(hit.stop), hit.tiles, hit.anchored, Pokemon::to_string(item.stop), item.tiles, item.anchored); + } + } + return true; +} + + +// plan_tile_route() around a pillar: two legs, both to a wall, that trace +// to the goal. +UnitTestResult test_plan_tile_route(Logger& logger){ + const StoryWorld world = make_world({"#####", "#...#", "#.#.#", "#...#", "#####"}); + const std::optional> legs = plan_tile_route(world, {1, 1}, {3, 3}); + if (!legs || legs->size() != 2 || !(*legs)[0].ends_at_wall || !(*legs)[1].ends_at_wall){ + return std::string("Expected two legs, both to a wall."); + } + if (!(trace_legs(world, {1, 1}, *legs).back() == TilePos{3, 3})){ + return std::string("The legs do not end on (3, 3)."); + } + logger.log(std::format("{}, {}", to_string((*legs)[0]), to_string((*legs)[1]))); + const std::optional> none = plan_tile_route(world, {1, 1}, {1, 1}); + if (!none || !none->empty()){ + return std::string("A route to the start is not empty."); + } + return true; +} + + +// plan_robust_route() from one or several tiles to a goal, with the open +// legs' error as the costs give it. +struct RobustCase{ + std::string name; + std::vector from; + TilePos goal; + RobustPlanCosts costs = {}; + // The plan as to_string() writes it, or empty when there is none. + std::string legs; +}; + +UnitTestResult test_plan_robust_route(Logger&){ + const StoryWorld world = make_world({"######", "#....#", "######"}); + RobustPlanCosts exact_step; + exact_step.exact_open_tiles = 1; + const std::vector cases{ + {.name = "two starts meet at the wall", .from = {{1, 1}, {2, 1}}, .goal = {4, 1}, .legs = "east 3 (to wall) to (4, 1)"}, + {.name = "an open stop is never sure", .from = {{1, 1}}, .goal = {3, 1}, .legs = ""}, + {.name = "unless a one-tile step is exact", .from = {{1, 1}}, .goal = {3, 1}, .costs = exact_step, + .legs = "east 3 (to wall) to (4, 1); west 1 (open) to (3, 1)"}, + }; + for (const RobustCase& item : cases){ + const auto legs = plan_robust_route(world, item.from, [&](const TilePos& pos){ return pos == item.goal; }, item.costs); + const std::string read = legs ? describe(*legs) : ""; + if (read != item.legs){ + return std::format("{}: planned \"{}\", expected \"{}\".", item.name, read, item.legs); + } + } + try{ + plan_robust_route(world, TilePos{0, 0}, TilePos{4, 1}); + return std::string("A start on a wall did not throw."); + }catch (InternalProgramError&){} + return true; +} + +// A held run on to a wall and tapped back is fine from the start, but not +// after a tapped leg: the player is exactly where the taps left them, and a +// run past that tile and back only adds a turn (lab-B 2026-11-12 14:24, 00.05c +// "south 15 (to wall), north 1" after "east 19 (open)"). +UnitTestResult test_robust_wall_and_back_not_after_taps(Logger&){ + // East along the top row, which goes on past column 5, then down column 5 + // to the goal a few tiles above the wall. + std::vector rows{"#########", "#.......#"}; + for (int y = 0; y < 40; y++){ + rows.push_back("#####.###"); + } + rows.push_back("#########"); + const StoryWorld world = make_world(rows); + RobustPlanCosts costs; + costs.exact_open_tiles = costs.max_open_tiles; + const auto legs = plan_robust_route(world, {{1, 1}}, [](const TilePos& pos){ return pos == TilePos{5, 38}; }, costs); + if (!legs){ + return std::string("no plan."); + } + for (size_t i = 1; i + 1 < legs->size(); i++){ + const TileLeg& before = (*legs)[i - 1].leg; + const TileLeg& wall = (*legs)[i].leg; + const TileLeg& back = (*legs)[i + 1].leg; + if (!before.ends_at_wall && wall.ends_at_wall && (int)back.direction == ((int)wall.direction + 2) % 4){ + return "a run to the wall and back after a tapped leg: " + describe(*legs); + } + } + 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 = "east along the row from inside it goes round, north first", .world = room, .from = {3, 2}, .goal = {5, 2}, + .legs = "north 1 (to wall) to (3, 1); east 2 (to wall) to (5, 1); south 1 (open) to (5, 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. +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 = {}; + std::optional still = {}; // someone who never moves +}; +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 (std::string_view 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}); + } + if (input.still){ + map.objects.push_back({.name = "still", .x = input.still->x, .y = input.still->y, .facing = std::nullopt, + .wander = std::nullopt, .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&){ + const StoryWorld world = make_world({".....", ".....", "..#.."}); + const TrainerSight trainer{.name = "lass", .pos = {2, 0}, .facing = Direction::SOUTH, .range = 4}; + if (sight_tiles(world, trainer) != std::vector{{2, 1}}){ + return std::string("The lass's sight is not the one tile above the rock."); + } + const std::vector legs{{Direction::EAST, 4, true}, {Direction::SOUTH, 1, false}}; + const auto crossings = legs_crossing_sight(world, {0, 1}, legs, {trainer}); + if (crossings != std::vector>{{"lass"}, {}}){ + return std::string("Only the first leg crosses the lass's sight."); + } + try{ + trace_legs(world, {0, 1}, {{Direction::SOUTH, 2, false}}); + return std::string("A leg off the map did not throw."); + }catch (InternalProgramError&){} + return true; +} + + +struct RoutePlannerInput{ + std::string name; + std::function body; +}; + +struct RoutePlannerExpectation{ +}; + +struct RoutePlannerCase{ + RoutePlannerInput input; + RoutePlannerExpectation expectation; +}; + +class Test_RoutePlanner : public UnitTest{ +public: + explicit Test_RoutePlanner(RoutePlannerCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Route planner: " + 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: + 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 = "a still person is a wall to anchor on", .from = {{2, 1}, {3, 1}}, + .warps = {{5, 1}}, .still = TilePos{.x = 1, .y = 1}}, + .expectation = {.anchor = TilePos{.x = 2, .y = 1}, .direction = Direction::WEST}}, + {.input = {.name = "warps on blocked glyphs are unsafe", .from = {{1, 1}, {5, 1}}, .warps = {{0, 1}, {6, 1}}}, + .expectation = {.anchor = std::nullopt}}, +}; + +} // namespace + + +const RoutePlannerCase ROUTE_PLANNER_CASES[] = { + { + .input = {"walking until stopped", test_walk_to_wall}, + .expectation = {}, + }, + { + .input = {"legs to walls around a pillar", test_plan_tile_route}, + .expectation = {}, + }, + { + .input = {"robust plans", test_plan_robust_route}, + .expectation = {}, + }, + { + .input = {"a run to the wall and back is not planned after a tapped leg", test_robust_wall_and_back_not_after_taps}, + .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 = {}, + }, +}; + +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); + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h new file mode 100644 index 0000000000..1a75a9811f --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h @@ -0,0 +1,24 @@ +/* BDSP AutoStory Route Planner Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RoutePlanner_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RoutePlanner_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Offline checks of the route planner on synthetic maps. +void add_tests_AutoStory_RoutePlanner(UnitTestDatabase& database); + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp new file mode 100644 index 0000000000..fd3b837f4a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -0,0 +1,625 @@ +/* BDSP AutoStory - Grid simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TrainerSight.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WalkRules.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegBattle.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkDpad.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkResult.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy.h" +#include "PokemonBDSP_AutoStory_GridSim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +using namespace detail; + +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); +} + +// 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); + +uint32_t step_rng(uint64_t& state){ + state = state * 6364136223846793005ULL + 1442695040888963407ULL; + return static_cast(state >> 32); +} + +} // namespace + + +namespace detail{ +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); +} +std::string_view 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 "?"; +} +} // namespace detail + +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; + } + m_player.dialog = false; + m_player.trainer.reset(); + m_player.scene.reset(); + m_player.warped.reset(); + if (m_world.can_run){ + m_player.can_run = *m_world.can_run; + } + for (SimWanderer& wanderer : m_wanderers){ + if (wanderer.time_offset > 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); + } +} + +namespace detail{ +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; +} + +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(); +} +} // namespace detail + +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 +// 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]) || std::find(m_world.doors.begin(), m_world.doors.end(), ahead[0]) != m_world.doors.end())){ + m_player.pos = sim_pos(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; + } + } + 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)){ + 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.fired.insert(m_player.fired.end(), trigger.spends.begin(), trigger.spends.end()); + m_player.dialog = true; + m_player.scene = trigger.name; + 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}; + } + m_player.warped.reset(); + 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; + } + sim_advance_time(*this, hold); + SimMove move = advance(direction, distance); + move.time = hold; + return move; +} + +Milliseconds sim_ms_per_tile(Direction direction, SimPace pace, bool can_run){ + 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); +} + +SimMove GridSim::hold(Direction direction, Milliseconds limit, SimPace pace){ + const Milliseconds tile_time = sim_ms_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){ + sim_advance_time(*this, tile_time); + 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; + } + } + for (SimWanderer& wanderer : m_wanderers){ + if (wanderer.pos == faced){ + m_player.dialog = true; + if (wanderer.goes_home){ + wanderer.pos = *wanderer.goes_home; + } + } + } + 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.scene.reset(); + m_player.dialog = false; +} + + +namespace detail{ +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 detail + + +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; +} + +// 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 fight_trainer() override{ + m_notes.push_back("[Sim escape] Fought as a trainer battle, then a potion check."); + } + 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); + } + std::string_view ended = "run from"; + if (result == WildEscapeResult::FOUGHT){ + ended = "fought to its end"; + }else if (result == WildEscapeResult::TRAINER_FOUGHT){ + ended = "fought as a trainer battle"; + } + 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)){ + escape_scripted_battle(encounter->battle, walk.label); + 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)}; + 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){ + 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}; + 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++){ + 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 + // 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++; + // 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; + } + 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); + result.warp.fade = move.stop == SimStop::WARP ? WarpFade::BLACK : WarpFade::NONE; + }else if (still >= 2){ + 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; +} + +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: + sim_advance_time(m_sim, input.hold * input.count); + break; + } + } +} + +RouteSight GridSimRouteIO::sight_within(const RouteWatch& watch){ + return {.dialog = watch.dialog && 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}; + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // 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 new file mode 100644 index 0000000000..2d39e28128 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h @@ -0,0 +1,340 @@ +// code-health: allow header_symbols -- grid simulation primitives and types for BDSP overworld movement simulation +/* 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 +#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/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TrainerSight.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkResult.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace detail{ + +// 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; +}; +// 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); +// 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, and +// spends the triggers named in `spends` with it: the same scene's. +struct SimTrigger{ + std::string name; + std::vector tiles; + std::vector spends = {}; +}; + +} // namespace detail + +// A tile, in the simulation's units. +using detail::SIM_TILE; +// Position in simulation units. +using detail::SimPos; +// Simulation position at the origin of a tile. +using detail::sim_pos; +// Checks if a position is exactly on grid. +using detail::on_grid; +// Returns the nearest tile to a position. +using detail::nearest_tile; +// Formats position as string. +using detail::to_string; +// Trigger region in simulation units. +using detail::SimTrigger; + +// Where the simulated player walks: the world (which must outlive the +// 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). +// 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 + std::optional goes_home = std::nullopt; // where they walk back to once talked to +}; + +// Simulated grid environment. +class GridSim; +namespace detail{ +// Advance simulation time. +void sim_advance_time(GridSim& sim, Milliseconds time); +// Get simulated wanderers. +const std::vector& sim_wanderers(const GridSim& sim); +// Add a simulated trigger. +void sim_add_trigger(GridSim& sim, SimTrigger trigger); +// Get simulated triggers. +const std::vector& sim_triggers(const GridSim& sim); +// Forget warp state. +void sim_forget_warp(GridSim& sim); +// Set simulated fight. +void sim_fight(GridSim& sim); +} // namespace detail +// What a GridSim walks on: the joined maps, the trainers, triggers, doors +// and wanderers on them, and whether the player can run yet. +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. +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 +}; +namespace detail{ +// Returns the debug string for a SimStop reason. +std::string_view sim_stop_name(SimStop stop); +} // namespace detail + +// 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 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 = {}; + 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 +}; +// A held walk's time per tile `direction` at `pace`, for a player who +// can run or not: GridSim::hold()'s pace. +Milliseconds sim_ms_per_tile(Pokemon::Direction direction, SimPace pace, bool can_run); + +// 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); + + // 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: + friend void detail::sim_advance_time(GridSim& sim, Milliseconds time); + friend const std::vector& detail::sim_wanderers(const GridSim& sim); + friend void detail::sim_add_trigger(GridSim& sim, SimTrigger trigger); + friend const std::vector& detail::sim_triggers(const GridSim& sim); + friend void detail::sim_forget_warp(GridSim& sim); + friend void detail::sim_fight(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; +}; + +namespace detail{ +// 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); +// 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); +} // namespace detail + + +// 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; +}; + +// 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; +}; +// 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{ +public: + // Every line noted goes to `notes`, which must outlive this. + GridSimRouteIO( + GridSim& sim, std::vector& notes, + 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; + virtual WalkResult walk_taps(Pokemon::Direction direction, size_t tiles, const std::string& label) override; + virtual void press(const RouteInput& input) override; + virtual RouteSight sight_within(const RouteWatch& watch) 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: + 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); + // 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. +struct GridSimFailure{ + std::string message; +}; + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif 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..d2b6949704 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.cpp @@ -0,0 +1,191 @@ +/* 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. +const std::string 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 = std::string(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); + // code-health: allow char_pointer -- std::getenv returns a const char pointer + 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_OldStorySteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp new file mode 100644 index 0000000000..f5152c7a97 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp @@ -0,0 +1,121 @@ +/* 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::GridPose; +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.action = "to_map"; + step.args["legs"] = std::vector{{.direction = Direction::WEST, .tiles = 8}}; + step.args["fight_wild"] = false; + step.pose_after = Pokemon::TileDeclared{.map = "Route203", .tiles = {TilePos{55, 9}}, .facing = 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.action = "to_wall"; + step.args["legs"] = std::vector{{.direction = Direction::SOUTH, .tiles = 4}}; + step.args["fight_wild"] = false; + step.pose_after = Pokemon::TileDeclared{.map = "Route204North", .tiles = {TilePos{20, 26}}, .facing = 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.action = "legs"; + step.args["legs"] = std::vector{{.direction = direction, .tiles = 19}}; + step.args["fight_wild"] = false; + return step; +} + +StoryStep old_coal_room_crate_cut(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "to_roarks_corner"; + step.action = "legs"; + step.args["legs"] = std::vector{ + {.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}, + }; + step.args["fight_wild"] = false; + return step; +} + +std::vector old_round_mom_to_the_mat(){ + StoryStep around; + around.kind = StoryStepKind::ROUTE; + around.name = "around_mom"; + around.action = "route"; + around.args["target"] = GridPose{.map = "PlayerHouse1F", .tiles = {TilePos{6, 9}}, .facing = Direction::SOUTH}; + around.args["fight_wild"] = false; + StoryStep step; + step.kind = StoryStepKind::STEP; + step.name = "to_moms_call"; + step.args["direction"] = Direction::SOUTH; + return {around, step}; +} + +StoryStep old_tap_into_the_gate(){ + StoryStep step; + step.kind = StoryStepKind::STEP; + step.name = "into_oreburgh_gate"; + step.action = "to_banner"; + step.args["direction"] = Direction::WEST; + step.pose_after = Pokemon::TileDeclared{.map = "OreburghGate", .tiles = {TilePos{27, 22}, TilePos{26, 22}}, .facing = Direction::WEST}; + return step; +} + +StoryStep old_west_along_the_field(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "west_along_the_field"; + step.action = "legs"; + step.args["legs"] = std::vector{{.direction = Direction::WEST, .tiles = 8}}; + step.args["fight_wild"] = false; + 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..bbd64ad818 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h @@ -0,0 +1,70 @@ +/* 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. + * +// code-health: allow header_symbols -- legacy story steps definitions for test parity verification + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OldStorySteps_H +#define PokemonAutomation_PokemonBDSP_AutoStory_OldStorySteps_H + +#include +#include +#include "Pokemon/AutoStory/Pokemon_StoryPose.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryStep.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(); + +// 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(); + +// 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). 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(); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp new file mode 100644 index 0000000000..df74f30fc7 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.cpp @@ -0,0 +1,322 @@ +/* BDSP AutoStory - Disturbances on the grid simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WalkRules.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegBattle.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP_AutoStory_SimDisturbance.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::TileKind; +using Pokemon::TilePos; + + +namespace{ + +// The caves on the story's way, where every tile has wild Pokemon. +constexpr std::string_view CAVE_MAPS[] = {"OreburghMineB1F", "OreburghMine", "RavagedPath"}; +// Drift comes in steps of this many thousandths of a tile: 4 ms of stick +// across, 6 ms up or down, so the grid sim puts it back on the grid exactly. +constexpr int DRIFT_STEP = 25; + +bool across(Direction direction){ + return direction == Direction::EAST || direction == Direction::WEST; +} +// The player's offset from their nearest tile along an axis. +int offset_of(const SimPos& pos, bool along_x){ + const TilePos tile = nearest_tile(pos); + return along_x ? pos.x - tile.x * SIM_TILE : pos.y - tile.y * SIM_TILE; +} +int along(const SimPos& pos, Direction direction){ + return across(direction) ? pos.x : pos.y; +} +bool wanderer_on(const GridSim& sim, const TilePos& pos){ + const std::vector& people = detail::sim_wanderers(sim); + return std::any_of(people.begin(), people.end(), [&](const SimWanderer& person){ return person.pos == pos; }); +} +// Whether the player can drift a little toward `direction`: the tile there +// is open ground with nobody on it, not a wall or a door. +bool room_toward(const GridSim& sim, Direction direction){ + const TilePos next = nearest_tile(sim.player().pos).next(direction); + const std::optional tile = sim.world().tile(next); + return tile && *tile != TileKind::DOOR && standable(sim.world(), next) && !wanderer_on(sim, next); +} +// A hold that stopped against what is in its way, not against a person. +bool stopped_at_wall(const GridSim& sim, const SimMove& move, Direction direction){ + return move.stop == SimStop::BLOCKED && !wanderer_on(sim, nearest_tile(sim.player().pos).next(direction)); +} + +bool in_cave(const StoryWorld& world, const TilePos& pos){ + const std::optional tile = world.to_local(pos); + return tile && std::ranges::any_of(CAVE_MAPS, [&](std::string_view map){ return tile->map == story_banner_name(std::string(map)); }); +} + +// Whether `box` of `map` holds `pos`. +bool holds(const Pokemon::TileBox& box, const TilePos& pos){ + return box.x0 <= pos.x && pos.x <= box.x1 && box.y0 <= pos.y && pos.y <= box.y1; +} + +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; +} + +} // namespace + + +SimDisturbance::SimDisturbance(Pokemon::DisturbancePlan plan) + : m_plan(std::move(plan)) +{} + +bool SimDisturbance::battle_at(const StoryWorld& world, const TilePos& pos){ + const std::optional tile = world.tile(pos); + if (!tile){ + return false; + } + const bool grass = *tile == TileKind::TALL_GRASS; + const bool cave = !grass && in_cave(world, pos); + m_tiles.grass += grass ? 1 : 0; + m_tiles.cave += cave ? 1 : 0; + const double rate = grass ? m_plan.rates.grass_encounter : cave ? m_plan.rates.cave_encounter : 0; + if (rate <= 0 || !m_plan.battles.chance(rate)){ + return false; + } + m_battles++; + return true; +} + +void SimDisturbance::reset(){ + m_x = {}; + m_y = {}; +} + +// The grid sim's position is the truth: a wall it stopped at, or a place +// the executor put the player, changes the offset, and the drift with it. +void SimDisturbance::sync(const GridSim& sim){ + for (bool along_x : {true, false}){ + Axis& axis = along_x ? m_x : m_y; + const int actual = offset_of(sim.player().pos, along_x); + if (actual != axis.applied){ + axis.drift = actual; + axis.applied = actual; + } + } +} + +void SimDisturbance::walked(GridSim& sim, Direction direction, int thousandths, bool at_wall, int drift_per_tile){ + sync(sim); + Axis& axis = across(direction) ? m_x : m_y; + if (at_wall){ + axis.drift = axis.applied; + return; + } + // In steps of DRIFT_STEP, which a stick press moves exactly. + const int64_t most = drift_per_tile / DRIFT_STEP; + const int64_t steps = m_plan.drift.between(-most, most) * thousandths / SIM_TILE; + axis.drift = std::clamp(axis.drift + (int)steps * DRIFT_STEP, -SIM_TILE + 100, SIM_TILE - 100); + materialize(sim, across(direction)); +} + +// Puts the drift past `fit` on the grid sim's position, with a stick press +// that far, and turns back the way the player faced. A wall or a door in +// the way absorbs it. +void SimDisturbance::materialize(GridSim& sim, bool along_x){ + Axis& axis = along_x ? m_x : m_y; + const int target = std::abs(axis.drift) > m_plan.rates.fit ? axis.drift : 0; + const int delta = target - axis.applied; + if (delta == 0){ + return; + } + const Direction direction = along_x ? (delta > 0 ? Direction::EAST : Direction::WEST) + : (delta > 0 ? Direction::SOUTH : Direction::NORTH); + if (!room_toward(sim, direction)){ + axis.drift = axis.applied; + return; + } + const Direction facing = sim.player().facing; + const SimPos before = sim.player().pos; + const Milliseconds tile_time = route_ms_per_tile(direction, MoveSpeed::WALK); + sim.tap(direction, Milliseconds((std::abs(delta) * tile_time.count() + SIM_TILE / 2) / SIM_TILE), true); + const int moved = along(sim.player().pos, direction) - along(before, direction); + axis.applied += moved; + if (std::abs(moved - delta) >= DRIFT_STEP){ + axis.drift = axis.applied; + } + sim.tap(facing, ROUTE_TURN_TAP, false); +} + +// The maps' wanderers on `world`, found from its wandering tiles: each +// tile's map, and who on that map wanders over it. +const std::vector& SimDisturbance::people(const StoryWorld& world){ + auto found = m_people.find(&world); + if (found != m_people.end()){ + return found->second; + } + std::vector& people = m_people[&world]; + for (const TilePos& pos : wandering_hazards(world)){ + const std::optional tile = world.to_local(pos); + for (const auto& [name, json] : bdsp_map_json()){ + if (!tile || story_banner_name(name) != tile->map){ + continue; + } + add_people(people, name, {pos.x - tile->pos.x, pos.y - tile->pos.y}, tile->pos); + } + } + return people; +} + +// Who on `map` (its tile (0, 0) at world tile `corner`) wanders over its +// tile `local`, if not in `people` yet. +void SimDisturbance::add_people(std::vector& people, const std::string& map, const TilePos& corner, const TilePos& local){ + for (const Pokemon::MapObject& object : story_map(map).objects){ + const std::string name = map + "/" + object.name; + const bool known = std::ranges::any_of(people, [&](const SimWanderer& person){ return person.name == name; }); + if (!object.wander || object.hide_flag || known || !holds(*object.wander, local)){ + continue; + } + const Pokemon::TileBox& box = *object.wander; + people.push_back({.name = name, .box = {corner.x + box.x0, corner.y + box.y0, corner.x + box.x1, corner.y + box.y1}, + .pos = {corner.x + object.x, corner.y + object.y}}); + } +} + +std::vector SimDisturbance::wanderers(const StoryWorld& world){ + std::vector out = people(world); + for (SimWanderer& person : out){ + person.seed = m_plan.wanderers.next(); + person.time_offset = Milliseconds(m_plan.wanderers.between(0, m_plan.rates.wanderer_start.count())); + person.step_interval = m_plan.rates.wander_step; + } + return out; +} + + +DisturbedHold disturbed_hold(GridSim& sim, SimDisturbance* noise, Direction direction, Milliseconds limit, SimPace pace){ + if (noise == nullptr){ + return {.move = sim.hold(direction, limit, pace)}; + } + // A tile at a time, at the hold's own pace. + const Milliseconds tile_time = sim_ms_per_tile(direction, pace, sim.player().can_run); + const int64_t tiles = limit < ROUTE_START_DELAY ? 0 : (limit - ROUTE_START_DELAY) / tile_time; + DisturbedHold out{.move = {.stop = SimStop::LIMIT}}; + for (int64_t i = 0; i < tiles && out.move.stop == SimStop::LIMIT; i++){ + const SimMove step = sim.hold(direction, ROUTE_START_DELAY + tile_time, pace); + out.move.distance += step.distance; + out.move.stop = step.stop; + if (step.stop == SimStop::LIMIT && noise->battle_at(sim.world(), nearest_tile(sim.player().pos))){ + out.battles++; + out.first_tile |= i == 0; + } + } + if (out.move.stop == SimStop::LIMIT){ + out.move.time = limit; + }else{ + const Milliseconds seen = out.move.stop == SimStop::BLOCKED ? 800ms : 0ms; + out.move.time = ROUTE_START_DELAY + tile_time * out.move.distance / SIM_TILE + seen; + } + if (out.move.stop == SimStop::LIMIT || out.move.stop == SimStop::BLOCKED){ + noise->walked(sim, direction, SIM_TILE, stopped_at_wall(sim, out.move, direction), noise->plan().rates.drift_per_tile); + } + return out; +} + + +WalkResult DisturbedRouteIO::walk_to_wall(const RouteWallWalk& walk){ + if (m_noise == nullptr){ + return GridSimRouteIO::walk_to_wall(walk); + } + const SimPace pace = walk.options.pace == DpadPace::RUN ? SimPace::RUN : SimPace::WALK; + const DisturbedHold hold = disturbed_hold(m_sim, m_noise, walk.direction, walk.limit, pace); + m_notes.push_back(std::format("[Sim] {}: held {} to {} at {}, {} wild battle(s).", walk.label, direction_name(walk.direction), + detail::sim_stop_name(hold.move.stop), to_string(m_sim.player().pos), hold.battles)); + WalkResult result{.stop = walk_stop(hold.move.stop), .walked = hold.move.time, .wild_battles = hold.battles, + .moved_chunks = (size_t)(hold.move.distance / SIM_TILE)}; + if (hold.first_tile){ + result.origin = WalkOrigin::MAY_PRECEDE_LEG; + } + return result; +} + +// A tap a tile, as GridSimRouteIO taps, drifting as the rates say; a battle on a tile stepped onto +// is fled and credited as a moved tile, as the console's walk credits it, +// and the taps go on. One on the first tap may have begun before it. +WalkResult DisturbedRouteIO::walk_taps(Direction direction, size_t tiles, const std::string& label){ + if (m_noise == nullptr){ + return GridSimRouteIO::walk_taps(direction, tiles, 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 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; + } + const int tap_drift = m_noise->plan().rates.tap_drift_per_tile; + if (move.distance > 0 && result.stop == WalkStop::LIMIT && tap_drift > 0){ + m_noise->walked(m_sim, direction, SIM_TILE, false, tap_drift); + } + if (move.distance > 0 && move.stop == SimStop::DONE && m_noise->battle_at(m_sim.world(), nearest_tile(m_sim.player().pos))){ + result.wild_battles++; + result.origin = tap == 0 ? WalkOrigin::MAY_PRECEDE_LEG : result.origin; + // The console's watchers time the battle from this tap. + record_tap_battle(result, tap + 1); + moved_at_battle = result.moved_chunks; + m_notes.push_back("[Sim] wild battle during " + label); + } + } + 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; +} + +// A stick press drifts with the tiles it moves. +void DisturbedRouteIO::press(const RouteInput& input){ + const SimPos before = m_sim.player().pos; + GridSimRouteIO::press(input); + if (m_noise == nullptr || input.kind != RouteInputKind::STICK){ + return; + } + const int moved = std::abs(along(m_sim.player().pos, input.direction) - along(before, input.direction)); + if (moved > 0){ + m_noise->walked(m_sim, input.direction, moved, false, m_noise->plan().rates.drift_per_tile); + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.h new file mode 100644 index 0000000000..14fdc775b4 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.h @@ -0,0 +1,126 @@ +/* BDSP AutoStory - Disturbances on the grid simulation + * + * From: https://github.com/PokemonAutomation/ + * + * One seed's disturbances (Pokemon::DisturbancePlan) played on a GridSim, + * as the console disturbs a run: + * + * - A wild battle on tall grass, or anywhere in a cave (Oreburgh Mine, + * the Ravaged Path), once the player has stepped onto the tile. It is + * fled, and the input goes on, as the console's walks go on. + * - Drift: a stick press or a hold stopped short of a wall ends up to + * DisturbanceRates::drift_per_tile off along its way, a D-pad tap up + * to DisturbanceRates::tap_drift_per_tile (none by default). Within DisturbanceRates::fit of the tile the player still + * fits a one-tile gap; past it, the grid sim has them part of a tile + * off, where a door frame or a rock's corner stops them. A walk that + * stops at a wall ends on its tile, and on the grid along that way. + * - The people who wander on the maps (MapObject::wander) walk about, + * each from a seed and a start of the plan's. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_SimDisturbance_H +#define PokemonAutomation_PokemonBDSP_AutoStory_SimDisturbance_H + +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_StoryMonteCarlo.h" +#include "PokemonBDSP_AutoStory_GridSim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// A seed's disturbances on a GridSim. Not thread-safe; one per run. +class SimDisturbance{ +public: + explicit SimDisturbance(Pokemon::DisturbancePlan plan); + + const Pokemon::DisturbancePlan& plan() const{ + return m_plan; + } + // Wild battles drawn so far. + size_t battles() const{ + return m_battles; + } + // Encounter tiles stepped onto so far. + struct EncounterTiles{ + size_t grass = 0; + size_t cave = 0; + }; + const EncounterTiles& encounter_tiles() const{ + return m_tiles; + } + // Whether stepping onto world tile `pos` starts a wild battle. + bool battle_at(const StoryWorld& world, const Pokemon::TilePos& pos); + // The player moved `thousandths` of a tile toward `direction` and did + // not stop at a wall (or, `at_wall`, stopped at one): drifts them by up + // to `drift_per_tile` thousandths a tile walked. + void walked(GridSim& sim, Pokemon::Direction direction, int thousandths, bool at_wall, int drift_per_tile); + // The player was put on a tile: no drift. + void reset(); + // The people who wander on `world`, each with a seed and start drawn. + std::vector wanderers(const StoryWorld& world); + +private: + // How far off the player is along one axis, in thousandths of a tile: + // `drift` in all, `applied` of it on the grid sim's position. + struct Axis{ + int drift = 0; + int applied = 0; + }; + void sync(const GridSim& sim); + void materialize(GridSim& sim, bool across); + const std::vector& people(const StoryWorld& world); + void add_people(std::vector& people, const std::string& map, const Pokemon::TilePos& corner, const Pokemon::TilePos& local); + + Pokemon::DisturbancePlan m_plan; + size_t m_battles = 0; + EncounterTiles m_tiles; + Axis m_x; + Axis m_y; + std::map> m_people; +}; + + +// A hold on the grid sim (GridSim::hold()), a tile at a time with wild +// battles and drift from `noise` if given. +struct DisturbedHold{ + SimMove move; + size_t battles = 0; + // A battle on the hold's first tile: the console cannot tell it from + // one that began before the hold (WalkOrigin::MAY_PRECEDE_LEG). + bool first_tile = false; +}; +// Holds toward `direction` for up to `limit`; see DisturbedHold. +DisturbedHold disturbed_hold(GridSim& sim, SimDisturbance* noise, Pokemon::Direction direction, Milliseconds limit, SimPace pace); + + +// GridSimRouteIO, disturbed by `noise` (none: GridSimRouteIO itself). +class DisturbedRouteIO : public GridSimRouteIO{ +public: + DisturbedRouteIO(GridSim& sim, std::vector& notes, SimDisturbance* noise, SimGrassBattles grass = {}) + : GridSimRouteIO(sim, notes, {}, {}, grass) + , m_sim(sim) + , m_notes(notes) + , m_noise(noise) + {} + + 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; + +private: + GridSim& m_sim; + std::vector& m_notes; + SimDisturbance* m_noise; +}; + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimTriggers.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimTriggers.cpp new file mode 100644 index 0000000000..56c1c0120c --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimTriggers.cpp @@ -0,0 +1,121 @@ +/* BDSP AutoStory - Story simulation triggers + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP_AutoStory_StorySim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::TilePos; + + +// 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). +namespace detail{ +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; +} + +// 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). + // 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}}}, + }; +} + +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}, .var = event.var, + }; + for (const ConsoleTrigger& seen : console_triggers()){ + if (seen.map == map && seen.name == event.name){ + out.trigger.tiles = seen.tiles; + } + } + // The maps name their events coord_event_0, 1, ...: a scene is spent by name, + // so the map goes in it. + out.trigger.name = map + " " + out.trigger.name; + return out; +} + +} // 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 detail + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimWanderWait.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimWanderWait.cpp new file mode 100644 index 0000000000..e1e8e8332b --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimWanderWait.cpp @@ -0,0 +1,120 @@ +/* BDSP AutoStory - Wait beside a wanderer, on the simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteTiming.h" +#include "PokemonBDSP_AutoStory_SimWanderWait.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::TilePos; + + +SimWanderWait::SimWanderWait(GridSim& sim, std::vector still) + : m_sim(sim) + , m_still(std::move(still)) +{} +bool SimWanderWait::step(Direction direction){ + return m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false).distance > 0; +} +void SimWanderWait::face(Direction direction){ + m_sim.tap(direction, 50ms, false); +} +bool SimWanderWait::ask(){ + const TilePos faced = nearest_tile(m_sim.player().pos).next(m_sim.player().facing); + bool someone = std::find(m_still.begin(), m_still.end(), faced) != m_still.end(); + for (const SimWanderer& wanderer : detail::sim_wanderers(m_sim)){ + someone |= wanderer.pos == faced; + } + // Whoever is faced answers: the world leaves a wanderer's box empty, + // so the press alone misses one standing on his spawn. + m_sim.press_a(); + m_sim.end_dialogue(); + detail::sim_advance_time(m_sim, 1500ms); + return someone; +} +void SimWanderWait::wait(Milliseconds time){ + detail::sim_advance_time(m_sim, time); +} + + +WanderWaitPlan wander_wait_plan(const Pokemon::StoryStep& step){ + const Pokemon::GridPose& stand = Pokemon::story_arg(step.args, "stand"); + const Pokemon::Pose exit = Pokemon::pose_of(*step.pose_after); + const Pokemon::GridPose& far_stand = Pokemon::story_arg(step.args, "far_stand"); + const Direction back = Pokemon::ALL_DIRECTIONS[((size_t)*stand.facing + 2) % 4]; + WanderWaitPlan plan{.sides = {{.stands = stand.tiles, .facing = *stand.facing}}, + .exit = Pokemon::tiles_of(exit).at(0), .exit_walls = {*Pokemon::facing_of(exit), back}}; + if (!far_stand.tiles.empty()){ + plan.sides.push_back({.stands = far_stand.tiles, .facing = *far_stand.facing}); + } + return plan; +} + + +namespace{ + +// The plan's tiles on `world`. +WanderWaitPlan on_world(WanderWaitPlan plan, const StoryWorld& world, const std::string& map){ + for (WanderWaitSide& side : plan.sides){ + for (TilePos& stand : side.stands){ + stand = story_to_world(world, map, stand); + } + } + plan.exit = story_to_world(world, map, plan.exit); + return plan; +} + +// Where the people of `map` the simulation does not walk stand: their +// spawns, on `world`. +std::vector still_people(const GridSim& sim, const StoryWorld& world, const std::string& map){ + std::vector out; + const std::vector& walking = detail::sim_wanderers(sim); + for (const Pokemon::MapObject& object : story_map(map).objects){ + const bool walks = std::ranges::any_of(walking, [&](const SimWanderer& wanderer){ return wanderer.name == object.name; }); + if (object.kind == Pokemon::ObjectKind::NPC && !walks){ + out.push_back(story_to_world(world, map, {object.x, object.y})); + } + } + return out; +} + +} // namespace + + +Pokemon::Outcome sim_wait_for_wanderer(GridSim& sim, const StoryWorld& world, const Pokemon::Pose& start, const Pokemon::StoryStep& step){ + const TilePos from = story_to_world(world, start.map, Pokemon::tiles_of(start).at(0)); + SimWanderWait body(sim, still_people(sim, world, start.map)); + const WanderWaitResult result = wait_beside_wanderer(body, from, on_world(wander_wait_plan(step), world, start.map)); + const std::string at = Pokemon::to_string(result.at); + switch (result.end){ + case WanderWaitEnd::TALKED: + return Pokemon::outcome_ok(); + case WanderWaitEnd::NO_TALK: + return Pokemon::outcome_failed("operation_failed", std::format("{}: no talk from any stand tile; on {}.", step.name, at)); + case WanderWaitEnd::STUCK: + return Pokemon::outcome_failed("operation_failed", std::format("{}: a step on the way stayed blocked at {}.", step.name, at)); + case WanderWaitEnd::LOST: + return Pokemon::outcome_failed("operation_failed", std::format("{}: a step from the exit moved to {}: not on the exit.", step.name, at)); + } + return Pokemon::outcome_failed("operation_failed", step.name + ": unknown wait end."); +} + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimWanderWait.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimWanderWait.h new file mode 100644 index 0000000000..6fc3498c4a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimWanderWait.h @@ -0,0 +1,56 @@ +/* BDSP AutoStory - Wait beside a wanderer, on the simulation + * + * From: https://github.com/PokemonAutomation/ + * + * wait_beside_wanderer() on the grid simulation: the wander wait tests' + * body, and the story simulation's wait_for_wanderer step. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_SimWanderWait_H +#define PokemonAutomation_PokemonBDSP_AutoStory_SimWanderWait_H + +#include +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "Pokemon/AutoStory/Pokemon_StoryPose.h" +#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WanderWait.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" +#include "PokemonBDSP_AutoStory_GridSim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// The wait on the simulation: a tap a tile, A at the faced tile, and the +// console's time per ask (the dialog watch). An ask talks to a wanderer +// on the faced tile, or to someone on one of `still` (world tiles): the +// people the simulation does not walk. +class SimWanderWait : public WanderWaitBody{ +public: + explicit SimWanderWait(GridSim& sim, std::vector still = {}); + virtual bool step(Pokemon::Direction direction) override; + virtual void face(Pokemon::Direction direction) override; + virtual bool ask() override; + virtual void wait(Milliseconds time) override; + +private: + GridSim& m_sim; + std::vector m_still; +}; + +// The wait plan of a wait_for_wanderer step, as the console reads it, in +// its map's tiles. +WanderWaitPlan wander_wait_plan(const Pokemon::StoryStep& step); + +// Plays wait_for_wanderer `step` on `sim`, on `world`, from the tile of +// `start` (its map's): the console's wait (wait_for_wanderer()), its +// failures named as there. Who on the map has no wanderer on `sim` +// stands on their spawn. +Pokemon::Outcome sim_wait_for_wanderer(GridSim& sim, const StoryWorld& world, const Pokemon::Pose& start, const Pokemon::StoryStep& step); + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif 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..9b795d8b73 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.cpp @@ -0,0 +1,248 @@ +/* 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{ +using namespace detail; + + +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.action = 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.action)){ + return "event " + step.action; + } + 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](const StoryStep&, RunState&){ + 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](const StoryStep&, RunState&){ + 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(step, state); + 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.action).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.action, actual, expected); + } + } + logger.log(std::format("{} (kind, action) 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, action) 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 new file mode 100644 index 0000000000..916fdcc598 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -0,0 +1,1069 @@ +/* BDSP AutoStory - Story simulation + * + * From: https://github.com/PokemonAutomation/ + * +// code-health: allow file_lines -- the sim executor, its knobs and the faults the console failures need share one translation unit + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkResult.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkScreen.h" +#include "PokemonBDSP_AutoStory_SimWanderWait.h" +#include "PokemonBDSP_AutoStory_StorySim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +using namespace detail; + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::GridPose; +using Pokemon::story_arg; +using Pokemon::Outcome; +using Pokemon::Pose; +using Pokemon::RunState; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + + +namespace detail{ +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}; +} +SimBeat sim_pause(std::string what, Milliseconds length, bool moving){ + return {.what = std::move(what), .length = length, .moving = moving}; +} +SimBeat sim_walk_past(std::string what, Milliseconds length){ + return {.what = std::move(what), .length = length, .moving = true, .at_player = true}; +} +SimBeat sim_fade(std::string what, Milliseconds length, WarpFade fade){ + return {.what = std::move(what), .length = length, .overworld = true, .moving = false, .fade = fade}; +} + +std::string play_scene(const SimScene& scene, const TalkOverRule& rule){ + const Milliseconds press = TALK_OVER_HOLD + talk_over_release(rule); + 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++; + } + Pokemon::ScreenEvents look{Pokemon::ScreenEvent::PLAYER_CAN_MOVE, Pokemon::ScreenEvent::SCREEN_STILL, Pokemon::ScreenEvent::PLAYER_STILL}; + if (beat < scene.size()){ + const SimBeat& shown = scene[beat]; + 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.set(Pokemon::ScreenEvent::PLAYER_STILL, !shown.at_player); + + look.merge(Pokemon::fade_events(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(); +} +} // namespace detail + +// 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, SettleKind kind, const std::string&){ + const bool fade = kind == SettleKind::AFTER_WARP; + m_misses.fading_in = false; + 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, .door = kind == SettleKind::DOOR}); + 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(); +} + +namespace{ + +// The fault counter for a miss counted from 0: none if not set. +Pokemon::FaultOccurrences miss_chances(std::optional miss){ + if (!miss){ + return {}; + } + return Pokemon::FaultOccurrences({(int)*miss + 1}); +} + +} // namespace + +void arm_misses(SimMisses& misses){ + misses.fade_chances = miss_chances(misses.fade); + misses.hold_chances = miss_chances(misses.hold); + misses.banner_chances = miss_chances(misses.banner); + misses.door_chances = miss_chances(misses.dark); + misses.tap_step_chances = miss_chances(misses.through); +} + +SimStoryStepIO::FadeShown SimStoryStepIO::next_fade(){ + const bool unseen = m_misses.fade_chances.next(); + const bool hold_unseen = m_misses.hold_chances.next(); + const FadeShown shown = unseen ? FadeShown::UNSEEN : hold_unseen ? 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). 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_route.check_fade_in(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 = disturbed_hold(m_sim, m_noise, direction, limit, SimPace::WALK).move; + if (move.stop == SimStop::WARP && next_fade() != FadeShown::SEEN && m_far_side()){ + limit -= std::min(limit, move.time); + move = disturbed_hold(m_sim, m_noise, direction, limit, SimPace::WALK).move; + } + if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ + m_route.note(label + ": " + std::string(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& label){ + m_route.check_fade_in(label); + 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 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 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){ + const std::optional taps = taps_to_banner(direction, map, max_taps); + // Through: the far side fades in as the step ends. + m_misses.fading_in = taps.has_value(); + return taps; +} +std::optional SimStoryStepIO::taps_to_banner(Direction direction, const std::string& map, size_t max_taps){ + if (m_misses.tap_step_chances.next()){ + m_misses.missed = true; + if (m_far_side() && m_misses.through_banner){ + return 0; + } + } + if (std::exchange(m_misses.banner_up, "") == map){ + return 0; + } + m_route.check_fade_in(std::format("{}: taps toward {}", m_step, map)); + 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; + } + WarpFade fade = WarpFade::NONE; + if (move.stop == SimStop::WARP){ + 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 != WarpFade::NONE){ + return tap; + } + } + return std::nullopt; +} + +void SimKnobRouteIO::check_fade_in(const std::string& label){ + if (m_knobs.slow_fade_in && std::exchange(m_misses.fading_in, false)){ + note(std::format("{}: moved while the last warp still faded in (no settle after it).", label), RouteNote::FAILURE); + } +} + +WalkResult SimKnobRouteIO::walk_to_wall(const RouteWallWalk& walk){ + check_fade_in(walk.label); + WalkResult result = DisturbedRouteIO::walk_to_wall(walk); + const TilePos ahead = nearest_tile(m_grid.player().pos).next(walk.direction); + const std::vector& people = sim_wanderers(m_grid); + const bool pushing = std::any_of(people.begin(), people.end(), [&](const SimWanderer& person){ + return person.pos == ahead; + }); + if (result.stop == WalkStop::BLOCKED && pushing){ + result.walked += m_knobs.pushing_someone; + } + if (result.warp.fade != WarpFade::NONE){ + for (const SimSlide& item : m_knobs.hold_slides){ + if (item.step == m_step && item.direction == walk.direction){ + m_misses.slid = true; + note("[Sim] held through a warp to " + Pokemon::to_string(item.far) + ".", RouteNote::LOG); + result = through_warp(item, result); + // A hold's walk stops on a change of the whole screen that walking cannot + // make when no battle follows (a warp whose fade fell between two frames, + // "its fade unseen", 8a570a642; the console's 21:54 hold), where the + // taps of a slide read the time out. + if (item.fade == SimFade::UNSEEN){ + result.stop = WalkStop::TRANSITION; + } + return result; + } + } + } + return result; +} + +WalkResult SimKnobRouteIO::walk_taps(Direction direction, size_t tiles, const std::string& label){ + check_fade_in(label); + const WalkResult result = DisturbedRouteIO::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 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++){ + 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); + return through_warp(slide, result); + } + return result; +} + +// The player went through a warp to `slide.far` on a walk: the fade as the +// slide says, the walk's own result otherwise. +WalkResult SimKnobRouteIO::through_warp(const SimSlide& slide, WalkResult result){ + m_cross(slide.far); + m_misses.banner_up = slide.banner_up ? slide.far.map : ""; + if (slide.fade == SimFade::UNSEEN){ + m_misses.banner_soon = slide.far.map; + // The console's walk read the time out, not a fade. + result.warp.fade = WarpFade::NONE; + if (result.stop == WalkStop::TRANSITION){ + result.stop = WalkStop::LIMIT; + } + return result; + } + 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; + } + return result; +} + +RouteSight SimKnobRouteIO::sight_within(const RouteWatch& watch){ + RouteSight sight; + if (watch.dialog){ + const auto late = m_knobs.first_line.find(m_step); + if (late != m_knobs.first_line.end() && late->second > watch.wait){ + note(std::format("[Sim] {}: the first line comes after {} ms, past the {} ms wait.", m_step, late->second.count(), watch.wait.count()), RouteNote::LOG); + }else{ + sight = GridSimRouteIO::sight_within(watch); + } + } + if (watch.banner){ + sight.banner = std::exchange(m_misses.banner_soon, ""); + } + return sight; +} + +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 = 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))); + } + } + 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 = m_noise != nullptr ? m_noise->wanderers(*world) : 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 && m_knobs.standing.empty()){ + return out; + } + for (const auto& [map, json] : bdsp_map_json()){ + if (!on_world(world, map)){ + continue; + } + for (const auto& object : story_map(map).objects){ + const auto stands = m_knobs.standing.find(object.name); + const bool still = stands != m_knobs.standing.end(); + // A person who stays put on the map (a trainer) and stood elsewhere on the console. + if ((!object.wander && !still) || (!m_knobs.wander_seed && !still)){ + continue; + } + const uint64_t seed = m_knobs.wander_seed.value_or(0) * 1000003 + out.size() * 7919 + (uint64_t)(object.x * 31 + object.y); + const TilePos low = story_to_world(world, map, object.wander ? TilePos{object.wander->x0, object.wander->y0} : stands->second); + const TilePos high = story_to_world(world, map, object.wander ? TilePos{object.wander->x1, object.wander->y1} : stands->second); + 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, still ? stands->second : TilePos{object.x, object.y}), + .seed = seed, + .step_interval = still ? Milliseconds(0) : Milliseconds(2000), + .elapsed = Milliseconds(0), + .time_offset = still ? Milliseconds(0) : Milliseconds((int64_t)(seed % 2000)), + .goes_home = object.wander ? std::nullopt : std::optional(story_to_world(world, map, {object.x, object.y})), + }); + } + } + return out; +} + +// 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){ + std::vector now; + for (const RowTrigger& trigger : story_triggers()){ + if (trigger.row == m_row && trigger.after == after){ + 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 && settled() && !player.dialog){ + place(&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_misplaced) && 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 && settled() && std::find(tiles.begin(), tiles.end(), *local) != tiles.end()){ + return true; + } + const std::optional& start_at = m_knobs.start_at; + if (!m_placed && start_at && start_at->map == pose.map && !Pokemon::tiles_of(*start_at).empty()){ + place(world, story_to_world(*world, pose.map, Pokemon::tiles_of(*start_at).front()), Pokemon::facing_of(pose)); + m_placed = true; + m_misplaced = true; + m_logger.log(std::format("[{}] the save leaves the player on {}, off the declared {}.", m_row, to_string(*start_at), to_string(pose))); + return true; + } + place(world, story_to_world(*world, pose.map, tiles.front()), Pokemon::facing_of(pose)); + m_placed = true; + return true; +} + +void SimExecutor::start_scene_at_end(const StoryStep& step){ + std::optional end; + if (step.kind == StoryStepKind::ROUTE && step.args.contains("target")){ + end = Pokemon::pose_of(story_arg(step.args, "target")); + }else if (step.pose_after){ + end = Pokemon::pose_of(*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&){} + } + // 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 : 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))); + sim_add_trigger(m_sim, std::move(trigger)); +} + +void SimExecutor::land(const std::string& step){ + count_coupons(step); + slide_after_scene(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))); + } +} + +// The step's scene ran on: the player stands further along than the table's +// pose says (SimWorldKnobs::scene_slides), and stays there like a slide on (the next walks are not checked against the table). +void SimExecutor::slide_after_scene(const std::string& step){ + for (const SimSlide& item : m_knobs.scene_slides){ + if (item.step != step || !m_placed){ + continue; + } + for (size_t tile = 0; tile < item.tiles; tile++){ + m_sim.tap(item.direction, ROUTE_MS_PER_TILE_ACROSS, false); + } + m_sim.end_dialogue(); + m_astray = true; + m_notes.push_back(std::format("[Sim] scene ended {} tile(s) further, at {}.", item.tiles, to_string(m_sim.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(){ + 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; + } + place(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 (settled() && 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)}; + }, step.name); + if (m_misses.fading_in){ + return Pokemon::outcome_failed("heal", step.name + ": walked to the nurse while the Center was still fading in."); + } + 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. +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 ? std::optional(Pokemon::pose_of(*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::stub(){ + if (!m_result.rows.empty()){ + m_result.rows.back().stubbed.push_back(m_step); + } + m_sim.end_dialogue(); + return Pokemon::outcome_ok(); +} + +void SimExecutor::count_coupons(const std::string& step){ + static const std::set CLOWNS{"mart_clown", "tv_clown", "company_clown"}; + if (CLOWNS.contains(step) && !m_knobs.talks_without_coupon.contains(step)){ + m_coupons.insert(step); + } + if (step == "president"){ + m_poketch = m_coupons.size() == CLOWNS.size(); + m_logger.log(std::format("[{}] president: {} coupons, {}.", m_row, m_coupons.size(), m_poketch ? "the Poketch" : "no Poketch")); + } +} + +// 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](const StoryStep&, RunState&){ + return stub(); + }; + return StoryBoundActions{ + .new_game = stubbed, + .options = stubbed, + .answer = stubbed, + .battle = [this](const StoryStep& step, RunState& state){ + return battle(state, step); + }, + .train = stubbed, + .heal = [this](const StoryStep& step, RunState& state){ + return heal(state, step); + }, + .save = stubbed, + .event = [this](const std::string& name){ + return sim_event(name); + }, + }; +} + +Pokemon::StoryActionFunction SimExecutor::sim_event(const std::string& name){ + if (name == "check_poketch"){ + return [this](const StoryStep& step, RunState&){ + return m_poketch ? Pokemon::outcome_ok() : Pokemon::outcome_failed("no_poketch", step.name + ": no Poketch on the screen."); + }; + } + if (name == "wait_for_wanderer"){ + return [this](const StoryStep& step, RunState& state){ + return wait_for_wanderer(step, state); + }; + } + if (name == "check_coupons"){ + return [this](const StoryStep& step, RunState&){ + return m_coupons.size() == jubilife_clown_coupons().size() ? Pokemon::outcome_ok() + : Pokemon::outcome_failed("operation_failed", std::format("{}: {} of the coupons in the Key Items.", step.name, m_coupons.size())); + }; + } + return [this](const StoryStep&, RunState&){ + return stub(); + }; +} + +Outcome SimExecutor::wait_for_wanderer(const StoryStep& step, RunState& state){ + if (!sync(state.pose)){ + return stub(); + } + return sim_wait_for_wanderer(m_sim, m_sim.world(), state.pose, step); +} + +// 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); + 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); + 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; +} + +// 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](std::string_view what){ + return [this, what](const Pokemon::InterruptVerdict&, RunState&){ + 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(); + }; + }; + const auto battled = [this](std::string_view what){ + return [this, what](const Pokemon::InterruptVerdict&, RunState&){ + m_logger.log(std::format("[{}] {}: {} cleared before it.", m_row, m_step, what)); + m_battle_opening = false; + return Pokemon::outcome_ok(); + }; + }; + return StoryInterruptActions{ + .wild = battled("a wild battle"), + .trainer = battled("a trainer's battle"), + .dialog = cleared("a dialog"), + .warp = cleared("a warp"), + }; +} + +Outcome SimExecutor::run_action(const StoryStep& step, RunState& state){ + 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(step, state); +} + +Outcome SimExecutor::run_step(const StoryStep& step, RunState& state){ + if (!m_start_mismatch.empty()){ + return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); + } + m_far = step.pose_after ? std::optional(Pokemon::pose_of(*step.pose_after)) : std::nullopt; + // 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). + // 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 GridPose* target_ptr = step.args.contains("target") ? &story_arg(step.args, "target") : nullptr; + const StoryWorld* on = step.kind == StoryStepKind::ROUTE && target_ptr && !state.pose.map.empty() + ? story_plan_world(state.pose.map, target_ptr->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(); + } + 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(step, state); +} + +// Puts the player on `start` of `world`: on the grid, no drift. +void SimExecutor::place(const StoryWorld* world, const TilePos& start, std::optional facing){ + m_sim.place(setup(world), start, facing); + if (m_noise != nullptr){ + m_noise->reset(); + } +} + +// Whether the player stands on their tile: on the grid, or, disturbed, +// anywhere nearer it than another (how far off is the run's to find out). +bool SimExecutor::settled() const{ + return m_noise != nullptr || on_grid(m_sim.player().pos); +} + +void SimExecutor::record_failure(const Outcome& outcome, const StoryStep& step, size_t battles_before){ + // 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.failure = outcome.failure; + m_result.failure_detail = outcome.detail; + m_result.failed_step_battles = m_noise == nullptr ? 0 : m_noise->battles() - battles_before; +} + +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(const StoryStep& step, RunState& state){ + Outcome outcome; + m_passed_over = false; + m_step = step.name; + detail::sim_forget_warp(m_sim); + show_before(step); + const size_t battles_before = m_noise == nullptr ? 0 : m_noise->battles(); + try{ + outcome = run_step(step, state); + }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()){ + 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; + m_misplaced = false; + sync(Pokemon::pose_of(*step.pose_after)); + } + if (outcome.succeeded()){ + 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()){ + m_result.missed_step = m_row + " " + step.name; + } + if (!outcome.succeeded() && m_result.error.empty()){ + record_failure(outcome, step, battles_before); + } + m_result.battles = m_noise == nullptr ? 0 : m_noise->battles(); + 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); + 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::SegmentPolicy policy; + Pokemon::Segment segment = make_story_segment(rows, executor, saved, policy.save_mode); + policy.attempts_per_checkpoint = 1; + 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(range, policy, segment, hooks, state); +} + +// 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; +} + +namespace detail{ +// 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"; +} +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; +} +} // namespace detail + + +} // 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..7108b62067 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -0,0 +1,682 @@ +/* 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. + * With a SimDisturbance the run is disturbed as the console disturbs it + * (wild battles, drift off the grid, people wandering): the story's Monte + * Carlo tests. + * +// code-health: allow header_symbols -- story simulation executor, scenario runners and mock IO + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StorySim_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StorySim_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#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 "Pokemon/Navigation/Simulation/Pokemon_SimFaults.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.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_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" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkResult.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkScreen.h" +#include "PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_SimDisturbance.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 `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 detail::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 counters and flags below are the run's: each +// miss's chances on the shared fault counters (arm_misses()), 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 hold = {}; + std::optional dark = {}; + std::optional through = {}; + bool through_banner = false; + // The chances of the misses above, numbered from 1 where they count + // from 0: a fade is a chance of `fade` and of `hold`, a door run one of + // `dark`, a tap step one of `through`. + Pokemon::FaultOccurrences fade_chances = {}; + Pokemon::FaultOccurrences hold_chances = {}; + Pokemon::FaultOccurrences banner_chances = {}; + Pokemon::FaultOccurrences door_chances = {}; + Pokemon::FaultOccurrences tap_step_chances = {}; + bool missed = false; + bool fade_unseen = false; + // A door's fade showed and nothing has settled since: on the console + // the inside is still fading in, and a walk then goes nowhere (lab-B + // 2026-11-10, 00.04b heal_sandgem: "nurse not reached"). + bool fading_in = false; + bool slid = false; + std::string banner_up = {}; + // The map whose banner shows a second after a fade the walk missed + // (SimFade::UNSEEN): only a look within a wait reads it. + std::string banner_soon = {}; +}; + +// Sets the chances' counters of `misses` from its misses, none counted yet. +void arm_misses(SimMisses& misses); +// How many of a miss's chances the run looked for: its fades, banners, +// door runs or tap steps. +inline size_t looked_for(const Pokemon::FaultOccurrences& chances){ + return (size_t)chances.chances(); +} + +// 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 (SIM_DOOR_FADE). + BLACK, + // 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. The walk's old encounter-flash watcher read it + // as a wild battle. + WHITE, + // A door's fade the walk's frames miss (a short one between two): the + // walk goes on as if nothing happened and only the banner, a second or + // so later, shows the far map (lab-B 2026-11-12, 01.02's east mouth). + UNSEEN, +}; + +// 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; +}; + +namespace detail{ +// 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`. +// `at_player`: the moving reaches the box around the player. +struct SimBeat{ + std::string what; + bool line = false; + Milliseconds length = Milliseconds(0); + bool overworld = true; + bool moving = false; + bool at_player = 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 overworld with someone walking right past the player. +SimBeat sim_walk_past(std::string what, Milliseconds length); + +// `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. +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); +} // namespace detail + +// 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 = {}; + // A hold of the step `step` toward `direction` (a recovery's hold to a + // wall, a walk to a wall) that runs on through a warp its watchers + // miss: the player lands on `far` (lab-B 2026-11-12 20:20:50, 01.02's + // past_curtis, a hold east along row 22 that went out the Gate's east + // door). `tiles` is not used. + std::vector hold_slides = {}; + // A scene or trigger step `step` that leaves the player `tiles` toward + // `direction` past the pose the table gives it (lab-B 2026-11-12 21:02, + // 01.02's the_hiker: the walk east after it met Curtis a tile sooner than + // counted). The program goes on believing the table's pose. `far` is not used. + std::vector scene_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 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. + std::optional wander_seed = std::nullopt; + // People with a wander box who stand still on a tile of their map + // instead, by name, with or without wander_seed: 00.05b's boy below + // the Mart (school_kid_m_5, x 51, y 33..35) on row 34. + std::map standing = {}; + // How much longer a hold into someone standing still takes to read as + // stopped: the screen moves on while we push against them. On lab-B + // (2026-11-11 21:00, 00.05b) "east 8 (to wall)" stopped against the boy + // below the Mart after 2800 ms, about 5 tiles in, where a free run + // stops at its wall after about 2000. + Milliseconds pushing_someone = Milliseconds(0); + // 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 = {}; + // 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 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; + // A seed's disturbances (wild battles, drift off the grid, people + // wandering), which must outlive the run: the story's Monte Carlo tests. + // Within half a tile of where a step should end counts as there. + SimDisturbance* noise = nullptr; + // Where a step really leaves the player, by step name, when that is + // not the table's pose_after or the walk's end: 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; 00.04b's run into Sandgem two columns west, + // lab-B 2026-11-09 20:09). + 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; + // Every warp's fade-in runs long: a walk, a tap or a door run after a + // door's fade or a tap step's way through, with no settle() between, + // goes nowhere (lab-B 2026-11-10, 00.04b heal_sandgem walked to the + // nurse 1500 ms after the Center's fade and stopped on "transition"). + bool slow_fade_in = false; + // Where the first row's save really leaves the player, when that is not + // its declared start: the program starts from the declared start, the + // player from here (00.05, lab-B 2026-11-11: two tiles off). + std::optional start_at = std::nullopt; + // Jubilife's coupons (00.05b, 00.05c): the clown talks, by step name, + // whose coupon the save holds at the run's start; the clown talks that + // read another line first and give none (lab-B 2026-11-11: the + // Poketch Company's sign); and whether the save has the Poketch. The + // president's talk gives it with all three coupons only. + std::set coupons_at_start = {"mart_clown", "tv_clown", "company_clown"}; + std::set talks_without_coupon = {}; + bool poketch_at_start = true; +}; + +namespace detail{ + +// The walker's RouteIO on the story simulation, with SimWorldKnobs' slides +// and late first lines, disturbed by SimWorldKnobs::noise if set. `step` +// names the step running now; `cross` puts the player on a pose past a warp. +class SimKnobRouteIO : public DisturbedRouteIO{ +public: + SimKnobRouteIO( + GridSim& sim, std::vector& notes, SimMisses& misses, const SimWorldKnobs& knobs, + const std::string& step, std::function cross + ) + : DisturbedRouteIO(sim, notes, knobs.noise, knobs.grass) + , m_grid(sim) + , m_misses(misses) + , m_knobs(knobs) + , m_step(step) + , m_cross(std::move(cross)) + {} + + 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 RouteSight sight_within(const RouteWatch& watch) override; + // With SimWorldKnobs::slow_fade_in, fails the move `label` if the last + // warp is still fading in (SimMisses::fading_in). + void check_fade_in(const std::string& label); + +private: + WalkResult slide_on(const SimSlide& slide, WalkResult result); + WalkResult through_warp(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; +}; +} // namespace detail + +namespace detail{ + +// 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; +// 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); +// 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); +} // namespace detail + +// 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, 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. + const StoryWorld* world = nullptr; + Pokemon::TilePos end; + // Wild battles in the run, and in the step it failed in. + size_t battles = 0; + size_t failed_step_battles = 0; + // How the run failed: the failure and its message. + std::string failure; + std::string failure_detail; + // 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 +// 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_noise(knobs.noise) + , m_route(sim, notes, misses, knobs, step, std::move(cross)) + , m_misses(misses) + , m_knobs(knobs) + , m_far_side(std::move(far_side)) + , m_step(step) + {} + + 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 (sim_fight()). + virtual bool fight(const std::string&) override{ + detail::sim_fight(m_sim); + return true; + } + 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 + // 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{ + m_route.check_fade_in(std::format("{}: run into the door", m_step)); + const SimPace pace = run ? SimPace::RUN : SimPace::WALK; + if (false_dark() && dark_from <= detail::SIM_FALSE_DARK && detail::SIM_FALSE_DARK < timeout){ + disturbed_hold(m_sim, m_noise, direction, detail::SIM_FALSE_DARK, pace); + return {.fade = WarpFade::BLACK}; + } + if (disturbed_hold(m_sim, m_noise, direction, timeout, pace).move.stop != SimStop::WARP){ + return {}; + } + const WarpSeen seen = door_fade(banner); + m_misses.fading_in = seen.any(); + return seen; + } + // 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. With a scene in SimWorldKnobs::scenes, the program's + // TalkOver plays it instead. + virtual void settle(Button, const std::string& label, SettleKind kind, const std::string&) override; + virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) override; + +private: + // tap_to_banner()'s taps, before it marks the far side fading in. + std::optional taps_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps); + // 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.door_chances.next(); + m_misses.missed |= dark; + return dark; + } + bool banner_missed(){ + const bool miss = m_misses.banner_chances.next(); + 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; + SimDisturbance* m_noise; + detail::SimKnobRouteIO m_route; + SimMisses& m_misses; + const SimWorldKnobs& m_knobs; + std::function m_far_side; + const std::string& m_step; +}; + +namespace detail{ + +// 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`, 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 +// 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(); +} // namespace detail + +// 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 = {}) + : Pokemon::TableExecutor(m_table, m_guard) + , m_logger(logger) + , m_misses(misses) + , m_knobs(std::move(knobs)) + , m_noise(m_knobs.noise) + , 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())) + , m_interrupts(story_interrupts([this](bool fresh){ return look(fresh); }, sim_interrupt_actions())) + , m_coupons(m_knobs.coupons_at_start) + , m_poketch(m_knobs.poketch_at_start) + { + arm_misses(m_misses); + if (m_knobs.clear_interrupts){ + set_interrupts(&m_interrupts); + } + } + + const SimMisses& misses() const{ + return m_misses; + } + 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; + } + virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ + m_row = data.id; + m_start_mismatch = data.start ? off_pose(Pokemon::pose_of(*data.start)) : ""; + m_ran.clear(); + m_astray = false; + m_result.rows.push_back({.row = data.id, .fades = looked_for(m_misses.fade_chances), .banners = looked_for(m_misses.banner_chances)}); + m_walks.begin_attempt(data.id, data.steps); + arm(""); + } + virtual Pokemon::Outcome run(const Pokemon::StoryStep& step, Pokemon::RunState& state) 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(const Pokemon::StoryStep& step, Pokemon::RunState& state) override; + virtual Pokemon::Outcome heal(Pokemon::RunState& state, const Pokemon::StoryStep& step); + virtual Pokemon::Outcome new_game(Pokemon::RunState&, const Pokemon::StoryStep&){ return stub(); } + virtual Pokemon::Outcome options(Pokemon::RunState&, const Pokemon::StoryStep&){ return stub(); } + virtual Pokemon::Outcome answer(Pokemon::RunState&, const Pokemon::StoryStep&){ return stub(); } + virtual Pokemon::Outcome battle(Pokemon::RunState& state, const Pokemon::StoryStep& step); + virtual Pokemon::Outcome train(Pokemon::RunState&, const Pokemon::StoryStep&){ return stub(); } + virtual Pokemon::Outcome shop(Pokemon::RunState&, const Pokemon::StoryStep&){ return stub(); } + virtual Pokemon::Outcome save(Pokemon::RunState&, const Pokemon::StoryStep&){ return stub(); } + virtual Pokemon::Outcome game(Pokemon::RunState&, const Pokemon::StoryStep&){ 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(); + // A clown's coupon or the president's Poketch, after step `step` passed. + void count_coupons(const std::string& step); + StoryBoundActions sim_actions(); + // The BDSP event `name` on the simulation: the ones it plays, or a stub. + Pokemon::StoryActionFunction sim_event(const std::string& name); + // A wander wait, played from where the step before left us, on its map. + Pokemon::Outcome wait_for_wanderer(const Pokemon::StoryStep& step, Pokemon::RunState& state); + // 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); + 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); + 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, and counts its coupon or Poketch (count_coupons()). + void land(const std::string& step); + void slide_after_scene(const std::string& step); + 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(const Pokemon::StoryStep& step, Pokemon::RunState& state); + void place(const StoryWorld* world, const Pokemon::TilePos& start, std::optional facing); + bool settled() const; + void record_failure(const Pokemon::Outcome& outcome, const Pokemon::StoryStep& step, size_t battles_before); + + Logger& m_logger; + std::vector m_notes; + SimMisses m_misses; + SimWorldKnobs m_knobs; + SimDisturbance* m_noise; + // The step running now. + std::string m_step; + GridSim m_sim; + SimStoryStepIO m_io; + StoryWalkSteps m_walks; + 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; + bool m_dialog_rose = false; + // 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. + std::set m_ran; + // The clowns' coupons held and the Poketch (SimWorldKnobs::coupons_at_start). + std::set m_coupons; + bool m_poketch = true; + 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; + // 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; +}; + +// 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); +namespace detail{ + +// 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); +// 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); +} // namespace detail + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif 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..fcc990e132 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp @@ -0,0 +1,792 @@ +/* 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. 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. + * And 00.05c's greeter by the Wonder Station, who talks each time we come + * near: heard out each time, the walk still arrives. And a talk no battle + * follows that outlasts a press-through: heard out, the walk goes round. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.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{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +using namespace detail; + + +namespace{ + +using Pokemon::Direction; +using Pokemon::GridPose; +using Pokemon::story_arg; +using Pokemon::StoryStep; +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&){ return true; }}; + 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, .held = false}); + 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"}}, +}; + + +// 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 bool fight(const std::string& trainer) override{ + unsupported("a fight with " + trainer); + return false; + } + 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, SettleKind, 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.args.contains("target") && + step.args.contains("legs") && + story_arg>(step.args, "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 GridPose& target = story_arg(step.args, "target"); + const StoryWorld& world = *story_plan_world(start.map, 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, target.map, target.tiles.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 = story_arg>(into_dawns_scene().args, "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 > 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)); + } + 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}}, +}; + +// The Wonder Station's greeter in Jubilife's plaza walks up and talks +// whenever we come near, then walks off: on lab-B (2026-11-12 03:57, 00.05c +// below_the_company_clown; 00.05c's first walk is now beside_the_president) +// she stopped one walk three times, at about +// (44, 28), (43, 30) and (39, 32), and the third failed it as "dialogue the +// map does not explain". Here a step onto the step's greeter ground starts +// her dialogue, and so does the next one after each talk, `talks` in all. +struct GreeterInput{ + std::string name; + size_t talks; +}; +struct GreeterExpectation{ + bool arrives; +}; +struct GreeterCase{ + GreeterInput input; + GreeterExpectation expectation; +}; + +// Where the walk past `talks` of the greeter's went wrong, or "". +std::string walk_past_the_greeter(Logger& logger, size_t most_talks){ + const StoryStep* step = nullptr; + for (const StoryCheckpoint& row : story_checkpoints()){ + for (const StoryStep& s : row.steps){ + step = row.id == "00.05c" && s.name == "beside_the_president" ? &s : step; + } + } + const StoryWorld* world = story_plan_world("JubilifeCity", "JubilifeCity"); + if (step == nullptr || world == nullptr){ + return "00.05c beside_the_president: not in the table, or no JubilifeCity world."; + } + const std::vector greeter = story_route_tiles(*world, *step, "greeter"); + const TilePos start = story_to_world(*world, "JubilifeCity", {57, 22}); + const TilePos target = story_to_world(*world, "JubilifeCity", {45, 35}); + GridSim sim({.world = world, .trainers = {}, .triggers = {}}, start, Direction::WEST, true); + size_t talks = 0; + const auto arm = [&](){ + sim_add_trigger(sim, {.name = std::format("the greeter {}", talks), .tiles = greeter, .spends = {}}); + }; + arm(); + std::vector notes; + GridSimRouteIO sim_io(sim, notes); + RouteTrainers trainers{{}, [&](const std::string&){ + sim.end_dialogue(); + talks++; + if (talks < most_talks){ + arm(); + } + return false; + }}; + std::vector believed; + try{ + believed = walk_route(sim_io, *world, {start}, trainers, {.goal = [&](const TilePos& pos){ return pos == target; }, + .label = "beside the president", .avoid = story_route_tiles(*world, *step, "avoid"), .costs = *story_route_costs("town"), + .speed = MoveSpeed::RUN, .scene_next = false, .goal_is_trigger = false, .greeter = greeter}); + }catch (const GridSimFailure& e){ + return std::format("failed after {} talk(s): {}", talks, e.message); + } + for (const std::string& note : notes){ + logger.log(note); + } + const TilePos at = nearest_tile(sim.player().pos); + const bool arrived = believed == std::vector{target} && at == target && talks == most_talks; + return arrived ? "" : std::format("ended on {} after {} talk(s), not on {}.", describe(*world, at), talks, describe(*world, target)); +} + +class Test_GreeterSim : public UnitTest{ +public: + explicit Test_GreeterSim(GreeterCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Grid sim: 00.05c, the Wonder Station's greeter " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const std::string error = walk_past_the_greeter(logger, m_case.input.talks); + if (error.empty() != m_case.expectation.arrives){ + return error.empty() ? "arrived" : error; + } + return true; + } + +private: + GreeterCase m_case; +}; + +const GreeterCase GREETER_SIM_CASES[] = { + {.input = {.name = "talks once", .talks = 1}, .expectation = {.arrives = true}}, + {.input = {.name = "talks again on each leg near her (lab-B, 2026-11-12 03:57)", .talks = 3}, .expectation = {.arrives = true}}, +}; + +// A talk no battle followed, long enough to outlast a press-through, from +// someone who stands on the leg: on lab-B (2026-11-12 04:58, 00.05c +// below_the_company_clown, the 5th failure there) the Wonder Station's +// woman stopped "west 1 (to wall)" as "a trainer on the way", 2 s of B left +// her explanation on screen, and the walk on into her ran out of time. +// Here a corridor two rows high: her talk starts on (11, 1) and takes +// `presses` press-throughs to end; with `stands` she stays on (12, 1), +// which our map has open. +struct TalkerInput{ + std::string name; + size_t presses; + bool stands; +}; +struct TalkerExpectation{ + bool arrives; +}; +struct TalkerCase{ + TalkerInput input; + TalkerExpectation expectation; +}; + +// One press-through of the talk: the `needed`th ends it. +void press_through(GridSim& sim, size_t& presses, size_t needed){ + if (sim.player().dialog && ++presses >= needed){ + sim.end_dialogue(); + } +} + +// Where the walk past the talker went wrong, or "". +std::string walk_past_the_talker(Logger& logger, const TalkerInput& input){ + const std::vector open{ + "########################", + "#......................#", + "#......................#", + "########################", + }; + std::vector real = open; + if (input.stands){ + real[1][12] = '#'; + } + const StoryWorld map = make_world(open); + const StoryWorld world = make_world(real); + const TilePos start{1, 1}; + const TilePos target{22, 1}; + const SimTrigger talk{.name = "the woman", .tiles = {TilePos{11, 1}}}; + GridSim sim({.world = &world, .trainers = {}, .triggers = {talk}}, start, Direction::EAST, true); + std::vector notes; + GridSimRouteIO sim_io(sim, notes); + size_t presses = 0; + RouteTrainers trainers{{}, [&](const std::string&){ + press_through(sim, presses, input.presses); + return false; + }}; + std::vector believed; + try{ + believed = walk_route(sim_io, map, {start}, trainers, {.goal = [&](const TilePos& pos){ return pos == target; }, + .label = "past the talker", .avoid = {}, .costs = *story_route_costs("town"), .speed = MoveSpeed::RUN}); + }catch (const GridSimFailure& e){ + return std::format("failed after {} press-through(s): {}", presses, e.message); + } + for (const std::string& note : notes){ + logger.log(note); + } + const TilePos at = nearest_tile(sim.player().pos); + const bool arrived = believed == std::vector{target} && at == target; + return arrived ? "" : std::format("ended on {} believing {}, not on {}.", to_string(sim.player().pos), + believed.empty() ? std::string("nothing") : describe(map, believed[0]), describe(map, target)); +} + +class Test_TalkerSim : public UnitTest{ +public: + explicit Test_TalkerSim(TalkerCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Grid sim: a talk no battle follows " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const std::string error = walk_past_the_talker(logger, m_case.input); + if (error.empty() != m_case.expectation.arrives){ + return error.empty() ? "arrived" : error; + } + return true; + } + +private: + TalkerCase m_case; +}; + +const TalkerCase TALKER_SIM_CASES[] = { + {.input = {.name = "outlasts a press-through, then she walks off", .presses = 3, .stands = false}, .expectation = {.arrives = true}}, + {.input = {.name = "outlasts a press-through, and she stands on the leg (lab-B, 2026-11-12 04:58)", .presses = 3, .stands = true}, .expectation = {.arrives = true}}, + {.input = {.name = "ends in the fight, and she stands on the leg (lab-B, 2026-11-12 06:12)", .presses = 1, .stands = true}, .expectation = {.arrives = true}}, +}; + +// The plaza's greeter on an open leg, as lab-B saw her (2026-11-12 07:44, +// 00.05c below_the_company_clown, run 8): her talk stopped "south 5 (open)" +// from (46, 27) with no tap counted, so the stop could be any tile of the +// leg, (46, 27) to (46, 33); the walk planned from all seven, and her next +// talk, a tap later, spread it over two columns, from which no plan was +// found. Here her talk starts on each of `talks` tiles in turn (map tiles), +// and the console's count of taps before a talk is lost (UncountedTalkIO). +struct OpenLegTalkInput{ + std::string name; + std::vector talks; +}; +struct OpenLegTalkExpectation{ + bool arrives; +}; +struct OpenLegTalkCase{ + OpenLegTalkInput input; + OpenLegTalkExpectation expectation; +}; + +// Taps a talk stopped count none moved, as on lab-B (run 8). +class UncountedTalkIO : public RouteIO{ +public: + explicit UncountedTalkIO(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{ + WalkResult result = m_io.walk_taps(direction, tiles, label); + if (result.stop == WalkStop::DIALOG){ + result.moved_chunks = 0; + } + return result; + } + virtual void press(const RouteInput& input) override{ + m_io.press(input); + } + virtual RouteSight sight_within(const RouteWatch& watch) override{ + return m_io.sight_within(watch); + } + 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; +}; + +// Where the walk from (46, 27) past the greeter's talks went wrong, or "". +// It walks to the Poketch Company's clown, as on lab-B, on the plaza +// ground of 00.05c's walk to the president (the old walk's, unchanged). +std::string walk_open_leg_talks(Logger& logger, const OpenLegTalkInput& input){ + const StoryStep* step = nullptr; + for (const StoryCheckpoint& row : story_checkpoints()){ + for (const StoryStep& s : row.steps){ + step = row.id == "00.05c" && s.name == "beside_the_president" ? &s : step; + } + } + const StoryWorld* world = story_plan_world("JubilifeCity", "JubilifeCity"); + if (step == nullptr || world == nullptr){ + return "00.05c beside_the_president: not in the table, or no JubilifeCity world."; + } + const TilePos start = story_to_world(*world, "JubilifeCity", {46, 27}); + const TilePos target = story_to_world(*world, "JubilifeCity", {15, 19}); + GridSim sim({.world = world, .trainers = {}, .triggers = {}}, start, Direction::SOUTH, true); + size_t talks = 0; + const auto arm = [&](){ + if (talks < input.talks.size()){ + sim_add_trigger(sim, {.name = std::format("the greeter {}", talks), + .tiles = {story_to_world(*world, "JubilifeCity", input.talks[talks])}, .spends = {}}); + } + }; + arm(); + std::vector notes; + GridSimRouteIO sim_io(sim, notes); + UncountedTalkIO io(sim_io); + RouteTrainers trainers{{}, [&](const std::string&){ + sim.end_dialogue(); + talks++; + arm(); + return false; + }}; + std::vector believed; + std::string error; + try{ + believed = walk_route(io, *world, {start}, trainers, {.goal = [&](const TilePos& pos){ return pos == target; }, + .label = "beside the president", .avoid = story_route_tiles(*world, *step, "avoid"), .costs = *story_route_costs("town"), + .speed = MoveSpeed::RUN, .scene_next = false, .goal_is_trigger = false, .greeter = story_route_tiles(*world, *step, "greeter")}); + }catch (const GridSimFailure& e){ + error = std::format("failed after {} talk(s): {}", talks, e.message); + } + for (const std::string& note : notes){ + logger.log(note); + } + if (!error.empty()){ + return error; + } + const TilePos at = nearest_tile(sim.player().pos); + const bool arrived = believed == std::vector{target} && at == target && talks == input.talks.size(); + return arrived ? "" : std::format("ended on {} after {} talk(s), not on {}.", describe(*world, at), talks, describe(*world, target)); +} + +class Test_OpenLegTalkSim : public UnitTest{ +public: + explicit Test_OpenLegTalkSim(OpenLegTalkCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Grid sim: 00.05c, the greeter's talk on an open leg " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const std::string error = walk_open_leg_talks(logger, m_case.input); + if (error.empty() != m_case.expectation.arrives){ + return error.empty() ? "arrived" : error; + } + return true; + } + +private: + OpenLegTalkCase m_case; +}; + +const OpenLegTalkCase OPEN_LEG_TALK_SIM_CASES[] = { + {.input = {.name = "with no tap counted", .talks = {{46, 29}}}, .expectation = {.arrives = true}}, + {.input = {.name = "with no tap counted, then again a tap on (lab-B, 2026-11-12 07:44)", .talks = {{46, 29}, {45, 30}}}, .expectation = {.arrives = true}}, +}; + +// lab-B 2026-11-12 21:01, 01.02 past_curtis: camper_1's sight on column 17 +// stopped the taps on (17, 22), and the count read "blocked after 9 of 13" +// with the dialogue on the next tap: the walk placed us a tile or two back, +// marked the beaten camper's tile, and planned a loop round it. In the Gate +// the only way on is the east door along row 22, so any fight on the way +// ends in a hold east to the door's fade, fighting what stops us on the way +// (picnicker_0 on column 24). +class DialogOnNextTapIO : public GridSimRouteIO{ +public: + using GridSimRouteIO::GridSimRouteIO; + virtual WalkResult walk_taps(Direction direction, size_t tiles, const std::string& label) override{ + if (m_dialog_next){ + m_dialog_next = false; + return {.stop = WalkStop::DIALOG, .walked = 800ms, .wild_battles = 0, .moved_chunks = 0}; + } + WalkResult result = GridSimRouteIO::walk_taps(direction, tiles, label); + if (result.stop == WalkStop::DIALOG){ + result.stop = WalkStop::BLOCKED; + result.moved_chunks = result.moved_chunks > 0 ? result.moved_chunks - 1 : 0; + m_dialog_next = true; + } + return result; + } + +private: + bool m_dialog_next = false; +}; + +std::string leave_the_gate_by_the_east_door(Logger& logger, bool leave){ + const StoryWorld* world = story_plan_world("OreburghGate", "OreburghGate"); + if (world == nullptr){ + return "no OreburghGate world."; + } + // The Gate's trainers, as the game has them; the walk's map lists none + // of them (map_trainers() has no OreburghGate), so they are people it lacks. + const std::vector gate_trainers{ + {.name = "camper_1", .pos = story_to_world(*world, "OreburghGate", {17, 25}), .facing = Direction::NORTH, .range = 4}, + {.name = "picnicker_0", .pos = story_to_world(*world, "OreburghGate", {24, 21}), .facing = Direction::SOUTH, .range = 2}, + }; + const TilePos start = story_to_world(*world, "OreburghGate", {7, 22}); + const TilePos target = story_to_world(*world, "OreburghGate", {20, 22}); + GridSim sim({.world = world, .trainers = gate_trainers, .triggers = {}}, start, Direction::EAST, true); + std::vector notes; + DialogOnNextTapIO io(sim, notes); + std::vector fought; + RouteTrainers trainers{{}, [&](const std::string& name){ + fought.push_back(name); + sim.end_dialogue(); + return true; + }}; + RouteEnd end; + std::string error; + try{ + end = walk_route_to_warp(io, *world, {start}, trainers, {.goal = [&](const TilePos& pos){ return pos == target; }, + .label = "past curtis", .costs = *story_route_costs("town"), .speed = MoveSpeed::RUN, + .leave_toward = leave ? std::optional(Direction::EAST) : std::nullopt}); + }catch (const GridSimFailure& e){ + error = e.message; + } + for (const std::string& note : notes){ + logger.log(note); + } + if (!error.empty()){ + return error; + } + if (!end.warp.any() || !sim.player().warped){ + return std::format("did not leave by the east door: ended on {} after {} fight(s).", + describe(*world, nearest_tile(sim.player().pos)), fought.size()); + } + return fought.size() >= 2 ? "" : std::format("left after {} fight(s), not camper_1 and picnicker_0.", fought.size()); +} + +struct GateEastOutInput{ + std::string name; +}; +struct GateEastOutExpectation{ + bool leaves; +}; +struct GateEastOutCase{ + GateEastOutInput input; + GateEastOutExpectation expectation; +}; + +class Test_GateEastOut : public UnitTest{ +public: + explicit Test_GateEastOut(GateEastOutCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Grid sim: 01.02 past_curtis, " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const std::string error = leave_the_gate_by_the_east_door(logger, true); + if (error.empty() != m_case.expectation.leaves){ + return error.empty() ? "left" : error; + } + return true; + } + +private: + GateEastOutCase m_case; +}; + +const GateEastOutCase GATE_EAST_OUT_CASES[] = { + {.input = {.name = "a fight in the Gate ends in a hold east through the door (lab-B 2026-11-12 21:01)"}, .expectation = {.leaves = true}}, +}; + +} // namespace + + +void add_tests_AutoStory_WallBattleSim(UnitTestDatabase& database){ + for (const GateEastOutCase& item : GATE_EAST_OUT_CASES){ + database.add(item); + } + for (const OpenLegTalkCase& item : OPEN_LEG_TALK_SIM_CASES){ + database.add(item); + } + for (const TalkerCase& item : TALKER_SIM_CASES){ + database.add(item); + } + for (const GreeterCase& item : GREETER_SIM_CASES){ + database.add(item); + } + for (const WallBattleCase& item : WALL_BATTLE_SIM_CASES){ + database.add(item); + } + for (const SceneRunCase& item : SCENE_RUN_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..864d05a021 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h @@ -0,0 +1,29 @@ +/* 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. +// 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); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index fa0728a2c1..011caa9890 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1876,6 +1876,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources_Tests.cpp 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_SimulatedRoute_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_SimulatedRoute_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.cpp @@ -1908,6 +1910,23 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walks.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walks.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.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_SimDisturbance.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimDisturbance.h + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimTriggers.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimWanderWait.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimWanderWait.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_WallBattleSim_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_CountedWallLeg.h Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.cpp Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h