From eccd30fa447ac8eb1f20e5eaa6ce3c5513f9f15b Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 10 Nov 2026 23:26:06 -0800 Subject: [PATCH 1/5] Revert "AutoStory core: move the tile navigation package out of nav/shared" This reverts commit 0859830511bebfefe7680bbe9d6eaeee6338a6c3. --- .github/workflows/runtime-map-reader.yml | 29 + SerialPrograms/CMakeLists.txt | 2 + .../ComputerPrograms_UnitTestRunner.cpp | 12 + .../Pokemon/Navigation/Pokemon_LegPlanner.h | 366 +++++++++++ .../Navigation/Pokemon_LegPlanner_Tests.cpp | 419 +++++++++++++ .../Navigation/Pokemon_LegPlanner_Tests.h | 23 + .../Pokemon/Navigation/Pokemon_LegTypes.h | 117 ++++ .../Pokemon/Navigation/Pokemon_LegWalker.cpp | 105 ++++ .../Pokemon/Navigation/Pokemon_LegWalker.h | 212 +++++++ .../Navigation/Pokemon_LegWalker_Tests.cpp | 306 +++++++++ .../Navigation/Pokemon_LegWalker_Tests.h | 23 + .../Pokemon/Navigation/Pokemon_MapData.cpp | 586 ++++++++++++++++++ .../Pokemon/Navigation/Pokemon_MapData.h | 103 +++ .../Navigation/Pokemon_MapData_Tests.cpp | 526 ++++++++++++++++ .../Navigation/Pokemon_MapData_Tests.h | 23 + .../Pokemon/Navigation/Pokemon_MapFeatures.h | 100 +++ .../Pokemon/Navigation/Pokemon_MapTiles.h | 89 +++ .../Navigation/Pokemon_NavigationTestMaps.h | 26 + .../Pokemon/Navigation/Pokemon_RouteLog.cpp | 103 +++ .../Pokemon/Navigation/Pokemon_RouteLog.h | 71 +++ .../Pokemon/Navigation/Pokemon_RouteLogLegs.h | 53 ++ .../Navigation/Pokemon_RouteLogTypes.h | 54 ++ .../Navigation/Pokemon_RouteLog_Tests.cpp | 206 ++++++ .../Navigation/Pokemon_RouteLog_Tests.h | 23 + .../Pokemon/Navigation/Pokemon_RuntimeMap.cpp | 229 +++++++ .../Pokemon/Navigation/Pokemon_RuntimeMap.h | 22 + .../Navigation/Pokemon_RuntimeMap_Tests.cpp | 198 ++++++ .../Navigation/Pokemon_RuntimeMap_Tests.h | 17 + .../Pokemon/Navigation/Pokemon_WallRecovery.h | 134 ++++ .../Navigation/Pokemon_WallRecovery_Tests.cpp | 256 ++++++++ .../Navigation/Pokemon_WallRecovery_Tests.h | 23 + .../Pokemon/Navigation/TestMaps/BigField.json | 140 +++++ .../Pokemon/Navigation/TestMaps/Cave.json | 11 + SerialPrograms/cmake/SourceFiles.cmake | 28 + devtools/runtime-map-tests/CMakeLists.txt | 65 ++ devtools/runtime-map-tests/README.md | 55 ++ devtools/runtime-map-tests/legacy_tests.cpp | 37 ++ devtools/runtime-map-tests/prepare_parity.py | 55 ++ 38 files changed, 4847 insertions(+) create mode 100644 .github/workflows/runtime-map-reader.yml create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_NavigationTestMaps.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogLegs.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_WallRecovery.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_WallRecovery_Tests.cpp create mode 100644 SerialPrograms/Source/Pokemon/Navigation/Pokemon_WallRecovery_Tests.h create mode 100644 SerialPrograms/Source/Pokemon/Navigation/TestMaps/BigField.json create mode 100644 SerialPrograms/Source/Pokemon/Navigation/TestMaps/Cave.json create mode 100644 devtools/runtime-map-tests/CMakeLists.txt create mode 100644 devtools/runtime-map-tests/README.md create mode 100644 devtools/runtime-map-tests/legacy_tests.cpp create mode 100644 devtools/runtime-map-tests/prepare_parity.py diff --git a/.github/workflows/runtime-map-reader.yml b/.github/workflows/runtime-map-reader.yml new file mode 100644 index 0000000000..1fd59940a7 --- /dev/null +++ b/.github/workflows/runtime-map-reader.yml @@ -0,0 +1,29 @@ +name: Runtime map reader +on: + pull_request: + workflow_dispatch: +jobs: + native-schema: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v7 + - uses: actions/checkout@v7 + with: + repository: dayfine/PokemonSimulation + ref: 906956e94fc912ae9adb0e44845da780f3bc7e4c + path: publisher + - uses: actions/setup-python@v6 + with: + python-version: '3.12' + - run: python devtools/runtime-map-tests/prepare_parity.py --publisher publisher --publisher-revision 906956e94fc912ae9adb0e44845da780f3bc7e4c --out runtime-map-pairs.json + - run: cmake -S devtools/runtime-map-tests -B build-runtime-maps -DCMAKE_BUILD_TYPE=Debug + - run: cmake --build build-runtime-maps --config Debug -j4 + - run: ctest --test-dir build-runtime-maps -C Debug --output-on-failure + - if: runner.os != 'Windows' + run: ./build-runtime-maps/RuntimeMapTests runtime-map-pairs.json + - if: runner.os == 'Windows' + run: ./build-runtime-maps/Debug/RuntimeMapTests.exe runtime-map-pairs.json diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index 3265c73c14..6b925e88a3 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -225,6 +225,8 @@ add_library(SerialProgramsLib STATIC ${CORE_LIBRARY_SOURCES} ${LIBRARY_SOURCES}) # Data files built into the program (see cmake/EmbedTextFiles.cmake). include(cmake/EmbedTextFiles.cmake) +pa_embed_text_files(SerialProgramsLib Source/Pokemon/Navigation/TestMaps + Pokemon/Navigation/Pokemon_NavigationTestMaps.h PokemonAutomation::Pokemon navigation_test_map_json) # Create binary target diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 5b581f449e..5eec7c80d7 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -32,6 +32,12 @@ #include "NintendoSwitch/Programs/Typewriter/NintendoSwitch_Typewriter_Tests.h" #include "NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.h" +#include "Pokemon/Navigation/Pokemon_LegPlanner_Tests.h" +#include "Pokemon/Navigation/Pokemon_LegWalker_Tests.h" +#include "Pokemon/Navigation/Pokemon_MapData_Tests.h" +#include "Pokemon/Navigation/Pokemon_RouteLog_Tests.h" +#include "Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h" +#include "Pokemon/Navigation/Pokemon_WallRecovery_Tests.h" #include "VideoGames/PokemonHome/PokemonHome_Tests.h" #include "VideoGames/PokemonSwSh/PokemonSwSh_Tests.h" #include "VideoGames/PokemonLA/PokemonLA_Tests.h" @@ -68,6 +74,12 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ add_tests_LabControl(ret); OCR::add_tests(ret); Kernels::add_tests(ret); + Pokemon::add_tests_LegPlanner(ret); + Pokemon::add_tests_LegWalker(ret); + Pokemon::add_tests_WallRecovery(ret); + Pokemon::add_tests_MapData(ret); + Pokemon::add_tests_RuntimeMap(ret); + Pokemon::add_tests_RouteLog(ret); Pokemon::add_tests_AutoStory(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner.h new file mode 100644 index 0000000000..4ebb84e9c2 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner.h @@ -0,0 +1,366 @@ +/* Leg Planner + * + * From: https://github.com/PokemonAutomation/ + * + * Plans a walk as straight legs: hold one direction, then the next. The + * game decides what a single press does through its step model; the + * planner searches, joins steps into legs, and prefers legs that end + * against a wall, because the player stops there however long the button + * is held, while a leg that ends in the open depends on timing. It can + * weigh more heavily a leg ending in the open that went through tiles + * where the walk is likely to be interrupted (tall grass): after an + * interruption a leg to a wall is simply walked again, while how far an + * open one got is a guess. + * + * A step model is a class with: + * + * using State = ...; // where the player is and what moves them: + * // comparable with == + * using StateHash = ...; // a hash of State, e.g. std::hash + * std::optional> press(const State& state, Direction direction) const; + * bool held_at(const State& state, Direction direction) const; + * + * press() is what pressing `direction` once does, or nothing if the player + * can't go that way (a wall, or something the plan must not do). held_at() + * is whether holding `direction` keeps the player on this tile: a wall, but + * not a person who may walk off or an edge to a map that isn't loaded. + * + */ + +#ifndef PokemonAutomation_Pokemon_LegPlanner_H +#define PokemonAutomation_Pokemon_LegPlanner_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What one press does. +template +struct Step{ + State next; + // 0 for a plain step. Anything else is a step of the game's own kind + // (e.g. starting to Surf), planned as a leg on its own. + int action = 0; + // The step can't continue the leg before it, e.g. leaving the water, + // after which the player walks at another speed. + bool starts_leg = false; + // No later step continues this leg: the game stops the player, e.g. + // at a warp. + bool ends_leg = false; + // The step takes a warp: a door, a ladder, a cave entrance. + bool warped = false; + // Which way the player faces afterwards. Usually the pressed direction; + // some warps turn the player. + Direction facing = Direction::NORTH; + // Cost on top of LegCosts::per_tile: tall grass, a warp's fade, a dialog. + int extra_cost = 0; + // The walk can be interrupted on this step, e.g. by a wild battle in + // tall grass. See LegCosts::per_open_wild_stop. + bool wild = false; +}; + + +// Category of navigation action in a route leg. +enum class LegKind{ + WALK, // hold `direction` for `tiles` steps + ACTION, // one step of the game's own kind, `action` + FACE, // turn to `direction` without moving +}; + +// Single continuous movement leg or turn action. +template +struct Leg{ + LegKind kind = LegKind::WALK; + int action = 0; + Direction direction = Direction::NORTH; + int tiles = 0; + // WALK: the last step takes a warp. + bool warps = false; + // WALK: holding on keeps the player on the last tile, so the leg can be + // held for longer than it takes and walked again after an interruption. + bool to_wall = false; + // A step of the leg is wild (Step::wild). + bool wild = false; + Direction facing_after = Direction::NORTH; + State start; + State end; +}; + + +// Weights and penalties used during route planning. +struct LegCosts{ + int per_tile = 1; + // Extra for a step in a new direction. + int per_turn = 2; + // Extra for ending a leg where the player could keep going: it has to + // be timed, and where an interruption leaves the player is a guess. + int per_open_stop = 8; + // Extra again when that leg has a wild step, where an interruption is + // likely. + int per_open_wild_stop = 0; +}; + + +// The cheapest legs from `start` to a state where `at_goal` holds, facing +// `goal_facing` if given, or nothing if there is none. `start_facing` is +// the way the player faces at the start, if known. +template +std::optional>> plan_legs( + const Model& model, + const typename Model::State& start, std::optional start_facing, + const std::function& at_goal, + std::optional goal_facing, + const LegCosts& costs = LegCosts() +); + + + +namespace LegPlannerInternal{ + +// A search node: the player, the way they face (4: not known), whether +// they are in the middle of a leg that could go on, and whether that leg +// had a wild step. +template +struct Node{ + State state; + int facing = 4; + bool moving = false; + bool wild = false; + + bool operator==(const Node& other) const = default; +}; + +// Hash functor for planner search nodes. +template +struct NodeHash{ + size_t operator()(const Node& node) const{ + return StateHash()(node.state) * 20 + node.facing * 4 + (node.moving ? 2 : 0) + (node.wild ? 1 : 0); + } +}; + +// Edge transition between search nodes. +template +struct Move{ + Node from; + Direction direction; + Step step; +}; + +// Cost incurred when stopping at a node. +template +int stop_cost(const Model& model, const Node& node, const LegCosts& costs){ + if (!node.moving || model.held_at(node.state, (Direction)node.facing)){ + return 0; + } + return costs.per_open_stop + (node.wild ? costs.per_open_wild_stop : 0); +} + +// Combines atomic movement steps into contiguous legs. +template +std::vector> join_legs(const Model& model, const State& start, const std::vector>& moves){ + std::vector> legs; + bool can_extend = false; + State before = start; + for (const Move& move : moves){ + const Step& step = move.step; + const bool extends = can_extend && step.action == 0 && !step.starts_leg + && legs.back().kind == LegKind::WALK && legs.back().direction == move.direction; + if (extends){ + legs.back().tiles++; + legs.back().wild |= step.wild; + }else{ + Leg leg; + leg.kind = step.action == 0 ? LegKind::WALK : LegKind::ACTION; + leg.action = step.action; + leg.direction = move.direction; + leg.tiles = 1; + leg.wild = step.wild; + leg.start = before; + legs.push_back(leg); + } + Leg& leg = legs.back(); + leg.warps = step.warped; + leg.to_wall = leg.kind == LegKind::WALK && !step.warped && model.held_at(step.next, move.direction); + leg.facing_after = step.facing; + leg.end = step.next; + can_extend = step.action == 0 && !step.ends_leg; + before = step.next; + } + return legs; +} + +// The search's working set. Nodes are kept in a list and queued by index, +// so State needs no ordering. +template +struct Search{ + using State = typename Model::State; + using Hash = NodeHash; + using Entry = std::pair; + + std::unordered_map, int, Hash> distance; + std::unordered_map, Move, Hash> came_from; + std::vector> nodes; + std::priority_queue, std::greater> queue; +}; + +// Looks up the distance to a search node. +template +int distance_of(const Search& search, const Node& node){ + auto iter = search.distance.find(node); + return iter == search.distance.end() ? std::numeric_limits::max() : iter->second; +} + +// Records `cost` as the way to `node` if it is cheaper than any so far. +template +void relax(const Node& node, int cost, const Move& move, Search& search){ + if (cost >= distance_of(search, node)){ + return; + } + search.distance[node] = cost; + search.came_from.insert_or_assign(node, move); + search.nodes.push_back(node); + search.queue.emplace(cost, search.nodes.size() - 1); +} + +// Queues every press from `current`, reached at `cost`. +template +void expand( + const Model& model, const Node& current, int cost, + const LegCosts& costs, Search& search +){ + for (Direction direction : ALL_DIRECTIONS){ + std::optional> step = model.press(current.state, direction); + if (!step){ + continue; + } + const bool continues = step->action == 0 && !step->ends_leg; + const bool extends = current.moving && current.facing == (int)direction + && step->action == 0 && !step->starts_leg; + const Node next{step->next, (int)step->facing, continues, (extends && current.wild) || step->wild}; + int step_cost = costs.per_tile + step->extra_cost; + if (current.facing != (int)direction){ + step_cost += costs.per_turn + stop_cost(model, current, costs); + } + relax(next, cost + step_cost, Move{current, direction, *step}, search); + } +} + +// What it costs to end at `node`: stopping there, then turning to +// `goal_facing`. +template +int arrival_cost( + const Model& model, const Node& node, + std::optional goal_facing, const LegCosts& costs +){ + int cost = stop_cost(model, node, costs); + if (goal_facing && node.facing != (int)*goal_facing){ + cost += costs.per_turn; + } + return cost; +} + +// Runs the search from `first` and returns the goal node cheapest to end +// at, or nothing if no goal can be reached. +template +std::optional> search_goal( + const Model& model, const Node& first, + const std::function& at_goal, + std::optional goal_facing, const LegCosts& costs, Search& search +){ + search.distance[first] = 0; + search.nodes.push_back(first); + search.queue.emplace(0, 0); + + std::optional> best_end; + int best_total = std::numeric_limits::max(); + while (!search.queue.empty()){ + const auto [cost, index] = search.queue.top(); + search.queue.pop(); + const Node current = search.nodes[index]; + if (cost != distance_of(search, current)){ + continue; + } + if (cost >= best_total){ + break; + } + if (!at_goal(current.state)){ + expand(model, current, cost, costs, search); + continue; + } + const int total = cost + arrival_cost(model, current, goal_facing, costs); + if (total < best_total){ + best_total = total; + best_end = current; + } + } + return best_end; +} + +// The moves from `first` to `end`, in order. +template +std::vector> trace_moves(const Search& search, const Node& first, const Node& end){ + std::vector> moves; + for (Node node = end; !(node == first); node = search.came_from.at(node).from){ + moves.push_back(search.came_from.at(node)); + } + std::reverse(moves.begin(), moves.end()); + return moves; +} + +// Constructs a leg that faces a direction in place. +template +Leg face_leg(const State& state, Direction direction){ + Leg face; + face.kind = LegKind::FACE; + face.direction = direction; + face.facing_after = direction; + face.start = state; + face.end = state; + return face; +} + +} // namespace LegPlannerInternal + + + +template +std::optional>> plan_legs( + const Model& model, + const typename Model::State& start, std::optional start_facing, + const std::function& at_goal, + std::optional goal_facing, + const LegCosts& costs +){ + using State = typename Model::State; + using Node = LegPlannerInternal::Node; + + const Node first{start, start_facing ? (int)*start_facing : 4, false, false}; + LegPlannerInternal::Search search; + const std::optional end = LegPlannerInternal::search_goal(model, first, at_goal, goal_facing, costs, search); + if (!end){ + return std::nullopt; + } + std::vector> legs = LegPlannerInternal::join_legs( + model, start, LegPlannerInternal::trace_moves(search, first, *end) + ); + if (goal_facing && end->facing != (int)*goal_facing){ + legs.push_back(LegPlannerInternal::face_leg(end->state, *goal_facing)); + } + return legs; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp new file mode 100644 index 0000000000..0d2db0642b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp @@ -0,0 +1,419 @@ +/* Leg Planner Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The planner on a small made-up game, with the kinds of tiles the real + * games have: walls, people, tall grass, a one-way tile and a warp. + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_LegPlanner.h" +#include "Pokemon_LegPlanner_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// '#' wall, '.' floor, '"' tall grass, 'p' a person (blocks, but may walk +// off, so not a wall to stop against), 'v' entered only going south, 'W' +// a warp to the tile marked 'X'. +class ToyGame{ +public: + using State = TilePos; + using StateHash = std::hash; + + explicit ToyGame(std::vector rows) + : m_rows(std::move(rows)) + { + for (int y = 0; y < (int)m_rows.size(); y++){ + for (int x = 0; x < (int)m_rows[y].size(); x++){ + if (m_rows[y][x] == 'X'){ + m_warp_to = {x, y}; + } + } + } + } + + std::optional> press(const State& state, Direction direction) const{ + const TilePos next = state.next(direction); + const char tile = at(next); + if (tile == '#' || tile == 'p' || (tile == 'v' && direction != Direction::SOUTH)){ + return std::nullopt; + } + Step step; + step.next = next; + step.facing = direction; + if (tile == '"'){ + step.extra_cost = 5; + step.wild = true; + } + if (tile == 'W'){ + step.next = m_warp_to; + step.warped = true; + step.ends_leg = true; + step.extra_cost = 10; + } + return step; + } + bool held_at(const State& state, Direction direction) const{ + const char tile = at(state.next(direction)); + return tile == '#' || (tile == 'v' && direction != Direction::SOUTH); + } + +private: + char at(const TilePos& pos) const{ + if (pos.y < 0 || pos.y >= (int)m_rows.size() || pos.x < 0 || pos.x >= (int)m_rows[pos.y].size()){ + return '#'; + } + return m_rows[pos.y][pos.x]; + } + + std::vector m_rows; + TilePos m_warp_to; +}; + + +std::string describe(const std::vector>& legs){ + std::string text; + for (const Leg& leg : legs){ + text += "\n "; + text += leg.kind == LegKind::FACE ? "face " : "walk "; + text += direction_name(leg.direction); + if (leg.kind == LegKind::WALK){ + text += std::format(" {}", leg.tiles); + } + if (leg.to_wall){ + text += " (to wall)"; + } + if (leg.wild){ + text += " (wild)"; + } + if (leg.warps){ + text += " (warp)"; + } + text += std::format(" -> {}", to_string(leg.end)); + } + return text; +} + +std::optional>> plan( + const ToyGame& game, TilePos from, TilePos to, + std::optional start_facing = std::nullopt, + std::optional goal_facing = std::nullopt, + const LegCosts& costs = LegCosts() +){ + return plan_legs(game, from, start_facing, std::function([to](const TilePos& pos){ return pos == to; }), goal_facing, costs); +} + +// The open-stop weight after a wild step, high enough to outweigh any detour +// in these grids. +LegCosts wild_stop_costs(){ + LegCosts costs; + costs.per_open_wild_stop = 300; + return costs; +} + + +UnitTestResult test_prefers_wall_legs(){ + // Two ways of equal length: east then south ends both legs in the open; + // south then east ends the last one against the pillar. + const ToyGame game({ + "......", + "...#..", + "......", + }); + const auto legs = plan(game, {0, 0}, {2, 1}); + if (!legs || legs->size() != 2){ + return std::format("Expected 2 legs:{}", legs ? describe(*legs) : " none"); + } + if ((*legs)[1].direction != Direction::EAST || !(*legs)[1].to_wall){ + return std::format("Expected to end going east into the pillar:{}", describe(*legs)); + } + return true; +} + +UnitTestResult test_person_is_not_a_wall(){ + // The only way ends next to a person, which isn't a wall to stop against. + const ToyGame game({ + "#####", + "#..p#", + "#####", + }); + const auto legs = plan(game, {1, 1}, {2, 1}); + if (!legs || legs->size() != 1 || (*legs)[0].to_wall){ + return std::format("Expected one open leg:{}", legs ? describe(*legs) : " none"); + } + return true; +} + +UnitTestResult test_avoids_grass(){ + // Straight through the grass is 4 tiles; around it is 8, cheaper with + // 5 extra per grass tile. + const ToyGame game({ + ".....", + ".\"\"\".", + ".....", + }); + const auto legs = plan(game, {0, 1}, {4, 1}); + if (!legs){ + return "No route."; + } + for (const Leg& leg : *legs){ + if (leg.end.y == 1 && leg.end.x > 0 && leg.end.x < 4){ + return std::format("Walked into the grass:{}", describe(*legs)); + } + } + return true; +} + +UnitTestResult test_one_way_tile(){ + // The 'v' can only be entered going south, so going back up must go around. + const ToyGame game({ + "#.#.#", + "#v#.#", + "#...#", + "#####", + }); + if (!plan(game, {1, 0}, {1, 2})){ + return "No route down through the one-way tile."; + } + const auto up = plan(game, {1, 2}, {1, 0}); + if (up){ + return std::format("Went up through the one-way tile:{}", describe(*up)); + } + return true; +} + +UnitTestResult test_warp_ends_leg(){ + // The warp on the left takes the player to X on the right. + const ToyGame game({ + "#######", + "#W.#X.#", + "#..#..#", + "#######", + }); + const auto legs = plan(game, {2, 2}, {5, 2}); + if (!legs){ + return "No route."; + } + bool warped = false; + for (const Leg& leg : *legs){ + if (leg.warps){ + warped = true; + if (!(leg.end == TilePos{4, 1})){ + return std::format("The warp leg ends at {}:{}", to_string(leg.end), describe(*legs)); + } + } + } + if (!warped){ + return std::format("Expected a warp leg:{}", describe(*legs)); + } + return true; +} + +UnitTestResult test_goal_facing(){ + const ToyGame game({ + "....", + }); + const auto legs = plan(game, {0, 0}, {2, 0}, std::nullopt, Direction::NORTH); + if (!legs || legs->back().kind != LegKind::FACE || legs->back().direction != Direction::NORTH){ + return std::format("Expected to end facing north:{}", legs ? describe(*legs) : " none"); + } + return true; +} + +UnitTestResult test_wild_leg(){ + // The only way crosses the grass: that leg is wild. One that doesn't isn't. + const ToyGame grass({ + ".\"\".", + }); + const auto through = plan(grass, {0, 0}, {3, 0}); + if (!through || through->size() != 1 || !(*through)[0].wild){ + return std::format("Expected one wild leg:{}", through ? describe(*through) : " none"); + } + const ToyGame floor({ + "....", + }); + const auto across = plan(floor, {0, 0}, {3, 0}); + if (!across || across->size() != 1 || (*across)[0].wild){ + return std::format("Expected one leg that isn't wild:{}", across ? describe(*across) : " none"); + } + return true; +} + +UnitTestResult test_open_wild_stop(){ + // Two ways down to the goal at (3, 2): turn south right after the + // grass, stopping in the open, or walk on to the wall and come back + // along the bottom row. The first is shorter by more than an open stop + // costs, but its open stop follows grass, so with the open-wild-stop + // weight the second wins. + const ToyGame game({ + ".\"\"..........", + "###.########.", + "###..........", + }); + const auto plain = plan(game, {0, 0}, {3, 2}); + if (!plain || plain->empty() || (*plain)[0].to_wall || !(*plain)[0].wild || (*plain)[0].end.x != 3){ + return std::format("Without the weight, expected a wild leg east to stop in the open at x = 3:{}", plain ? describe(*plain) : " none"); + } + const auto weighed = plan(game, {0, 0}, {3, 2}, std::nullopt, std::nullopt, wild_stop_costs()); + if (!weighed || weighed->empty() || !(*weighed)[0].to_wall){ + return std::format("With the weight, expected to walk east to the wall:{}", weighed ? describe(*weighed) : " none"); + } + return true; +} + +UnitTestResult test_open_stop_without_grass(){ + // The same map without grass: the weight changes nothing. + const ToyGame game({ + ".............", + "###.########.", + "###..........", + }); + const auto legs = plan(game, {0, 0}, {3, 2}, std::nullopt, std::nullopt, wild_stop_costs()); + if (!legs || legs->empty() || (*legs)[0].to_wall || (*legs)[0].wild || (*legs)[0].end.x != 3){ + return std::format("Expected to stop in the open at x = 3:{}", legs ? describe(*legs) : " none"); + } + return true; +} + +UnitTestResult test_wild_ends_with_leg(){ + // East through the grass to the wall, then south. The south leg has no + // wild step, so it still stops in the open at (2, 2) to turn east to + // the goal at (4, 2), rather than going around by the bottom row. + const ToyGame game({ + ".\"\"###", + "##.###", + "##...#", + "##.#.#", + "##.#.#", + "##.#.#", + "##.#.#", + "##.#.#", + "##.#.#", + "##.#.#", + "##.#.#", + "##.#.#", + "##...#", + }); + const auto legs = plan(game, {0, 0}, {4, 2}, std::nullopt, std::nullopt, wild_stop_costs()); + if (!legs || legs->size() != 3){ + return std::format("Expected 3 legs:{}", legs ? describe(*legs) : " none"); + } + const Leg& east = (*legs)[0]; + const Leg& south = (*legs)[1]; + if (!east.wild || !east.to_wall){ + return std::format("Expected a wild leg east to the wall:{}", describe(*legs)); + } + if (south.wild || south.to_wall || !(south.end == TilePos{2, 2})){ + return std::format("Expected the south leg to stop in the open at (2, 2):{}", describe(*legs)); + } + return true; +} + +UnitTestResult test_unreachable(){ + const ToyGame game({ + ".#.", + }); + if (plan(game, {0, 0}, {2, 0})){ + return "Planned through a wall."; + } + return true; +} + + +struct LegPlannerInput{ + std::string name; + UnitTestResult (*test)(); +}; + +struct LegPlannerExpectation{ + std::string_view description; +}; + +struct LegPlannerTestCase{ + LegPlannerInput input; + LegPlannerExpectation expectation; +}; + +class Test_LegPlanner : public UnitTest{ +public: + explicit Test_LegPlanner(LegPlannerTestCase scenario) + : UnitTest(std::format("Pokemon::LegPlanner - {}", scenario.input.name)) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.input.test(); + } + +private: + LegPlannerTestCase m_scenario; +}; + +const LegPlannerTestCase LEG_PLANNER_CASES[] = { + { + .input = {.name = "prefers legs that end at a wall", .test = test_prefers_wall_legs}, + .expectation = {.description = "ends last leg against a wall rather than in the open"}, + }, + { + .input = {.name = "a person is not a wall", .test = test_person_is_not_a_wall}, + .expectation = {.description = "does not treat an NPC obstacle as a wall to stop against"}, + }, + { + .input = {.name = "avoids tall grass", .test = test_avoids_grass}, + .expectation = {.description = "routes around tall grass tiles when cheaper"}, + }, + { + .input = {.name = "one-way tile", .test = test_one_way_tile}, + .expectation = {.description = "respects directional one-way constraints"}, + }, + { + .input = {.name = "a warp ends the leg", .test = test_warp_ends_leg}, + .expectation = {.description = "terminates the current leg upon entering a warp"}, + }, + { + .input = {.name = "turns to face the goal", .test = test_goal_facing}, + .expectation = {.description = "adds a final turn leg to match required goal orientation"}, + }, + { + .input = {.name = "nothing through a wall", .test = test_unreachable}, + .expectation = {.description = "returns empty plan when destination is blocked"}, + }, + { + .input = {.name = "a leg through grass is wild", .test = test_wild_leg}, + .expectation = {.description = "marks leg as wild when stepping through grass"}, + }, + { + .input = {.name = "an open stop after grass is weighed", .test = test_open_wild_stop}, + .expectation = {.description = "prefers wall stops over open stops following grass"}, + }, + { + .input = {.name = "the weight needs a wild step", .test = test_open_stop_without_grass}, + .expectation = {.description = "does not penalize open stop when route has no grass"}, + }, + { + .input = {.name = "a new leg is not wild", .test = test_wild_ends_with_leg}, + .expectation = {.description = "clears wild status on subsequent non-grass legs"}, + }, +}; + +} // namespace + + +void add_tests_LegPlanner(UnitTestDatabase& database){ + for (const auto& scenario : LEG_PLANNER_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.h new file mode 100644 index 0000000000..99a2e82047 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.h @@ -0,0 +1,23 @@ +/* Leg Planner Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_LegPlanner_Tests_H +#define PokemonAutomation_Pokemon_LegPlanner_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers leg planner algorithm unit tests. +void add_tests_LegPlanner(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h new file mode 100644 index 0000000000..c1a7401c3b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h @@ -0,0 +1,117 @@ +/* Leg Types + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_LegWalker.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_LegTypes_H +#define PokemonAutomation_Pokemon_LegTypes_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Something that stops the player part-way through a leg. +template +class LegInterrupt{ +public: + virtual ~LegInterrupt() = default; + + virtual std::string name() const = 0; + + // A new watcher for the screen the interruption brings up. + virtual std::unique_ptr make_watcher() const = 0; + + // How long after the step that set it off the watcher fires. The games + // only interrupt between steps, so from this the walker works out how + // many tiles of an open leg were walked. + virtual Milliseconds detection_delay() const = 0; + + // Clears it, leaving the player standing on the overworld, on the same + // tile and facing the same way. + virtual void clear(Console& console, Context& context) const = 0; +}; + +// Collection of interrupt detectors active during leg movement. +template +using LegInterrupts = std::vector>>; + + +// How the game moves the player: holds `direction` for `duration`, then +// lets go. +template +using LegMover = std::function; + + +// A straight leg, for a player standing still and facing its way. +struct LegSpec{ + Direction direction = Direction::NORTH; + int tiles = 0; + // A wall stops the player after the last tile. + bool to_wall = false; + // How long one tile takes, for this leg's direction and way of moving. + Milliseconds tile_time{0}; + // An open leg stops at its first interrupt, once cleared, instead of + // walking on from an estimate; the caller finds the player again. + bool stop_on_interrupt = false; + // A leg to a wall stops when, held again after an interrupt, it is + // interrupted again right away: something on the way, like a sign, + // interrupts every hold, so the wall is never reached. + bool stop_if_blocked = false; + // The steps (from 1) the game holds the player up a tile before, as + // FireRed does on a step onto a connected map: each makes a hold over + // it a tile longer. + std::vector stalled_steps = {}; +}; +// Formats a LegSpec into a descriptive string. +std::string to_string(const LegSpec& leg); + +// Execution summary of a completed or stopped leg movement. +struct LegResult{ + // Tiles walked, which is `tiles` unless the leg gave up. + int tiles = 0; + // Whether `tiles` is certain: an interrupted open leg is an estimate. + bool exact = true; + size_t interruptions = 0; + // The leg stopped at an interrupt (stop_on_interrupt, stop_if_blocked): + // the player is somewhere along it. For an open leg `tiles` is then how + // many the interrupt's timing says were walked (tiles_before_interrupt()), + // for the caller to look around; for a leg to a wall it is 0. + bool stopped = false; +}; + + +// How long to hold for `tiles` tiles: an open leg lets go half a tile before +// the last step would end, so the step under way finishes and no other +// starts; a leg to a wall is held two tiles longer than it takes. The last +// `tiles` of the leg are held for, a tile more for each of its stalled +// steps among them. +Milliseconds leg_hold(const LegSpec& leg, int tiles); + +// How many tiles an open leg had walked when an interrupt was seen +// `elapsed` into its hold, given the interrupt's detection delay. Steps end +// a whole number of tiles into the hold, so this rounds to the nearest. +int tiles_before_interrupt(const LegSpec& leg, Milliseconds elapsed, Milliseconds detection_delay, int remaining); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.cpp new file mode 100644 index 0000000000..a3da4fff8d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.cpp @@ -0,0 +1,105 @@ +/* Leg Walker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon_LegWalker.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string to_string(const LegSpec& leg){ + return std::format("{} {}{}", direction_name(leg.direction), leg.tiles, leg.to_wall ? " (to wall)" : ""); +} + + +Milliseconds leg_hold(const LegSpec& leg, int tiles){ + const int first = leg.tiles - tiles + 1; + const int stalls = (int)std::count_if( + leg.stalled_steps.begin(), leg.stalled_steps.end(), + [&](int step){ return step >= first && step <= leg.tiles; } + ); + const Milliseconds stalled = leg.tile_time * stalls; + if (leg.to_wall){ + return leg.tile_time * (tiles + 2) + stalled; + } + return leg.tile_time * (tiles - 1) + leg.tile_time / 2 + stalled; +} + +int tiles_before_interrupt(const LegSpec& leg, Milliseconds elapsed, Milliseconds detection_delay, int remaining){ + const Milliseconds since_first_step = elapsed - detection_delay + leg.tile_time / 2; + if (since_first_step.count() <= 0){ + return 0; + } + return std::clamp((int)(since_first_step / leg.tile_time), 0, remaining); +} + + +namespace{ + +// Whether `leg` stops at the interrupt just cleared: an open leg asked to +// stop at any, or a leg to a wall interrupted again within three tiles of +// being held again (a message there lags the step by about two tiles). +bool stops_here(const LegSpec& leg, const LegResult& result, const HoldOutcome& outcome){ + if (!leg.to_wall){ + return leg.stop_on_interrupt; + } + return leg.stop_if_blocked && result.interruptions > 1 && outcome.elapsed < leg.tile_time * 3; +} + +} // namespace + + +LegResult walk_leg_with(const LegSpec& leg, const LegCalls& calls, size_t max_interruptions){ + LegResult result; + int remaining = leg.tiles; + while (true){ + const std::optional outcome = calls.hold_watching(leg_hold(leg, remaining)); + if (!outcome){ + result.tiles = leg.tiles; + return result; + } + result.interruptions++; + if (result.interruptions > max_interruptions){ + calls.fail(std::format("Interrupted {} times on: {}", result.interruptions, to_string(leg))); + } + calls.clear(outcome->interrupt); + const std::string seen = std::format("{} after {}ms", calls.name(outcome->interrupt), outcome->elapsed.count()); + if (stops_here(leg, result, *outcome)){ + result.exact = false; + result.stopped = true; + if (leg.to_wall){ + calls.log(std::format("{}, stopping the leg.", seen)); + return result; + } + // The caller finds the player again, near where the timing says. + result.tiles = leg.tiles - remaining + + tiles_before_interrupt(leg, outcome->elapsed, calls.detection_delay(outcome->interrupt), remaining); + calls.log(std::format("{}, about {} of {} tiles walked, stopping the leg.", seen, result.tiles, leg.tiles)); + return result; + } + if (leg.to_wall){ + // The wall stops the player on the leg's last tile however far + // they got, so the leg is simply held again. + calls.log(std::format("{}, walking to the wall again.", seen)); + continue; + } + const int walked = tiles_before_interrupt(leg, outcome->elapsed, calls.detection_delay(outcome->interrupt), remaining); + remaining -= walked; + result.exact = false; + calls.log(std::format("{}, about {} tiles walked, {} to go.", seen, walked, remaining)); + if (remaining <= 0){ + result.tiles = leg.tiles; + return result; + } + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h new file mode 100644 index 0000000000..31be625cb4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h @@ -0,0 +1,212 @@ +/* Leg Walker + * + * From: https://github.com/PokemonAutomation/ + * + * Walks one leg of a plan: holds a direction for the leg's tiles while + * watching for whatever can stop the player part-way (a wild battle, a + * message, a trainer). Each of those is a LegInterrupt the game supplies. + * When one shows, the hold stops, the game clears it, and the rest of the + * leg is walked: a leg to a wall is simply held again, since the wall stops + * the player on its tile; for an open leg, how far the player got is worked + * out from when the interrupt was seen. + * + * How a direction is held (D-pad or stick) and how long a tile takes are + * the game's too, through LegMover. Templated on the console and the + * controller context, like run_until(), so this stays free of any one + * console's types. + * + */ + +#ifndef PokemonAutomation_Pokemon_LegWalker_H +#define PokemonAutomation_Pokemon_LegWalker_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "Pokemon_Grid.h" +#include "Pokemon_LegTypes.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What one hold reported: nothing if it ran out, or which interrupt showed +// and how long into the hold. +struct HoldOutcome{ + size_t interrupt = 0; + Milliseconds elapsed{0}; +}; + +// The leg's bookkeeping, with the console side passed in, so it can be +// tested with scripted outcomes. `hold_watching` holds for the duration and +// reports the first interrupt seen; `clear` clears interrupt i; +// `detection_delay` is interrupt i's delay; `log` reports progress; `fail` +// throws, and is called after more than `max_interruptions`. +struct LegCalls{ + std::function(Milliseconds hold)> hold_watching; + std::function clear; + std::function detection_delay; + std::function name; + std::function log; + std::function fail; +}; +// Low-level leg execution using provided callback interface. +LegResult walk_leg_with(const LegSpec& leg, const LegCalls& calls, size_t max_interruptions); + + +// Shows a hold's frames to `watcher` without letting it stop the hold, and +// keeps whether it fired. A warp's fade can be over before the hold onto +// the warp ends, so a wait for it that starts after the hold sees nothing: +// the walk watches the hold with this, then waits on with the same watcher +// if it has not fired (FRLG 00.27, console B, 2026-11-09 01:41, the warp to +// CeruleanCity: the watch started 1.3 s into the hold and missed the fade). +class WatchAlong : public VisualInferenceCallback{ +public: + explicit WatchAlong(VisualInferenceCallback& watcher) + : VisualInferenceCallback("WatchAlong") + , m_watcher(watcher) + {} + + VisualInferenceCallback& watcher() const{ + return m_watcher; + } + bool fired() const{ + return m_fired.load(std::memory_order_acquire); + } + + virtual void make_overlays(VideoOverlaySet& items) const override{ + m_watcher.make_overlays(items); + } + using VisualInferenceCallback::process_frame; + virtual bool process_frame(const VideoSnapshot& frame) override{ + if (!fired() && m_watcher.process_frame(frame)){ + m_fired.store(true, std::memory_order_release); + } + return false; + } + +private: + VisualInferenceCallback& m_watcher; + std::atomic m_fired{false}; +}; + + +// Walks `leg`. Throws OperationFailedException if it is interrupted more +// than `max_interruptions` times. `hold_watchers` see every hold's frames +// too, after the interrupts' watchers, but stop nothing: a WatchAlong. +template +LegResult walk_leg( + ConsoleHandle& console, Context& context, + const std::type_identity_t>& mover, + const LegInterrupts& interrupts, + const LegSpec& leg, + size_t max_interruptions = 5, + const std::vector& hold_watchers = std::vector() +); + +template +LegResult walk_leg( + ConsoleHandle& console, Context& context, + const std::type_identity_t>& mover, + const LegInterrupts& interrupts, + const LegSpec& leg, + size_t max_interruptions, + const std::vector& hold_watchers +){ + auto hold_watching = [&](Milliseconds hold) -> std::optional{ + std::vector> watchers; + std::vector callbacks; + for (const auto& interrupt : interrupts){ + watchers.emplace_back(interrupt->make_watcher()); + callbacks.emplace_back(*watchers.back()); + } + for (WatchAlong* along : hold_watchers){ + callbacks.emplace_back(*along); + } + context.wait_for_all_requests(); + WallClock start = current_time(); + const int ret = run_until( + console, context, + [&](Context& context){ + start = current_time(); + mover(context, leg.direction, hold); + }, + callbacks + ); + if (ret < 0){ + return std::nullopt; + } + return HoldOutcome{(size_t)ret, std::chrono::duration_cast(current_time() - start)}; + }; + LegCalls calls; + calls.hold_watching = hold_watching; + calls.clear = [&](size_t index){ interrupts[index]->clear(console, context); }; + calls.detection_delay = [&](size_t index){ return interrupts[index]->detection_delay(); }; + calls.name = [&](size_t index){ return interrupts[index]->name(); }; + calls.log = [&](const std::string& message){ console.log(std::format("Leg: {}", message), COLOR_ORANGE); }; + calls.fail = [&](const std::string& message){ + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, message, console); + }; + return walk_leg_with(leg, calls, max_interruptions); +} + + +// After a leg: waits `watch` for an interrupt the last step set off, which +// shows after the hold has ended, and clears it. Returns how many it +// cleared. Throws OperationFailedException after `max_interruptions` in a +// row. +template +size_t clear_late_interrupts( + ConsoleHandle& console, Context& context, + const LegInterrupts& interrupts, + Milliseconds watch, + size_t max_interruptions = 5 +); + +template +size_t clear_late_interrupts( + ConsoleHandle& console, Context& context, + const LegInterrupts& interrupts, + Milliseconds watch, + size_t max_interruptions +){ + for (size_t count = 0; ; count++){ + std::vector> watchers; + std::vector callbacks; + for (const auto& interrupt : interrupts){ + watchers.emplace_back(interrupt->make_watcher()); + callbacks.emplace_back(*watchers.back()); + } + context.wait_for_all_requests(); + const int ret = wait_until(console, context, watch, callbacks); + if (ret < 0){ + return count; + } + if (count >= max_interruptions){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + std::format("Interrupted {} times in a row after a leg.", count), + console + ); + } + console.log(std::format("Leg: {} at the end of the leg.", interrupts[ret]->name()), COLOR_ORANGE); + interrupts[ret]->clear(console, context); + } +} + + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp new file mode 100644 index 0000000000..e676450cb0 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp @@ -0,0 +1,306 @@ +/* Leg Walker Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The leg walker's bookkeeping, with holds that report scripted + * interruptions instead of a console. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "Pokemon_LegWalker.h" +#include "Pokemon_LegWalker_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +using namespace std::chrono_literals; + +constexpr Milliseconds TILE = 267ms; +constexpr Milliseconds DELAY = 300ms; + +// Holds that report the scripted outcomes in order, then run out. +struct ScriptedLeg{ + std::deque> outcomes; + std::vector holds; + std::vector cleared; + + LegCalls calls(){ + LegCalls calls; + calls.hold_watching = [this](Milliseconds hold) -> std::optional{ + holds.push_back(hold); + if (outcomes.empty()){ + return std::nullopt; + } + std::optional outcome = outcomes.front(); + outcomes.pop_front(); + return outcome; + }; + calls.clear = [this](size_t index){ cleared.push_back(index); }; + calls.detection_delay = [](size_t){ return DELAY; }; + calls.name = [](size_t){ return std::string("a battle"); }; + calls.log = [](const std::string&){}; + calls.fail = [](const std::string& message){ throw std::runtime_error(message); }; + return calls; + } +}; + +// An interrupt set off by step `step`, seen DELAY after it ends. +HoldOutcome after_step(int step){ + return HoldOutcome{0, TILE * step + DELAY}; +} + + +UnitTestResult test_hold_times(){ + const LegSpec open{Direction::EAST, 4, false, TILE}; + const LegSpec wall{Direction::EAST, 4, true, TILE}; + if (leg_hold(open, 4) != TILE * 3 + TILE / 2){ + return std::format("Open leg: {}ms", leg_hold(open, 4).count()); + } + if (leg_hold(wall, 4) != TILE * 6){ + return std::format("Wall leg: {}ms", leg_hold(wall, 4).count()); + } + // A stall on step 2: a tile longer while the hold covers it. + LegSpec stalled = open; + stalled.stalled_steps = {2}; + if (leg_hold(stalled, 4) != TILE * 4 + TILE / 2 || leg_hold(stalled, 3) != TILE * 3 + TILE / 2){ + return std::format("Stalled leg: {}ms, {}ms", leg_hold(stalled, 4).count(), leg_hold(stalled, 3).count()); + } + if (leg_hold(stalled, 2) != TILE + TILE / 2){ + return std::format("Stalled leg past its stall: {}ms", leg_hold(stalled, 2).count()); + } + return true; +} + +UnitTestResult test_tiles_before_interrupt(){ + const LegSpec leg{Direction::EAST, 8, false, TILE}; + for (int step = 0; step <= 8; step++){ + for (Milliseconds jitter : {-100ms, 0ms, 100ms}){ + const int walked = tiles_before_interrupt(leg, TILE * step + DELAY + jitter, DELAY, 8); + if (walked != step){ + return std::format("Step {} seen {}ms off read as {}", step, jitter.count(), walked); + } + } + } + if (tiles_before_interrupt(leg, 50ms, DELAY, 8) != 0){ + return "An interrupt from before the leg should count no tiles."; + } + if (tiles_before_interrupt(leg, TILE * 20, DELAY, 3) != 3){ + return "Should not count more tiles than remain."; + } + return true; +} + +UnitTestResult test_wall_leg_walked_again(){ + ScriptedLeg script; + script.outcomes = {after_step(2)}; + const LegSpec leg{Direction::NORTH, 6, true, TILE}; + const LegResult result = walk_leg_with(leg, script.calls(), 5); + if (script.holds.size() != 2 || script.holds[1] != leg_hold(leg, 6)){ + return "Expected the whole leg held again."; + } + if (!result.exact || result.interruptions != 1 || script.cleared.size() != 1){ + return "Expected an exact result after one interruption."; + } + return true; +} + +UnitTestResult test_open_leg_rest_walked(){ + ScriptedLeg script; + script.outcomes = {after_step(2)}; + const LegSpec leg{Direction::NORTH, 6, false, TILE}; + const LegResult result = walk_leg_with(leg, script.calls(), 5); + if (script.holds.size() != 2 || script.holds[1] != leg_hold(leg, 4)){ + return "Expected the remaining 4 tiles held."; + } + if (result.exact){ + return "An interrupted open leg is an estimate."; + } + return true; +} + +UnitTestResult test_open_leg_interrupted_at_end(){ + ScriptedLeg script; + script.outcomes = {after_step(6)}; + const LegSpec leg{Direction::NORTH, 6, false, TILE}; + walk_leg_with(leg, script.calls(), 5); + if (script.holds.size() != 1){ + return "Nothing was left to walk after the last step."; + } + return true; +} + +// An open leg set to stop at an interrupt doesn't walk on from a guess; it +// says how far the timing puts the player, for the caller to look around. +UnitTestResult test_open_leg_stops(){ + ScriptedLeg script; + script.outcomes = {after_step(2)}; + LegSpec leg{Direction::NORTH, 6, false, TILE}; + leg.stop_on_interrupt = true; + const LegResult result = walk_leg_with(leg, script.calls(), 5); + if (script.holds.size() != 1 || !result.stopped || result.exact || script.cleared.size() != 1){ + return "Expected one hold, the interrupt cleared, and the leg stopped."; + } + if (result.tiles != 2){ + return std::format("Expected the timing to put the player 2 tiles in, got {}.", result.tiles); + } + return true; +} + +// Console B, 2026-11-01, run 16: held south into a sign, the leg to a wall +// was interrupted by its message 600ms into every hold, six times. +UnitTestResult test_wall_leg_blocked(){ + ScriptedLeg script; + script.outcomes = {HoldOutcome{0, 2200ms}, HoldOutcome{0, 600ms}, HoldOutcome{0, 600ms}}; + LegSpec leg{Direction::SOUTH, 23, true, TILE}; + leg.stop_if_blocked = true; + const LegResult result = walk_leg_with(leg, script.calls(), 5); + if (script.holds.size() != 2 || !result.stopped){ + return std::format("Expected the leg stopped after 2 holds, got {}.", script.holds.size()); + } + return true; +} + +UnitTestResult test_too_many_interruptions(){ + ScriptedLeg script; + for (int c = 0; c < 4; c++){ + script.outcomes.push_back(after_step(0)); + } + const LegSpec leg{Direction::NORTH, 6, true, TILE}; + try{ + walk_leg_with(leg, script.calls(), 3); + }catch (std::runtime_error&){ + return true; + } + return "Expected to give up after 3 interruptions."; +} + +// A watcher that fires on the frame numbered `fires_on` (from 1). +class CountingWatcher : public VisualInferenceCallback{ +public: + explicit CountingWatcher(int fires_on) + : VisualInferenceCallback("CountingWatcher") + , m_fires_on(fires_on) + {} + int frames() const{ + return m_frames; + } + virtual void make_overlays(VideoOverlaySet&) const override{} + using VisualInferenceCallback::process_frame; + virtual bool process_frame(const VideoSnapshot&) override{ + return ++m_frames == m_fires_on; + } + +private: + int m_fires_on; + int m_frames = 0; +}; + +UnitTestResult test_watch_along(){ + CountingWatcher watcher(3); + WatchAlong along(watcher); + for (int c = 0; c < 5; c++){ + if (along.process_frame(VideoSnapshot())){ + return std::format("WatchAlong stopped the hold on frame {}.", c + 1); + } + if (along.fired() != (c >= 2)){ + return std::format("After frame {}, expected fired() {}.", c + 1, c >= 2); + } + } + if (watcher.frames() != 3){ + return std::format("Expected the watcher to see 3 frames, up to its firing; it saw {}.", watcher.frames()); + } + return true; +} + + +struct LegWalkerInput{ + std::string name; + UnitTestResult (*test)(); +}; + +struct LegWalkerExpectation{ + std::string_view description; +}; + +struct LegWalkerTestCase{ + LegWalkerInput input; + LegWalkerExpectation expectation; +}; + +class Test_LegWalker : public UnitTest{ +public: + explicit Test_LegWalker(LegWalkerTestCase scenario) + : UnitTest(std::format("Pokemon::LegWalker - {}", scenario.input.name)) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.input.test(); + } + +private: + LegWalkerTestCase m_scenario; +}; + +const LegWalkerTestCase LEG_WALKER_CASES[] = { + { + .input = {.name = "hold times", .test = test_hold_times}, + .expectation = {.description = "verifies open and wall leg hold durations"}, + }, + { + .input = {.name = "tiles before an interrupt", .test = test_tiles_before_interrupt}, + .expectation = {.description = "computes traversed tiles before an interrupt occurred"}, + }, + { + .input = {.name = "a wall leg is walked again", .test = test_wall_leg_walked_again}, + .expectation = {.description = "re-executes entire wall leg following an interrupt"}, + }, + { + .input = {.name = "an open leg walks the rest", .test = test_open_leg_rest_walked}, + .expectation = {.description = "walks only the remaining tiles on an open leg"}, + }, + { + .input = {.name = "an open leg interrupted at its end", .test = test_open_leg_interrupted_at_end}, + .expectation = {.description = "does not re-walk an open leg interrupted at its final tile"}, + }, + { + .input = {.name = "gives up after too many interruptions", .test = test_too_many_interruptions}, + .expectation = {.description = "throws when interrupt count exceeds limit"}, + }, + { + .input = {.name = "an open leg stops at an interrupt", .test = test_open_leg_stops}, + .expectation = {.description = "aborts remaining movement when stop_on_interrupt is set"}, + }, + { + .input = {.name = "a wall leg blocked by a sign stops", .test = test_wall_leg_blocked}, + .expectation = {.description = "aborts wall movement when blocked prematurely repeatedly"}, + }, + { + .input = {.name = "a watcher along a hold never stops it", .test = test_watch_along}, + .expectation = {.description = "WatchAlong keeps its watcher's firing and returns false"}, + }, +}; + +} // namespace + + +void add_tests_LegWalker(UnitTestDatabase& database){ + for (const auto& scenario : LEG_WALKER_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.h new file mode 100644 index 0000000000..9f1f4432d3 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.h @@ -0,0 +1,23 @@ +/* Leg Walker Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_LegWalker_Tests_H +#define PokemonAutomation_Pokemon_LegWalker_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers leg walker execution unit tests. +void add_tests_LegWalker(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp new file mode 100644 index 0000000000..6fde755d24 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp @@ -0,0 +1,586 @@ +/* Map Data + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon_RuntimeMap.h" +#include "Pokemon_MapData.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +constexpr std::pair GLYPHS[] = { + {'#', TileKind::WALL}, + {'.', TileKind::OPEN}, + {'~', TileKind::TALL_GRASS}, + {'w', TileKind::WATER}, + {'^', TileKind::LEDGE_NORTH}, + {'v', TileKind::LEDGE_SOUTH}, + {'<', TileKind::LEDGE_WEST}, + {'>', TileKind::LEDGE_EAST}, + {'D', TileKind::DOOR}, + {'S', TileKind::SIGN}, + {' ', TileKind::OUTSIDE}, + {'8', TileKind::CLOSED_NORTH}, + {'2', TileKind::CLOSED_SOUTH}, + {'4', TileKind::CLOSED_WEST}, + {'6', TileKind::CLOSED_EAST}, +}; + +constexpr std::pair WARP_ENTRIES[] = { + {"walk_into", WarpEntry::WALK_INTO}, + {"step_on", WarpEntry::STEP_ON}, + {"cave_entrance", WarpEntry::CAVE_ENTRANCE}, + {"walk_north", WarpEntry::WALK_NORTH}, + {"walk_south", WarpEntry::WALK_SOUTH}, + {"walk_west", WarpEntry::WALK_WEST}, + {"walk_east", WarpEntry::WALK_EAST}, +}; + +} // namespace + +std::optional tile_from_glyph(char glyph){ + for (const auto& [known, tile] : GLYPHS){ + if (known == glyph){ + return tile; + } + } + return std::nullopt; +} + +char glyph_of(TileKind tile){ + for (const auto& [glyph, known] : GLYPHS){ + if (known == tile){ + return glyph; + } + } + return '?'; +} + + +namespace{ + +// The readers take `where`, the source and the path to the object being +// read (e.g. "Maps/TestTown.json: warps[2]."), and name the field in what +// they throw. + +const JsonObject& as_object(const JsonValue& value, const std::string& where){ + const JsonObject* object = value.to_object(); + if (object == nullptr){ + throw ParseException(std::format("{} is not a JSON object.", where)); + } + return *object; +} + +const JsonValue& read_field(const JsonObject& object, const std::string& key, const std::string& where){ + const JsonValue* value = object.get_value(key); + if (value == nullptr){ + throw ParseException(std::format("{}{} is missing.", where, key)); + } + return *value; +} + +int read_int(const JsonObject& object, const std::string& key, const std::string& where){ + const JsonValue& value = read_field(object, key, where); + if (!value.is_integer()){ + throw ParseException(std::format("{}{} is not an integer.", where, key)); + } + return (int)value.to_integer_default(); +} + +std::string read_string(const JsonObject& object, const std::string& key, const std::string& where){ + const std::string* text = read_field(object, key, where).to_string(); + if (text == nullptr){ + throw ParseException(std::format("{}{} is not a string.", where, key)); + } + return *text; +} + +// The boolean `key`, or `fallback` when the map leaves it out. +bool optional_bool(const JsonObject& object, const std::string& key, bool fallback, const std::string& where){ + const JsonValue* value = object.get_value(key); + if (value == nullptr){ + return fallback; + } + if (!value->is_boolean()){ + throw ParseException(std::format("{}{} is not true or false.", where, key)); + } + return value->to_boolean_default(fallback); +} + +// The string `key`, or nothing when the map leaves it out. +std::optional optional_string(const JsonObject& object, const std::string& key, const std::string& where){ + if (object.get_value(key) == nullptr){ + return std::nullopt; + } + return read_string(object, key, where); +} + +TilePos read_pos(const JsonObject& object, const std::string& where){ + return TilePos{read_int(object, "x", where), read_int(object, "y", where)}; +} + +Direction parse_direction(const std::string& name, const std::string& where){ + for (Direction candidate : ALL_DIRECTIONS){ + if (name == direction_name(candidate)){ + return candidate; + } + } + throw ParseException(std::format("{} \"{}\" is not north, east, south or west.", where, name)); +} + +Direction read_direction(const JsonObject& object, const std::string& key, const std::string& where){ + return parse_direction(read_string(object, key, where), std::format("{}{}", where, key)); +} + +// The list `key`, or nothing when the map leaves it out. +const JsonArray* optional_array(const JsonObject& object, const std::string& key, const std::string& where){ + const JsonValue* value = object.get_value(key); + if (value == nullptr){ + return nullptr; + } + const JsonArray* array = value->to_array(); + if (array == nullptr){ + throw ParseException(std::format("{}{} is not an array.", where, key)); + } + return array; +} + +const JsonObject* optional_object(const JsonObject& object, const std::string& key, const std::string& where){ + const JsonValue* value = object.get_value(key); + if (value == nullptr){ + return nullptr; + } + return &as_object(*value, std::format("{}{}", where, key)); +} + +template +std::vector read_list( + const JsonObject& object, const std::string& key, const std::string& where, + Item (*read_item)(const JsonObject& object, const std::string& where) +){ + std::vector items; + const JsonArray* array = optional_array(object, key, where); + if (array == nullptr){ + return items; + } + for (size_t c = 0; c < array->size(); c++){ + const std::string item_where = std::format("{}{}[{}]", where, key, c); + items.push_back(read_item(as_object((*array)[c], item_where), std::format("{}.", item_where))); + } + return items; +} + + +MapSource read_source(const JsonObject& root, const std::string& where){ + // Named, since GCC warns of a reference returned for a temporary path. + const std::string key = "source"; + const std::string path = std::format("{}{}", where, key); + const JsonObject& object = as_object(read_field(root, key, where), path); + const std::string source_where = std::format("{}.", path); + MapSource source; + source.decomp_file = read_string(object, "decomp_file", source_where); + source.revision = read_string(object, "revision", source_where); + source.date = read_string(object, "date", source_where); + return source; +} + +std::optional read_world(const JsonObject& root, const std::string& where){ + const JsonObject* object = optional_object(root, "world", where); + if (object == nullptr){ + return std::nullopt; + } + const std::string world_where = std::format("{}world.", where); + return MapWorld{ + .name = read_string(*object, "name", world_where), + .offset = read_pos(*object, world_where), + }; +} + +// Rows of glyphs, all as wide as the first. +Grid read_tiles(const JsonObject& root, const std::string& where){ + const std::string key = "tiles"; + const JsonValue& value = read_field(root, key, where); + const JsonArray* rows = value.to_array(); + if (rows == nullptr){ + throw ParseException(std::format("{}{} is not an array.", where, key)); + } + if (rows->empty()){ + throw ParseException(std::format("{}{} has no rows.", where, key)); + } + const std::string* first = (*rows)[0].to_string(); + const size_t width = first == nullptr ? 0 : first->size(); + if (width == 0){ + throw ParseException(std::format("{}{}[0] is not a string of glyphs.", where, key)); + } + Grid grid{(int)width, (int)rows->size(), {}}; + for (size_t y = 0; y < rows->size(); y++){ + const std::string row_where = std::format("{}{}[{}]", where, key, y); + const std::string* row = (*rows)[y].to_string(); + if (row == nullptr || row->size() != width){ + throw ParseException(std::format("{} is not a string of {} glyphs.", row_where, width)); + } + for (size_t x = 0; x < width; x++){ + const std::optional tile = tile_from_glyph((*row)[x]); + if (!tile){ + throw ParseException(std::format( + "{} has unknown glyph '{}' at {}.", row_where, (*row)[x], to_string(TilePos{(int)x, (int)y}) + )); + } + grid.cells.push_back(*tile); + } + } + return grid; +} + +TilePos read_pair(const JsonValue& value, const std::string& where){ + const JsonArray* pair = value.to_array(); + if (pair == nullptr || pair->size() != 2 || !(*pair)[0].is_integer() || !(*pair)[1].is_integer()){ + throw ParseException(std::format("{} is not [x, y].", where)); + } + return TilePos{(int)(*pair)[0].to_integer_default(), (int)(*pair)[1].to_integer_default()}; +} + +// Rows of hex digits, one per tile. +std::optional> read_elevation(const JsonObject& root, const Grid& tiles, const std::string& where){ + const std::string key = "elevation"; + const JsonArray* rows = optional_array(root, key, where); + if (rows == nullptr){ + return std::nullopt; + } + if ((int)rows->size() != tiles.height){ + throw ParseException(std::format("{}{} has {} rows, not the tiles' {}.", where, key, rows->size(), tiles.height)); + } + Grid grid{tiles.width, tiles.height, {}}; + for (size_t y = 0; y < rows->size(); y++){ + const std::string row_where = std::format("{}{}[{}]", where, key, y); + const std::string* row = (*rows)[y].to_string(); + if (row == nullptr || (int)row->size() != tiles.width){ + throw ParseException(std::format("{} is not a string of {} hex digits.", row_where, tiles.width)); + } + for (size_t x = 0; x < row->size(); x++){ + const char digit = (*row)[x]; + const size_t value = std::string_view("0123456789abcdef").find((char)std::tolower((unsigned char)digit)); + if (value == std::string_view::npos){ + throw ParseException(std::format("{} has '{}' at {}, not a hex digit.", row_where, digit, to_string(TilePos{(int)x, (int)y}))); + } + grid.cells.push_back((uint8_t)value); + } + } + return grid; +} + +// Each flag set is a list of flag names. +std::map> read_flag_sets(const JsonObject& root, const std::string& where){ + std::map> sets; + const JsonObject* object = optional_object(root, "flag_sets", where); + if (object == nullptr){ + return sets; + } + for (const auto& [name, value] : *object){ + const std::string set_where = std::format("{}flag_sets.{}", where, name); + const JsonArray* flags = value.to_array(); + if (flags == nullptr){ + throw ParseException(std::format("{} is not a list of flags.", set_where)); + } + std::set& set = sets[name]; + for (size_t c = 0; c < flags->size(); c++){ + const std::string* flag = (*flags)[c].to_string(); + if (flag == nullptr){ + throw ParseException(std::format("{}[{}] is not a string.", set_where, c)); + } + set.insert(*flag); + } + } + return sets; +} + +std::map read_points(const JsonObject& root, const std::string& where){ + std::map points; + const JsonObject* object = optional_object(root, "points", where); + if (object == nullptr){ + return points; + } + for (const auto& [name, value] : *object){ + points[name] = read_pair(value, std::format("{}points.{}", where, name)); + } + return points; +} + +// Each region is a non-empty list of [x, y]. +std::map> read_regions(const JsonObject& root, const std::string& where){ + std::map> regions; + const JsonObject* object = optional_object(root, "regions", where); + if (object == nullptr){ + return regions; + } + for (const auto& [name, value] : *object){ + const std::string region_where = std::format("{}regions.{}", where, name); + const JsonArray* tiles = value.to_array(); + if (tiles == nullptr || tiles->empty()){ + throw ParseException(std::format("{} is not a non-empty list of [x, y].", region_where)); + } + std::vector& region = regions[name]; + for (size_t c = 0; c < tiles->size(); c++){ + region.push_back(read_pair((*tiles)[c], std::format("{}[{}]", region_where, c))); + } + } + return regions; +} + +WarpEntry read_warp_entry(const JsonObject& object, const std::string& where){ + const std::optional name = optional_string(object, "enter", where); + if (!name){ + return WarpEntry::WALK_INTO; + } + for (const auto& [known, entry] : WARP_ENTRIES){ + if (*name == known){ + return entry; + } + } + throw ParseException(std::format( + "{}enter \"{}\" is not walk_into, step_on, cave_entrance or walk_.", where, *name + )); +} + +// `to_map` and `to_point` come together, or neither does. +MapWarp read_warp(const JsonObject& object, const std::string& where){ + MapWarp warp; + const TilePos pos = read_pos(object, where); + warp.x = pos.x; + warp.y = pos.y; + warp.enter = read_warp_entry(object, where); + const bool has_map = object.get_value("to_map") != nullptr; + const bool has_point = object.get_value("to_point") != nullptr; + if (has_map != has_point){ + throw ParseException(std::format("{}{} is missing.", where, has_map ? "to_point" : "to_map")); + } + if (has_map){ + warp.to = WarpDestination{ + .map = read_string(object, "to_map", where), + .point = read_string(object, "to_point", where), + }; + } + return warp; +} + +ObjectKind read_object_kind(const JsonObject& object, const std::string& where){ + const std::string kind = read_string(object, "kind", where); + if (kind == "npc"){ + return ObjectKind::NPC; + } + if (kind == "item"){ + return ObjectKind::ITEM; + } + if (kind == "sign"){ + return ObjectKind::SIGN; + } + throw ParseException(std::format("{}kind \"{}\" is not npc, item or sign.", where, kind)); +} + +TileBox read_box(const JsonObject& object, const std::string& where){ + TileBox box; + box.x0 = read_int(object, "x0", where); + box.y0 = read_int(object, "y0", where); + box.x1 = read_int(object, "x1", where); + box.y1 = read_int(object, "y1", where); + if (box.x0 > box.x1 || box.y0 > box.y1){ + throw ParseException(std::format("{} is not a box (x0 <= x1, y0 <= y1).", where.substr(0, where.size() - 1))); + } + return box; +} + +// `looks` defaults to the trainer's facing. +MapTrainer read_trainer(const JsonObject& object, const std::optional& facing, const std::string& where){ + MapTrainer trainer; + trainer.sight = read_int(object, "sight", where); + if (trainer.sight < 1){ + throw ParseException(std::format("{}sight {} is not at least 1.", where, trainer.sight)); + } + const JsonArray* looks = optional_array(object, "looks", where); + if (looks == nullptr){ + if (!facing){ + throw ParseException(std::format("{}looks is missing, and the object has no facing.", where)); + } + trainer.looks.push_back(*facing); + return trainer; + } + for (size_t c = 0; c < looks->size(); c++){ + const std::string item_where = std::format("{}looks[{}]", where, c); + const std::string* name = (*looks)[c].to_string(); + if (name == nullptr){ + throw ParseException(std::format("{} is not a string.", item_where)); + } + trainer.looks.push_back(parse_direction(*name, item_where)); + } + return trainer; +} + +MapObject read_object(const JsonObject& object, const std::string& where){ + MapObject map_object; + map_object.name = read_string(object, "name", where); + map_object.kind = read_object_kind(object, where); + const TilePos pos = read_pos(object, where); + map_object.x = pos.x; + map_object.y = pos.y; + if (object.get_value("facing") != nullptr){ + map_object.facing = read_direction(object, "facing", where); + } + if (const JsonObject* wander = optional_object(object, "wander", where)){ + map_object.wander = read_box(*wander, std::format("{}wander.", where)); + } + if (const JsonObject* trainer = optional_object(object, "trainer", where)){ + map_object.trainer = read_trainer(*trainer, map_object.facing, std::format("{}trainer.", where)); + } + map_object.hide_flag = optional_string(object, "hide_flag", where); + return map_object; +} + +MapTrigger read_trigger(const JsonObject& object, const std::string& where){ + MapTrigger trigger; + trigger.name = read_string(object, "name", where); + // Named, since GCC warns of a reference returned for a temporary path. + const std::string key = "box"; + trigger.box = read_box(as_object(read_field(object, key, where), std::format("{}{}", where, key)), std::format("{}{}.", where, key)); + trigger.when = optional_string(object, "when", where); + return trigger; +} + +MapConnection read_connection(const JsonObject& object, const std::string& where){ + MapConnection connection; + connection.side = read_direction(object, "side", where); + connection.to_map = read_string(object, "to_map", where); + connection.offset = read_int(object, "offset", where); + return connection; +} + +MapPatch read_patch(const JsonObject& object, const std::string& where){ + MapPatch patch; + const TilePos pos = read_pos(object, where); + patch.x = pos.x; + patch.y = pos.y; + const std::string glyph = read_string(object, "glyph", where); + const std::optional tile = glyph.size() == 1 ? tile_from_glyph(glyph[0]) : std::nullopt; + if (!tile){ + throw ParseException(std::format("{}glyph \"{}\" is not a tile glyph.", where, glyph)); + } + patch.glyph = *tile; + patch.measured_by = read_string(object, "measured_by", where); + return patch; +} + + +void check_inside(const Grid& tiles, const TilePos& pos, const std::string& where){ + if (!tiles.contains(pos)){ + throw ParseException(std::format("{} {} is outside the {}x{} map.", where, to_string(pos), tiles.width, tiles.height)); + } +} + +void check_box_inside(const Grid& tiles, const TileBox& box, const std::string& where){ + check_inside(tiles, TilePos{box.x0, box.y0}, where); + check_inside(tiles, TilePos{box.x1, box.y1}, where); +} + +// Everything with a place on the map has it inside the tiles. +void check_places(const MapData& map, const std::string& where){ + for (const auto& [name, pos] : map.points){ + check_inside(map.tiles, pos, std::format("{}points.{}", where, name)); + } + for (const auto& [name, region] : map.regions){ + for (size_t c = 0; c < region.size(); c++){ + check_inside(map.tiles, region[c], std::format("{}regions.{}[{}]", where, name, c)); + } + } + for (size_t c = 0; c < map.warps.size(); c++){ + check_inside(map.tiles, TilePos{map.warps[c].x, map.warps[c].y}, std::format("{}warps[{}]", where, c)); + } + for (size_t c = 0; c < map.objects.size(); c++){ + const MapObject& object = map.objects[c]; + check_inside(map.tiles, TilePos{object.x, object.y}, std::format("{}objects[{}]", where, c)); + if (object.wander){ + check_box_inside(map.tiles, *object.wander, std::format("{}objects[{}].wander", where, c)); + } + } + for (size_t c = 0; c < map.triggers.size(); c++){ + check_box_inside(map.tiles, map.triggers[c].box, std::format("{}triggers[{}].box", where, c)); + } + for (size_t c = 0; c < map.patches.size(); c++){ + check_inside(map.tiles, TilePos{map.patches[c].x, map.patches[c].y}, std::format("{}patches[{}]", where, c)); + } +} + +} // namespace + + +MapData parse_map(const JsonValue& json, const std::string& source_name){ + const JsonValue normalized = normalize_runtime_map(json, source_name); + const JsonObject& root = as_object(normalized, source_name); + const std::string where = std::format("{}: ", source_name); + MapData map; + map.name = read_string(root, "name", where); + map.source = read_source(root, where); + map.world = read_world(root, where); + map.allow_running = optional_bool(root, "allow_running", true, where); + map.tiles = read_tiles(root, where); + map.elevation = read_elevation(root, map.tiles, where); + map.points = read_points(root, where); + map.regions = read_regions(root, where); + map.warps = read_list(root, "warps", where, read_warp); + map.objects = read_list(root, "objects", where, read_object); + map.triggers = read_list(root, "triggers", where, read_trigger); + map.flag_sets = read_flag_sets(root, where); + map.connections = read_list(root, "connections", where, read_connection); + map.patches = read_list(root, "patches", where, read_patch); + check_places(map, where); + for (const MapPatch& patch : map.patches){ + cell_at(TilePos{patch.x, patch.y}, map.tiles) = patch.glyph; + } + return map; +} + +const MapWarp* warp_at(const MapData& map, const TilePos& pos){ + for (const MapWarp& warp : map.warps){ + if (warp.x == pos.x && warp.y == pos.y){ + return &warp; + } + } + return nullptr; +} + +size_t tiles_to_door(const Grid& tiles, const TilePos& from, Direction direction, size_t max_tiles){ + TilePos at = from; + size_t count = 0; + while (count < max_tiles){ + const TilePos next = at.next(direction); + if (!tiles.contains(next)){ + break; + } + count++; + const TileKind kind = tiles.at(next); + if (kind == TileKind::DOOR || kind == TileKind::WALL || kind == TileKind::OUTSIDE){ + break; + } + at = next; + } + return count; +} + +size_t tiles_to_door(const MapData& map, const TilePos& from, Direction direction, size_t max_tiles){ + return tiles_to_door(map.tiles, from, direction, max_tiles); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h new file mode 100644 index 0000000000..6b4d923fbf --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h @@ -0,0 +1,103 @@ +/* Map Data + * + * From: https://github.com/PokemonAutomation/ + * + * A map as a navigation program sees it, read from the one JSON schema the + * tile games (BDSP, FRLG) share: the tiles as rows of glyphs, the named + * points and regions routes start and end at, the warps, the objects + * standing on the map, the scenes that start on stepping somewhere, the + * connections to neighbouring maps, and patches that put tiles measured on + * the console on top of the decompilation's data. + * + * { + * "name": "TestTown", + * "source": {"decomp_file": "data/maps/TestTown/map.json", "revision": "abc123", "date": "2026-10-31"}, + * "world": {"name": "Sinnoh", "x": 96, "y": 864}, + * "allow_running": false, // left out: true + * "tiles": ["####", "#..~", ...], // rows of glyphs, all the same length + * "elevation": ["3333", "3300", ...], // one hex digit per tile + * "points": {"door": [1, 2], ...}, + * "regions": {"lawn": [[1, 1], [2, 1]], ...}, + * "warps": [{"x": 1, "y": 2, "enter": "walk_into", "to_map": "TestHouse", "to_point": "exit"}, ...], + * "objects": [{"name": "mom", "kind": "npc", "x": 2, "y": 1, + * "facing": "south", "wander": {"x0": 1, "y0": 1, "x1": 2, "y1": 2}, + * "trainer": {"sight": 4, "looks": ["south", "west"]}, + * "hide_flag": "FLAG_HIDE_MOM"}, ...], + * "triggers": [{"name": "mom_warning", "box": {"x0": 1, "y0": 2, "x1": 1, "y1": 2}, "when": "00.01"}, ...], + * "flag_sets": {"after_00.01": ["FLAG_HIDE_MOM", ...], ...}, + * "connections": [{"side": "east", "to_map": "Route 1", "offset": 0}, ...], + * "patches": [{"x": 2, "y": 1, "glyph": "#", "measured_by": "run 3, 2026-10-30"}, ...] + * } + * + * `name`, `source` and `tiles` are required; everything else may be left + * out. Which game's planner reads these maps, and how, is the game's + * business. + * + */ + +#ifndef PokemonAutomation_Pokemon_MapData_H +#define PokemonAutomation_Pokemon_MapData_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon_Grid.h" +#include "Pokemon_MapFeatures.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Complete map dataset including dimensions, collision tiles, warps, and objects. +struct MapData{ + std::string name; + MapSource source; + std::optional world; + // Whether the game lets the player run here. FRLG's indoor maps, such as + // the Pokemon Centers, don't (pokefirered's map header allow_running): + // B held there still walks. + bool allow_running = true; + // With the patches applied. + Grid tiles; + // The same size as `tiles`. FRLG reads a map without it as all ground + // (elevation 3); what the values mean is the game's business. + std::optional> elevation; + std::map points; + // Named sets of tiles, in the order the map lists them. + std::map> regions; + std::vector warps; + std::vector objects; + std::vector triggers; + // Flags set together, by name (e.g. "after_hall_of_fame"). + std::map> flag_sets; + std::vector connections; + std::vector patches; +}; + +// Reads legacy/unmarked v1 or compact pokesim-runtime-map/2 JSON. +// Both games use this entry point; `source_name` names it in errors. +// Throws ParseException, naming the source and the JSON path (e.g. +// "Maps/TestTown.json: warps[2].x is missing."), when a field is missing, +// doesn't fit the schema, or places something outside the tiles. +MapData parse_map(const JsonValue& json, const std::string& source_name); + +// The warp on `pos`, or nullptr if there is none. +const MapWarp* warp_at(const MapData& map, const TilePos& pos); + +// Counts the number of tiles along `direction` starting from `from` until reaching +// a DOOR tile, an impassable tile (WALL, OUTSIDE), or the edge of the grid. +// Used by AutoStory walkers to bound holds into door warps based on distance. +size_t tiles_to_door(const Grid& tiles, const TilePos& from, Direction direction, size_t max_tiles = 50); + +// Convenience overload that queries map.tiles. +size_t tiles_to_door(const MapData& map, const TilePos& from, Direction direction, size_t max_tiles = 50); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp new file mode 100644 index 0000000000..25c3ecfcb8 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp @@ -0,0 +1,526 @@ +/* Map Data Tests + * + * From: https://github.com/PokemonAutomation/ + * + * parse_map() on a small synthetic map: the good map, a map with only the + * required fields, and one row per error class; and on a map shaped like + * each game's (BDSP, FRLG), for the fields only that game writes today. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_MapData.h" +#include "Pokemon_MapData_Tests.h" +#include "Pokemon_NavigationTestMaps.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +const std::string VALID_MAP = R"({ + "name": "TestTown", + "source": {"decomp_file": "data/maps/TestTown/map.json", "revision": "abc123", "date": "2026-10-31"}, + "tiles": ["####", "#..~", "#D.S", "w^v#"], + "points": {"door": [1, 2], "sign": [3, 2]}, + "warps": [{"x": 1, "y": 2, "to_map": "TestHouse", "to_point": "exit"}], + "objects": [ + {"name": "mom", "kind": "npc", "x": 2, "y": 1, "facing": "south", "wander": {"x0": 1, "y0": 1, "x1": 2, "y1": 2}}, + {"name": "potion", "kind": "item", "x": 2, "y": 2} + ], + "connections": [{"side": "east", "to_map": "Route 1", "offset": 0}], + "patches": [{"x": 2, "y": 1, "glyph": "#", "measured_by": "run 3, 2026-10-30"}] +})"; + +// A map shaped like BDSP's: on a world grid, with tiles off the game's +// map, a region, a warp tile stood on, trainers, a person the story hides +// and scene triggers. +const std::string BDSP_MAP = R"({ + "name": "Route 201", + "source": {"decomp_file": "pret/pokediamond: land_data narc_0000.bin", "revision": "default branch", "date": "2026-11-01"}, + "world": {"name": "Sinnoh", "x": 96, "y": 839}, + "tiles": [" ###", " #..#", "#.~..", "#..v#"], + "points": {"save_spot": [2, 1]}, + "regions": {"lawn": [[3, 2], [1, 2], [1, 3]]}, + "warps": [{"x": 4, "y": 2, "enter": "step_on"}], + "objects": [ + {"name": "youngster_tristan", "kind": "npc", "x": 3, "y": 1, "facing": "west", "trainer": {"sight": 2}}, + {"name": "lass_natalie", "kind": "npc", "x": 1, "y": 3, "facing": "north", "trainer": {"sight": 3, "looks": ["north", "east"]}}, + {"name": "rowan", "kind": "npc", "x": 2, "y": 3, "hide_flag": "story_after_00.03"} + ], + "triggers": [ + {"name": "barry_warning", "box": {"x0": 2, "y0": 1, "x1": 3, "y1": 1}, "when": "00.02"}, + {"name": "border_sign", "box": {"x0": 1, "y0": 2, "x1": 1, "y1": 2}} + ] +})"; + +// A map shaped like FRLG's: elevations, one-sided walls, warps of every +// entry to per-warp points (one to a map not loaded), a person hidden by +// an event flag, and a flag set. +const std::string FRLG_MAP = R"({ + "name": "CeruleanCave_1F", + "source": {"decomp_file": "data/maps/CeruleanCave_1F/map.json", "revision": "ce6406d8c2ea", "date": "2026-11-01"}, + "allow_running": false, + "width": 4, + "tiles": ["#..#", "8.2#", "4.6."], + "elevation": ["3303", "3F03", "0a33"], + "points": {"warp_0": [1, 0]}, + "warps": [ + {"x": 1, "y": 0, "enter": "cave_entrance", "to_map": "CeruleanCity", "to_point": "warp_6"}, + {"x": 2, "y": 0, "enter": "step_on"}, + {"x": 1, "y": 1, "enter": "walk_north", "to_map": "CeruleanCave_2F", "to_point": "warp_0"}, + {"x": 2, "y": 1, "enter": "walk_south", "to_map": "CeruleanCave_2F", "to_point": "warp_1"}, + {"x": 1, "y": 2, "enter": "walk_west", "to_map": "CeruleanCave_2F", "to_point": "warp_2"}, + {"x": 3, "y": 2, "enter": "walk_east", "to_map": "CeruleanCave_2F", "to_point": "warp_3"} + ], + "objects": [ + {"name": "cooltrainer_m_1", "kind": "npc", "x": 1, "y": 1, "hide_flag": "FLAG_HIDE_CERULEAN_CAVE_GUARD", + "wander": {"x0": 1, "y0": 1, "x1": 2, "y1": 1}} + ], + "flag_sets": {"after_hall_of_fame": ["FLAG_B", "FLAG_HIDE_CERULEAN_CAVE_GUARD", "FLAG_B"]} +})"; + +// `base` with `find` replaced by `replacement`; empty when `find` is not +// in it. +std::string edited(const std::string& base, const std::string& find, const std::string& replacement){ + std::string json = base; + const size_t at = json.find(find); + if (at == std::string::npos){ + return ""; + } + return json.replace(at, find.size(), replacement); +} +std::string edited(const std::string& find, const std::string& replacement){ + return edited(VALID_MAP, find, replacement); +} + +// The ParseException that parsing `json` throws, or empty if it doesn't. +std::string parse_error(const std::string& json){ + try{ + parse_map(parse_json(json), "Test.json"); + }catch (ParseException& e){ + return e.message(); + } + return ""; +} + +// Whether `text` contains every one of `parts`. +bool mentions(const std::string& text, const std::vector& parts){ + for (const std::string& part : parts){ + if (text.find(part) == std::string::npos){ + return false; + } + } + return true; +} + + +UnitTestResult test_valid_map(){ + const MapData map = parse_map(parse_json(VALID_MAP), "Test.json"); + if (map.name != "TestTown" || map.source.decomp_file != "data/maps/TestTown/map.json" + || map.source.revision != "abc123" || map.source.date != "2026-10-31" + ){ + return "Wrong name or source."; + } + if (map.tiles.width != 4 || map.tiles.height != 4 + || map.tiles.at({3, 1}) != TileKind::TALL_GRASS || map.tiles.at({1, 2}) != TileKind::DOOR + || map.tiles.at({3, 2}) != TileKind::SIGN || map.tiles.at({0, 3}) != TileKind::WATER + || map.tiles.at({1, 3}) != TileKind::LEDGE_NORTH || map.tiles.at({2, 3}) != TileKind::LEDGE_SOUTH + ){ + return "Wrong tiles."; + } + if (map.tiles.at({2, 1}) != TileKind::WALL || map.patches.size() != 1 || map.patches[0].measured_by != "run 3, 2026-10-30"){ + return "The patch should have made (2, 1) a wall."; + } + if (map.points.size() != 2 || map.points.at("door") != TilePos{1, 2} || map.points.at("sign") != TilePos{3, 2}){ + return "Wrong points."; + } + if (map.warps.size() != 1 || map.warps[0].x != 1 || map.warps[0].y != 2 + || map.warps[0].enter != WarpEntry::WALK_INTO || !map.warps[0].to + || map.warps[0].to->map != "TestHouse" || map.warps[0].to->point != "exit" + ){ + return "Wrong warps."; + } + if (map.objects.size() != 2 || map.objects[0].name != "mom" || map.objects[0].kind != ObjectKind::NPC + || map.objects[0].facing != Direction::SOUTH || !map.objects[0].wander + || map.objects[0].wander->x0 != 1 || map.objects[0].wander->y1 != 2 + || map.objects[1].kind != ObjectKind::ITEM || map.objects[1].facing || map.objects[1].wander + ){ + return "Wrong objects."; + } + if (map.connections.size() != 1 || map.connections[0].side != Direction::EAST + || map.connections[0].to_map != "Route 1" || map.connections[0].offset != 0 + ){ + return "Wrong connections."; + } + return true; +} + +UnitTestResult test_lists_may_be_left_out(){ + const MapData map = parse_map(parse_json(R"({ + "name": "Cave", + "source": {"decomp_file": "f", "revision": "r", "date": "d"}, + "tiles": ["#.#"] + })"), "Cave.json"); + if (map.tiles.width != 3 || map.tiles.height != 1 || map.world || !map.allow_running || map.elevation + || !map.points.empty() || !map.regions.empty() || !map.warps.empty() || !map.objects.empty() + || !map.triggers.empty() || !map.flag_sets.empty() || !map.connections.empty() || !map.patches.empty() + ){ + return "Expected a 3x1 map with nothing on it, where the player may run."; + } + return true; +} + +UnitTestResult test_glyphs_round_trip(){ + for (char glyph : std::string("#.~wv^<>DS 8246")){ + const std::optional tile = tile_from_glyph(glyph); + if (!tile || glyph_of(*tile) != glyph){ + return std::format("Glyph '{}' does not round-trip.", glyph); + } + } + if (tile_from_glyph('?')){ + return "'?' is not a glyph."; + } + return true; +} + +struct BadMap{ + std::string name; + std::string json; + std::vector mentions; +}; + +// The first row whose map doesn't fail as it says, or true. +UnitTestResult first_wrong_error(const std::vector& rows){ + for (const BadMap& row : rows){ + if (row.json.empty()){ + return std::format("{}: the text to edit is not in its map.", row.name); + } + const std::string error = parse_error(row.json); + if (!mentions(error, row.mentions)){ + return std::format("{}: expected an error naming {}, got: \"{}\"", row.name, row.mentions.back(), error); + } + } + return true; +} + +UnitTestResult test_each_error_class(){ + const std::vector rows = { + {.name = "not an object", .json = "[]", .mentions = {"Test.json", "not a JSON object"}}, + {.name = "missing name", .json = edited("\"name\": \"TestTown\"", "\"title\": \"TestTown\""), .mentions = {"Test.json", "name is missing"}}, + {.name = "name not a string", .json = edited("\"name\": \"TestTown\"", "\"name\": 7"), .mentions = {"name is not a string"}}, + {.name = "source missing a field", .json = edited("\"revision\": \"abc123\"", "\"rev\": \"abc123\""), .mentions = {"source.revision is missing"}}, + {.name = "tiles without rows", .json = edited("\"tiles\": [\"####\", \"#..~\", \"#D.S\", \"w^v#\"]", "\"tiles\": []"), .mentions = {"tiles has no rows"}}, + {.name = "ragged row", .json = edited("\"#..~\"", "\"#..~.\""), .mentions = {"tiles[1]", "string of 4 glyphs"}}, + {.name = "unknown glyph", .json = edited("\"#..~\"", "\"#.?~\""), .mentions = {"tiles[1]", "unknown glyph '?'", "(2, 1)"}}, + {.name = "point not a pair", .json = edited("\"door\": [1, 2]", "\"door\": [1]"), .mentions = {"points.door", "[x, y]"}}, + {.name = "point outside", .json = edited("\"sign\": [3, 2]", "\"sign\": [4, 2]"), .mentions = {"points.sign", "(4, 2)", "outside the 4x4 map"}}, + {.name = "warp missing to_point", .json = edited("\"to_point\": \"exit\"", "\"to\": \"exit\""), .mentions = {"warps[0].to_point is missing"}}, + {.name = "warp missing to_map", .json = edited("\"to_map\": \"TestHouse\"", "\"map\": \"TestHouse\""), .mentions = {"warps[0].to_map is missing"}}, + {.name = "warp entry unknown", .json = edited("\"to_map\": \"TestHouse\"", "\"enter\": \"jump\", \"to_map\": \"TestHouse\""), .mentions = {"warps[0].enter", "jump", "walk_into"}}, + {.name = "warp field of the wrong type", .json = edited("{\"x\": 1, \"y\": 2, \"to_map\"", "{\"x\": \"1\", \"y\": 2, \"to_map\""), .mentions = {"warps[0].x is not an integer"}}, + {.name = "object kind unknown", .json = edited("\"kind\": \"item\"", "\"kind\": \"boss\""), .mentions = {"objects[1].kind", "boss", "npc, item or sign"}}, + {.name = "object facing unknown", .json = edited("\"facing\": \"south\"", "\"facing\": \"down\""), .mentions = {"objects[0].facing", "down", "north, east, south or west"}}, + {.name = "wander not a box", .json = edited("\"x1\": 2, \"y1\": 2", "\"x1\": 0, \"y1\": 2"), .mentions = {"objects[0].wander is not a box"}}, + {.name = "wander outside", .json = edited("\"x1\": 2, \"y1\": 2", "\"x1\": 2, \"y1\": 7"), .mentions = {"objects[0].wander", "(2, 7)", "outside"}}, + {.name = "connection side unknown", .json = edited("\"side\": \"east\"", "\"side\": \"up\""), .mentions = {"connections[0].side", "up"}}, + {.name = "patch glyph unknown", .json = edited("\"glyph\": \"#\"", "\"glyph\": \"?\""), .mentions = {"patches[0].glyph", "?", "not a tile glyph"}}, + {.name = "patch outside", .json = edited("{\"x\": 2, \"y\": 1, \"glyph\"", "{\"x\": 2, \"y\": 9, \"glyph\""), .mentions = {"patches[0]", "(2, 9)", "outside"}}, + }; + return first_wrong_error(rows); +} + +// One value read from a parsed map, and what it should be, both as text. +struct Expected{ + std::string what; + std::string expected; + std::string read; +}; + +// The first row whose value was read wrong, or true. +UnitTestResult first_wrong(const std::vector& rows){ + for (const Expected& row : rows){ + if (row.read != row.expected){ + return std::format("{}: expected \"{}\", read \"{}\".", row.what, row.expected, row.read); + } + } + return true; +} + +std::string text(const std::optional& value){ + return value ? *value : "(none)"; +} +std::string text(const std::vector& tiles){ + std::string out; + for (const TilePos& pos : tiles){ + out += to_string(pos); + } + return out; +} +std::string text(const std::optional& trainer){ + if (!trainer){ + return "(none)"; + } + std::string out = std::format("sight {}, looks", trainer->sight); + for (Direction direction : trainer->looks){ + out += std::format(" {}", direction_name(direction)); + } + return out; +} +std::string text(const TileBox& box){ + return std::format("({}, {})..({}, {})", box.x0, box.y0, box.x1, box.y1); +} +std::string text(const MapWarp* warp){ + if (warp == nullptr){ + return "(none)"; + } + const std::string to = warp->to ? std::format("{}.{}", warp->to->map, warp->to->point) : "(not loaded)"; + return std::format("{} {} -> {}", to_string(TilePos{warp->x, warp->y}), (int)warp->enter, to); +} +std::string text(const std::set& flags){ + std::string out; + for (const std::string& flag : flags){ + out += std::format("{} ", flag); + } + return out; +} + +UnitTestResult test_bdsp_shaped_map(){ + const MapData map = parse_map(parse_json(BDSP_MAP), "Route201.json"); + const std::string world = map.world ? std::format("{} {}", map.world->name, to_string(map.world->offset)) : "(none)"; + return first_wrong({ + {.what = "world", .expected = "Sinnoh (96, 839)", .read = world}, + {.what = "tile (0, 0)", .expected = "' '", .read = std::format("'{}'", glyph_of(map.tiles.at({0, 0})))}, + {.what = "tile (0, 1) is off the map", .expected = "1", .read = std::to_string(map.tiles.at({0, 1}) == TileKind::OUTSIDE)}, + {.what = "region lawn, in order", .expected = "(3, 2)(1, 2)(1, 3)", .read = text(map.regions.at("lawn"))}, + {.what = "warp_at (4, 2)", .expected = std::format("(4, 2) {} -> (not loaded)", (int)WarpEntry::STEP_ON), .read = text(warp_at(map, {4, 2}))}, + {.what = "warp_at (3, 2)", .expected = "(none)", .read = text(warp_at(map, {3, 2}))}, + {.what = "Tristan, sight along his facing", .expected = "sight 2, looks west", .read = text(map.objects[0].trainer)}, + {.what = "Natalie, sight both ways", .expected = "sight 3, looks north east", .read = text(map.objects[1].trainer)}, + {.what = "Rowan is no trainer", .expected = "(none)", .read = text(map.objects[2].trainer)}, + {.what = "Rowan's hide flag", .expected = "story_after_00.03", .read = text(map.objects[2].hide_flag)}, + {.what = "Tristan's hide flag", .expected = "(none)", .read = text(map.objects[0].hide_flag)}, + {.what = "trigger 0", .expected = "barry_warning (2, 1)..(3, 1) 00.02", .read = std::format( + "{} {} {}", map.triggers[0].name, text(map.triggers[0].box), text(map.triggers[0].when) + )}, + {.what = "trigger 1, any time", .expected = "border_sign (none)", .read = std::format("{} {}", map.triggers[1].name, text(map.triggers[1].when))}, + }); +} + +UnitTestResult test_frlg_shaped_map(){ + const MapData map = parse_map(parse_json(FRLG_MAP), "CeruleanCave_1F.json"); + if (!map.elevation || map.elevation->width != 4 || map.elevation->height != 3){ + return "Expected 4x3 elevations."; + } + const auto tile = [&](const TilePos& pos){ + return std::format("'{}'", glyph_of(map.tiles.at(pos))); + }; + const auto elevation = [&](const TilePos& pos){ + return std::to_string(map.elevation->at(pos)); + }; + const auto warp = [&](WarpEntry enter, const TilePos& pos, std::string_view to){ + return std::format("{} {} -> {}", to_string(pos), (int)enter, to); + }; + return first_wrong({ + {.what = "closed north", .expected = "'8'", .read = tile({0, 1})}, + {.what = "closed south", .expected = "'2'", .read = tile({2, 1})}, + {.what = "closed west", .expected = "'4'", .read = tile({0, 2})}, + {.what = "closed east", .expected = "'6'", .read = tile({2, 2})}, + {.what = "elevation (2, 0)", .expected = "0", .read = elevation({2, 0})}, + {.what = "elevation (1, 1), upper case", .expected = "15", .read = elevation({1, 1})}, + {.what = "elevation (1, 2), lower case", .expected = "10", .read = elevation({1, 2})}, + {.what = "cave entrance", .expected = warp(WarpEntry::CAVE_ENTRANCE, {1, 0}, "CeruleanCity.warp_6"), .read = text(warp_at(map, {1, 0}))}, + {.what = "ladder to a map not loaded", .expected = warp(WarpEntry::STEP_ON, {2, 0}, "(not loaded)"), .read = text(warp_at(map, {2, 0}))}, + {.what = "mat north", .expected = warp(WarpEntry::WALK_NORTH, {1, 1}, "CeruleanCave_2F.warp_0"), .read = text(warp_at(map, {1, 1}))}, + {.what = "mat south", .expected = warp(WarpEntry::WALK_SOUTH, {2, 1}, "CeruleanCave_2F.warp_1"), .read = text(warp_at(map, {2, 1}))}, + {.what = "mat west", .expected = warp(WarpEntry::WALK_WEST, {1, 2}, "CeruleanCave_2F.warp_2"), .read = text(warp_at(map, {1, 2}))}, + {.what = "mat east", .expected = warp(WarpEntry::WALK_EAST, {3, 2}, "CeruleanCave_2F.warp_3"), .read = text(warp_at(map, {3, 2}))}, + {.what = "the guard's hide flag", .expected = "FLAG_HIDE_CERULEAN_CAVE_GUARD", .read = text(map.objects[0].hide_flag)}, + {.what = "flag set, each flag once", .expected = "FLAG_B FLAG_HIDE_CERULEAN_CAVE_GUARD ", .read = text(map.flag_sets.at("after_hall_of_fame"))}, + {.what = "no running", .expected = "false", .read = map.allow_running ? "true" : "false"}, + }); +} + +UnitTestResult test_each_error_class_of_game_fields(){ + return first_wrong_error({ + {.name = "world missing a field", .json = edited(BDSP_MAP, "\"name\": \"Sinnoh\"", "\"grid\": \"Sinnoh\""), .mentions = {"world.name is missing"}}, + {.name = "unknown glyph", .json = edited(BDSP_MAP, "\" ###\"", "\" #9#\""), .mentions = {"tiles[0]", "unknown glyph '9'"}}, + {.name = "region empty", .json = edited(BDSP_MAP, "[[3, 2], [1, 2], [1, 3]]", "[]"), .mentions = {"regions.lawn", "non-empty"}}, + {.name = "region tile not a pair", .json = edited(BDSP_MAP, "[[3, 2], [1, 2]", "[[3, 2], [1]"), .mentions = {"regions.lawn[1]", "[x, y]"}}, + {.name = "region tile outside", .json = edited(BDSP_MAP, "[[3, 2], [1, 2]", "[[3, 2], [9, 2]"), .mentions = {"regions.lawn[1]", "(9, 2)", "outside"}}, + {.name = "trainer with no way to look", .json = edited(BDSP_MAP, "\"facing\": \"west\", ", ""), .mentions = {"objects[0].trainer.looks is missing"}}, + {.name = "trainer sight below 1", .json = edited(BDSP_MAP, "\"sight\": 2", "\"sight\": 0"), .mentions = {"objects[0].trainer.sight 0", "at least 1"}}, + {.name = "trainer looks unknown", .json = edited(BDSP_MAP, "[\"north\", \"east\"]", "[\"north\", \"up\"]"), .mentions = {"objects[1].trainer.looks[1]", "up"}}, + {.name = "hide flag not a string", .json = edited(BDSP_MAP, "\"story_after_00.03\"", "3"), .mentions = {"objects[2].hide_flag is not a string"}}, + {.name = "trigger missing its box", .json = edited(BDSP_MAP, "\"box\": {\"x0\": 2", "\"area\": {\"x0\": 2"), .mentions = {"triggers[0].box is missing"}}, + {.name = "trigger outside", .json = edited(BDSP_MAP, "\"x1\": 3, \"y1\": 1", "\"x1\": 7, \"y1\": 1"), .mentions = {"triggers[0].box", "(7, 1)", "outside"}}, + {.name = "warp entry unknown", .json = edited(FRLG_MAP, "\"step_on\"", "\"fly\""), .mentions = {"warps[1].enter", "fly"}}, + {.name = "elevation rows missing", .json = edited(FRLG_MAP, ", \"0a33\"]", "]"), .mentions = {"elevation has 2 rows", "tiles' 3"}}, + {.name = "elevation row short", .json = edited(FRLG_MAP, "\"3F03\"", "\"3F0\""), .mentions = {"elevation[1]", "4 hex digits"}}, + {.name = "elevation not hex", .json = edited(FRLG_MAP, "\"3F03\"", "\"3G03\""), .mentions = {"elevation[1]", "'G'", "not a hex digit"}}, + {.name = "flag set not a list", .json = edited(FRLG_MAP, "[\"FLAG_B\", \"FLAG_HIDE_CERULEAN_CAVE_GUARD\", \"FLAG_B\"]", "\"FLAG_B\""), .mentions = {"flag_sets.after_hall_of_fame", "not a list"}}, + {.name = "flag not a string", .json = edited(FRLG_MAP, "[\"FLAG_B\", ", "[7, "), .mentions = {"flag_sets.after_hall_of_fame[0] is not a string"}}, + {.name = "allow_running not a boolean", .json = edited(FRLG_MAP, "\"allow_running\": false", "\"allow_running\": 0"), .mentions = {"allow_running is not true or false"}}, + }); +} + + +// The maps in TestMaps/, read back from the program: the small one, and one +// longer than a string literal may be, which the build splits. +UnitTestResult test_built_in_maps(){ + const std::vector>& files = navigation_test_map_json(); + if (files.size() != 2 || files[0].first != "BigField" || files[1].first != "Cave"){ + return "Expected BigField and Cave, sorted by name."; + } + const MapData big = parse_map(parse_json(files[0].second), "BigField.json"); + if (files[0].second.size() <= 16000 || big.tiles.width != 130 || big.tiles.height != 130){ + return "Expected BigField's 130x130 tiles, over 16000 bytes of text."; + } + for (int y = 0; y < 130; y++){ + for (int x = 0; x < 130; x++){ + const bool border = x == 0 || y == 0 || x == 129 || y == 129; + if (big.tiles.at(TilePos{x, y}) != (border ? TileKind::WALL : TileKind::OPEN)){ + return std::format("BigField's tile ({}, {}) is wrong.", x, y); + } + } + } + const MapData cave = parse_map(parse_json(files[1].second), "Cave.json"); + if (cave.tiles.width != 3 || cave.tiles.height != 1){ + return "Expected Cave's 3x1 tiles."; + } + return true; +} + +struct MapDataTestInput{ + std::string name; + UnitTestResult (*test)(); +}; + +struct MapDataTestExpectation{ + std::string_view description; +}; + +struct MapDataTestCase{ + MapDataTestInput input; + MapDataTestExpectation expectation; +}; + +class Test_MapData : public UnitTest{ +public: + explicit Test_MapData(MapDataTestCase scenario) + : UnitTest(std::format("Pokemon::MapData - {}", scenario.input.name)) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_scenario.input.test(); + }catch (Exception& e){ + return std::format("{}: {}", e.name(), e.message()); + } + } + +private: + MapDataTestCase m_scenario; +}; + +UnitTestResult test_tiles_to_door(){ + // A 3x22 grid with a 20-tile corridor leading north to a door at (1, 0) + Grid corridor{ + .width = 3, + .height = 22, + .cells = std::vector(3 * 22, TileKind::WALL) + }; + cell_at({1, 0}, corridor) = TileKind::DOOR; + for (int y = 1; y <= 20; y++){ + cell_at({1, y}, corridor) = TileKind::OPEN; + } + + // From (1, 20) north to door at (1, 0): exactly 20 tiles + const size_t tiles_20 = tiles_to_door(corridor, {1, 20}, Direction::NORTH); + if (tiles_20 != 20){ + return std::format("corridor: expected 20 tiles to door, got {}.", tiles_20); + } + + // From (1, 1) north to door at (1, 0): exactly 1 tile + const size_t tiles_1 = tiles_to_door(corridor, {1, 1}, Direction::NORTH); + if (tiles_1 != 1){ + return std::format("doorstep: expected 1 tile to door, got {}.", tiles_1); + } + + // From (1, 1) south towards wall at row 21: 20 tiles + const size_t tiles_south = tiles_to_door(corridor, {1, 1}, Direction::SOUTH); + if (tiles_south != 20){ + return std::format("wall stop: expected 20 tiles to wall, got {}.", tiles_south); + } + + // From (1, 1) east into wall at (2, 1): 1 tile + const size_t tiles_east = tiles_to_door(corridor, {1, 1}, Direction::EAST); + if (tiles_east != 1){ + return std::format("adjacent wall: expected 1 tile to wall, got {}.", tiles_east); + } + + return true; +} + +const MapDataTestCase MAP_DATA_CASES[] = { + { + .input = {.name = "the valid map", .test = test_valid_map}, + .expectation = {.description = "parses full map with all properties and layers"}, + }, + { + .input = {.name = "lists may be left out", .test = test_lists_may_be_left_out}, + .expectation = {.description = "allows optional collection fields to be omitted"}, + }, + { + .input = {.name = "glyphs round-trip", .test = test_glyphs_round_trip}, + .expectation = {.description = "converts between tile characters and enum kinds"}, + }, + { + .input = {.name = "each error class", .test = test_each_error_class}, + .expectation = {.description = "rejects invalid JSON syntax and malformed map schemas"}, + }, + { + .input = {.name = "a map shaped like BDSP's", .test = test_bdsp_shaped_map}, + .expectation = {.description = "parses BDSP-specific world offsets, trainers, and triggers"}, + }, + { + .input = {.name = "a map shaped like FRLG's", .test = test_frlg_shaped_map}, + .expectation = {.description = "parses FRLG-specific elevations, flags, and warp directions"}, + }, + { + .input = {.name = "each error class of the game fields", .test = test_each_error_class_of_game_fields}, + .expectation = {.description = "validates constraints on game-specific map fields"}, + }, + { + .input = {.name = "maps built into the program", .test = test_built_in_maps}, + .expectation = {.description = "loads and verifies embedded test map assets"}, + }, + { + .input = {.name = "tiles to door raycasting", .test = test_tiles_to_door}, + .expectation = {.description = "counts tile distance along a corridor to a door or wall"}, + }, +}; + +} // namespace + + +void add_tests_MapData(UnitTestDatabase& database){ + for (const auto& scenario : MAP_DATA_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.h new file mode 100644 index 0000000000..92bacb3393 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.h @@ -0,0 +1,23 @@ +/* Map Data Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_MapData_Tests_H +#define PokemonAutomation_Pokemon_MapData_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers map data parsing and lookup unit tests. +void add_tests_MapData(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h new file mode 100644 index 0000000000..e7af9fd8be --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h @@ -0,0 +1,100 @@ +/* Map Features + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_MapData.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_MapFeatures_H +#define PokemonAutomation_Pokemon_MapFeatures_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon_Grid.h" +#include "Pokemon_MapTiles.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A warp from (x, y), taken as `enter` says. `to` is left out for a warp +// to a map that is not loaded: the warp is still there, for routes to keep +// off. +struct MapWarp{ + int x = 0; + int y = 0; + WarpEntry enter = WarpEntry::WALK_INTO; + std::optional to; +}; + +// Type classification for interactive map objects. +enum class ObjectKind{ + NPC, + ITEM, + SIGN, +}; + +// A box of tiles, both corners inclusive. +struct TileBox{ + int x0 = 0; + int y0 = 0; + int x1 = 0; + int y1 = 0; +}; + +// A trainer sees `sight` tiles ahead in each direction of `looks` (their +// facing, unless the map says otherwise). +struct MapTrainer{ + int sight = 0; + std::vector looks; +}; + +// Something standing on a tile, which blocks it. A person who wanders may +// stand anywhere in `wander`. The game hides the object while `hide_flag` +// is set (an event flag, or a story state the game's code sets). +struct MapObject{ + std::string name; + ObjectKind kind = ObjectKind::NPC; + int x = 0; + int y = 0; + std::optional facing; + std::optional wander; + std::optional trainer; + std::optional hide_flag; +}; + +// A scene that starts when the player steps into `box` while the story is +// in `when` (any time, if left out): the decompilation's coord events. +struct MapTrigger{ + std::string name; + TileBox box; + std::optional when; +}; + +// Walking off the map's `side` continues on `to_map`, whose tiles are +// shifted by `offset` along that side. +struct MapConnection{ + Direction side = Direction::NORTH; + std::string to_map; + int offset = 0; +}; + +// A tile measured on the console that differs from the decompilation's. +struct MapPatch{ + int x = 0; + int y = 0; + TileKind glyph = TileKind::WALL; + std::string measured_by; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h new file mode 100644 index 0000000000..6f3cf1373e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h @@ -0,0 +1,89 @@ +/* Map Tiles + * + * From: https://github.com/PokemonAutomation/ + * + * Split out of Pokemon_MapData.h, unchanged; it includes this header. + * + */ + +#ifndef PokemonAutomation_Pokemon_MapTiles_H +#define PokemonAutomation_Pokemon_MapTiles_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What a tile is, for walking. The map files write each as one glyph. +enum class TileKind : uint8_t{ + WALL, // '#' + OPEN, // '.' + TALL_GRASS, // '~' open, with wild encounters + WATER, // 'w' + LEDGE_NORTH, // '^' a wall, except that walking into it the arrow's + LEDGE_SOUTH, // 'v' way hops the player over it + LEDGE_WEST, // '<' + LEDGE_EAST, // '>' + DOOR, // 'D' a door or warp tile walked into + SIGN, // 'S' a sign, read by facing it + OUTSIDE, // ' ' no map of the game's here (a map's rectangle + // reaching past the game's own) + CLOSED_NORTH, // '8' open, but not crossed through its named side: + CLOSED_SOUTH, // '2' not entered from it, nor left through it (the + CLOSED_WEST, // '4' number pad's arrows) + CLOSED_EAST, // '6' +}; +// The tile a glyph stands for, or nothing if it isn't one. +std::optional tile_from_glyph(char glyph); +// Returns the character glyph representing a TileKind. +char glyph_of(TileKind tile); + + +// Where the tiles came from: the decompilation file, at which revision, +// read when. +struct MapSource{ + std::string decomp_file; + std::string revision; + std::string date; +}; + +// Where the map lies on a world grid that several maps share (a BDSP map +// matrix): its tile (0, 0) is tile `offset` of world `name`. Maps on the +// same world join where they meet. +struct MapWorld{ + std::string name; + TilePos offset; +}; + +// Where a warp puts the player: point `point` of map `map`. +struct WarpDestination{ + std::string map; + std::string point; +}; + +// How the player takes a warp, as the map file writes it. +enum class WarpEntry{ + WALK_INTO, // "walk_into": a door or cave mouth, walked into + STEP_ON, // "step_on": stepping onto the tile (ladders, + // escalators, BDSP's warp tiles) + CAVE_ENTRANCE, // "cave_entrance": stepping onto the tile; the game + // walks a player arriving on it a tile south + WALK_NORTH, // "walk_north" ...: standing on the tile and walking + WALK_SOUTH, // that way (exit mats, stairs at the side of a room) + WALK_WEST, + WALK_EAST, +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_NavigationTestMaps.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_NavigationTestMaps.h new file mode 100644 index 0000000000..75dcf2daa4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_NavigationTestMaps.h @@ -0,0 +1,26 @@ +/* Navigation Test Maps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_NavigationTestMaps_H +#define PokemonAutomation_Pokemon_NavigationTestMaps_H + +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// (name, JSON text) of each map in Pokemon/Navigation/TestMaps/, built into +// the program by pa_embed_text_files() (cmake/EmbedTextFiles.cmake). +const std::vector>& navigation_test_map_json(); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp new file mode 100644 index 0000000000..19ac59cf41 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp @@ -0,0 +1,103 @@ +/* Route Log + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_RouteLog.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string to_string(const RouteTile& tile){ + return std::format("{} {}", tile.map, to_string(tile.pos)); +} + +std::string describe(const std::vector& tiles){ + if (tiles.empty()){ + return "an unknown tile"; + } + std::string out; + for (const RouteTile& tile : tiles){ + out += (out.empty() ? "" : ", ") + to_string(tile); + } + return out; +} + +std::string to_string(const RouteLogLeg& leg){ + const std::string direction = direction_name(leg.direction); + switch (leg.action){ + case RouteLegAction::SURF: + return std::format("surf {}", direction); + case RouteLegAction::FACE: + return std::format("face {}", direction); + case RouteLegAction::WALK: + break; + } + const std::string_view end = leg.end == RouteLegEnd::WALL ? " (to wall)" : leg.end == RouteLegEnd::WARP ? " (warp)" : " (open)"; + return std::format("{} {}{}", direction, leg.tiles, end); +} + +std::string basis_name(EndBasis basis){ + switch (basis){ + case EndBasis::WALKED: + return "walked"; + case EndBasis::ASSUMED: + return "assumed"; + case EndBasis::UNKNOWN: + return "unknown"; + } + return "?"; +} + + +// " to ", as the plan and the leg lines both write a leg. +static std::string planned_leg_text(const PlannedRouteLeg& leg){ + return std::format("{} to {}", to_string(leg.leg), describe(leg.after)); +} + +std::string route_plan_line(const std::string& label, const std::vector& from, const std::vector& legs){ + std::string text = std::format("{}: plan from {}:", label, describe(from)); + for (size_t i = 0; i < legs.size(); i++){ + text += (i == 0 ? " " : "; ") + planned_leg_text(legs[i]); + } + return text; +} + +std::string route_leg_line(size_t number, size_t count, const PlannedRouteLeg& leg){ + return std::format("Leg {}/{}: {}", number, count, planned_leg_text(leg)); +} + +std::string route_leg_end_line( + const std::string& label, const RouteLogLeg& leg, + const std::vector& at, EndBasis basis, const std::string& why +){ + const std::string how = why.empty() ? basis_name(basis) : std::format("{}: {}", basis_name(basis), why); + return std::format("{}: {}: ended at {} ({}).", label, to_string(leg), describe(at), how); +} + +std::string route_replan_line( + const std::string& label, const RouteLogLeg& leg, + const std::string& what, const std::vector& at +){ + return std::format("{}: {}: {}, at {}; planning again.", label, to_string(leg), what, describe(at)); +} + +std::string route_found_line(const std::string& label, const std::vector& at, size_t holds){ + return std::format("{}: found again at {}, after {} hold(s).", label, describe(at), holds); +} + +std::string route_trainer_line(const std::string& label, const std::string& who, const std::vector& at){ + return std::format("{}: {} stopped us about {}.", label, who, describe(at)); +} + +std::string route_arrived_line(const std::string& label, const std::vector& at){ + return std::format("{}: arrived at {}.", label, describe(at)); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h new file mode 100644 index 0000000000..17cdaef020 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h @@ -0,0 +1,71 @@ +/* Route Log + * + * From: https://github.com/PokemonAutomation/ + * + * The log lines a route walk writes, shared by the games' walkers so that + * every game's log reads the same and devtools/maps can draw any run's + * routes from it. These are BDSP AutoStory's route lines, lifted from + * PokemonBDSP_AutoStory_RouteWalk.cpp, with what the other games need: + * + * [Route] To the grass: plan from Route 202 (15, 25), Route 202 (16, 25): east 15 (to wall) to Route 202 (23, 25), Route 202 (30, 26); north 5 (to wall) to Route 202 (23, 24) + * [Route] Leg 1/2: east 15 (to wall) to Route 202 (23, 25), Route 202 (30, 26) + * [Route] To the grass: east 15 (to wall): ended at Route 202 (23, 25) (walked). + * [Route] To the grass: north 5 (to wall): stopped early after about 2 tiles, at Route 202 (23, 23); planning again. + * [Route] To the grass: found again at Route 202 (22, 24), after 2 holds. + * [Route] To the grass: arrived at Route 202 (23, 24). + * + * A position is a set of tiles: BDSP plans from every tile the player may + * be on, FRLG from the one it is on. A leg's end says how it is known: + * walked (as planned, or seen), assumed (taken to have ended as planned + * after something interrupted it), or unknown. + * + * The functions return a line without the "[Route] " tag, which + * ROUTE_LOG_TAG holds; the caller logs it. + * + */ + +#ifndef PokemonAutomation_Pokemon_RouteLog_H +#define PokemonAutomation_Pokemon_RouteLog_H + +#include +#include +#include +#include +#include "Pokemon_Grid.h" +#include "Pokemon_RouteLogLegs.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// "