diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index 36f4de8f6d..847692b532 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -6,6 +6,10 @@ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h" #include "PokemonBDSP_Tests.h" namespace PokemonAutomation{ @@ -16,6 +20,10 @@ namespace PokemonBDSP{ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_Maps(database); + add_tests_AutoStory_StoryWorld(database); + add_tests_AutoStory_RoutePlanner(database); + add_tests_AutoStory_StoryMaps(database); + add_tests_AutoStory_Segment00(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp new file mode 100644 index 0000000000..eb982fef43 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp @@ -0,0 +1,47 @@ +/* BDSP AutoStory - Plan Costs + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP_AutoStory_RobustRoute.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +RobustPlanCosts route_plan_costs(){ + RobustPlanCosts costs; + costs.exact_open_tiles = costs.max_open_tiles; + costs.per_open_tile = 2; + costs.leg_not_at_wall = 6; + return costs; +} + +RobustPlanCosts waypoint_plan_costs(){ + RobustPlanCosts costs; + costs.exact_open_tiles = costs.max_open_tiles; + costs.per_open_tile = 0; + costs.leg_not_at_wall = 0; + return costs; +} + +RobustPlanCosts town_plan_costs(){ + RobustPlanCosts costs; + // A tile's hold moves exactly a tile; a longer open leg may end a tile + // either way ("south 5" went 6 in r134a), so the plan ends on a wall. + costs.exact_open_tiles = 1; + costs.open_error_per = 8; + costs.leg_not_at_wall = 6; + costs.per_open_tile = 2; + return costs; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h new file mode 100644 index 0000000000..be2959df39 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h @@ -0,0 +1,47 @@ +/* BDSP AutoStory - Plan Costs + * + * From: https://github.com/PokemonAutomation/ + * + * The costs the story's walks are planned with on the BDSP maps + * (plan_robust_route()), apart from the walker, so the map + * tests plan each walk the way the program does. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_PlanCosts_H +#define PokemonAutomation_PokemonBDSP_AutoStory_PlanCosts_H + +#include "PokemonBDSP_AutoStory_RobustRoute.h" +#include "PokemonBDSP_AutoStory_RoutePlanner.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// The default: open legs are whole tiles on the D-pad, so they land exactly +// at any length; a wall at a leg's end is still worth a little, and each +// open tile a little more. +RobustPlanCosts route_plan_costs(); + +// Between two corners of a walked line: whole tiles on the D-pad land +// exactly, so an open leg costs nothing extra and the straight leg to the +// corner beats a run to a wall and a tap back (r244a: "west 10 to the +// wall, east 1" through the wandering Youngster lost the count; "west 9" +// in taps keeps it). +RobustPlanCosts waypoint_plan_costs(); + +// In town: a one-tile step lands exactly, a short open leg a tile either +// way, and both cost little more than a leg to a wall, so a plan steps a +// tile across and walks straight through a gap rather than going round the +// town to end every leg on a wall (Sandgem: 13 legs, r127a and r128b +// walked into the Lab and the Mart). Pair it with a check at the end (a +// sign read) for the timed legs. +RobustPlanCosts town_plan_costs(); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RobustRoute.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RobustRoute.h new file mode 100644 index 0000000000..a54bdc1610 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RobustRoute.h @@ -0,0 +1,99 @@ +/* BDSP AutoStory - Robust route planner + * + * From: https://github.com/PokemonAutomation/ + * + * Plans walks whose open legs may go a tile short or long: each leg + * lists every tile the player may end on, and later walls bring them + * back together. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RobustRoute_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RobustRoute_H + +#include +#include +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP_AutoStory_StoryWorld.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// A leg of a plan that allows for open legs going a tile short or long. A +// leg to a wall is walked until the player stops; an open leg is walked for +// `leg.tiles` tiles' worth of time. `after` lists every tile the player may +// stand on once the leg is done. +struct PlannedLeg{ + TileLeg leg; + std::vector after; +}; +// Formats planned route leg with uncertainties into human-readable representation. +std::string to_string(const PlannedLeg& leg); + +// Cost configuration parameters accounting for movement execution tolerances. +struct RobustPlanCosts : TilePlanCosts{ + // An open leg of n tiles may end open_error + n / open_error_per tiles + // short or long: on the console 7 tiles went 9. + int open_error = 1; + int open_error_per = 5; + // Open legs this many tiles or shorter land exactly: a short hold moves + // whole tiles. 0 keeps every open leg uncertain. + int exact_open_tiles = 0; + // Extra per tile of an open leg: its timing error grows with its length, + // so a short step after a wall beats a long open leg. + int per_open_tile = 0; + int max_open_tiles = 12; // longest open leg to consider + size_t max_spread = 5; // most tiles the player may be on after a leg + // Most sets of possible tiles to search before giving up. The search is + // over sets, not tiles, so it grows far faster than the map: all of + // Jubilife City from six start tiles ran for minutes with no plan + // (r224a, 2026-10-31); 200000 sets took 31 s there, so this gives up + // after about 3. Use town costs in towns (a whole-Jubilife plan then + // takes 1 s) and crop the map to the part a leg needs rather than + // raising this. + size_t max_searched = 20000; +}; + +// Cheapest legs that take the player from any of the tiles in `from` to tiles +// that are all `goal`, even if every open leg ends up to `open_error` tiles +// off: the walls of later legs must bring the possible positions together. +// Legs that would leave the maps or enter a door are not used, nor legs that +// run along a zone where someone wanders: two tiles of it in a row, the +// leg's start among them. Crossing a zone (one tile of it) costs +// `per_wander_tile`. On lab-B (2026-11-08, 01.08) Route 204's youngster, +// who wanders (12, 2) to (14, 2), stopped the leg "west 2 (to wall)" from +// (13, 2) twice. Nothing if no such plan exists, or none is found within +// `costs.max_searched` sets. +std::optional> plan_robust_route( + const StoryWorld& world, + const std::vector& from, const std::function& goal, + const RobustPlanCosts& costs = RobustPlanCosts() +); +// The same, from one tile to exactly `to`. +std::optional> plan_robust_route( + const StoryWorld& world, + const Pokemon::TilePos& from, const Pokemon::TilePos& to, + const RobustPlanCosts& costs = RobustPlanCosts() +); + +// What plan_robust_route() charges for walking `legs` from any of `from`, +// each leg from the tiles the one before may end on. A leg it would not +// plan (along a wander zone, or off the maps) costs its tiles and legs +// without grass or wander tiles. +long long robust_route_cost( + const StoryWorld& world, + const std::vector& from, const std::vector& legs, + const RobustPlanCosts& costs +); + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp new file mode 100644 index 0000000000..a89679cf16 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp @@ -0,0 +1,511 @@ +/* BDSP AutoStory - Route planner + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon/Navigation/Pokemon_LegPlanner.h" +#include "PokemonBDSP_AutoStory_RobustRoute.h" +#include "PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP_AutoStory_TrainerSight.h" +#include "PokemonBDSP_AutoStory_WalkRules.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::Direction; +using Pokemon::TileKind; +using Pokemon::TilePos; + + +namespace{ + +size_t distance(const TilePos& a, const TilePos& b){ + return std::abs(a.x - b.x) + std::abs(a.y - b.y); +} + +bool tall_grass(const StoryWorld& world, const TilePos& pos){ + return world.tile(pos) == TileKind::TALL_GRASS; +} + +} // namespace + + +WallHit slide_to_wall(const StoryWorld& world, const TilePos& from, Direction direction){ + WallHit hit; + hit.stop = from; + while (true){ + const TilePos before = hit.stop; + const std::optional next = step(world, before, direction); + if (!next){ + hit.wall = before.next(direction); + hit.anchored = at_wall(world, before, direction); + return hit; + } + hit.tiles += distance(*next, before); + hit.stop = *next; + } +} + + +std::string to_string(const TileLeg& leg){ + return std::format("{} {}{}", Pokemon::direction_name(leg.direction), leg.tiles, leg.ends_at_wall ? " (to wall)" : " (open)"); +} + + +namespace{ + +// The world's step rules for the shared leg planner. A ledge hop is one +// press that moves two tiles. +class StoryWorldModel{ +public: + using State = TilePos; + using StateHash = std::hash; + + StoryWorldModel(const StoryWorld& world, const TilePlanCosts& costs) + : m_world(world) + , m_costs(costs) + {} + + std::optional> press(const State& pos, Direction direction) const{ + const std::optional next = step(m_world, pos, direction); + if (!next){ + return std::nullopt; + } + Pokemon::Step step; + step.next = *next; + step.facing = direction; + step.extra_cost = m_costs.per_tile * ((int)distance(*next, pos) - 1); + if (tall_grass(m_world, *next)){ + step.extra_cost += m_costs.per_grass_tile; + } + if (wandering_hazard(m_world, *next)){ + step.extra_cost += m_costs.per_wander_tile; + } + return step; + } + bool held_at(const State& pos, Direction direction) const{ + return at_wall(m_world, pos, direction); + } + +private: + const StoryWorld& m_world; + const TilePlanCosts& m_costs; +}; + +void check_standable(const StoryWorld& world, const TilePos& from, const TilePos& to){ + if (!standable(world, from) || !standable(world, to)){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format( + "Route ends must be standable: {} -> {}.", Pokemon::to_string(from), Pokemon::to_string(to) + )); + } +} + +} // namespace + +std::optional> plan_tile_route( + const StoryWorld& world, + const TilePos& from, const TilePos& to, + const TilePlanCosts& costs +){ + check_standable(world, from, to); + if (from == to){ + return std::vector(); + } + Pokemon::LegCosts leg_costs; + leg_costs.per_tile = costs.per_tile; + leg_costs.per_turn = costs.per_leg; + leg_costs.per_open_stop = costs.leg_not_at_wall; + const auto legs = Pokemon::plan_legs( + StoryWorldModel(world, costs), from, std::nullopt, + std::function([&](const TilePos& pos){ return pos == to; }), + std::nullopt, leg_costs + ); + if (!legs){ + return std::nullopt; + } + std::vector ret; + for (const Pokemon::Leg& leg : *legs){ + ret.push_back(TileLeg{leg.direction, distance(leg.end, leg.start), leg.to_wall}); + } + return ret; +} + +std::vector sight_tiles(const StoryWorld& world, const TrainerSight& trainer){ + std::vector tiles; + TilePos pos = trainer.pos; + for (int i = 0; i < trainer.range; i++){ + pos = pos.next(trainer.facing); + if (!standable(world, pos)){ + break; + } + tiles.push_back(pos); + } + return tiles; +} + +std::vector> legs_crossing_sight( + const StoryWorld& world, + const TilePos& from, + const std::vector& legs, + const std::vector& trainers +){ + std::vector> sights; + for (const TrainerSight& trainer : trainers){ + sights.push_back(sight_tiles(world, trainer)); + } + std::vector> crossings; + TilePos pos = from; + for (const TileLeg& leg : legs){ + const std::vector tiles = trace_legs(world, pos, {leg}); + std::vector seen_by; + for (size_t t = 0; t < trainers.size(); t++){ + const bool seen = std::any_of(tiles.begin() + 1, tiles.end(), [&](const TilePos& tile){ + return std::ranges::find(sights[t], tile) != sights[t].end(); + }); + if (seen){ + seen_by.push_back(trainers[t].name); + } + } + crossings.push_back(std::move(seen_by)); + pos = tiles.back(); + } + return crossings; +} + +std::vector trace_legs( + const StoryWorld& world, + const TilePos& from, + const std::vector& legs +){ + std::vector tiles{from}; + for (const TileLeg& leg : legs){ + size_t travelled = 0; + while (travelled < leg.tiles){ + const TilePos pos = tiles.back(); + const std::optional next = step(world, pos, leg.direction); + if (!next){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format( + "Leg {} is stopped at {}.", to_string(leg), Pokemon::to_string(pos) + )); + } + travelled += distance(*next, pos); + tiles.push_back(*next); + } + if (travelled != leg.tiles){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("Leg {} overshoots on a ledge hop.", to_string(leg))); + } + } + return tiles; +} + + +std::string to_string(const PlannedLeg& leg){ + std::string out = to_string(leg.leg) + " to"; + for (const TilePos& pos : leg.after){ + out += " " + Pokemon::to_string(pos); + } + return out; +} + +namespace{ + +// Where `from` ends up after `tiles` steps in `direction`, stopping early at +// anything that stops the player, and how many tall-grass tiles it enters. +// Nothing if a step would leave the maps or enter a door: the plan cannot +// tell what happens then. +struct Stepped{ + TilePos end; + int grass = 0; + int wander = 0; + // Two tiles in a row where someone wanders, the start among them: the + // walk runs along their zone, and plan_robust_route() does not use it. + bool along_wander = false; +}; +std::optional step_tiles(const StoryWorld& world, TilePos from, Direction direction, int tiles){ + Stepped stepped; + int travelled = 0; + bool in_wander = wandering_hazard(world, from); + while (travelled < tiles){ + const std::optional next = step(world, from, direction); + if (!next){ + if (!at_wall(world, from, direction)){ + return std::nullopt; + } + break; + } + travelled += (int)distance(*next, from); + if (tall_grass(world, *next)){ + stepped.grass++; + } + const bool next_wander = wandering_hazard(world, *next); + if (next_wander){ + stepped.wander++; + stepped.along_wander |= in_wander; + } + in_wander = next_wander; + from = *next; + } + stepped.end = from; + return stepped; +} + +using Spread = std::vector; + +bool spread_less(const TilePos& a, const TilePos& b){ + return a.y != b.y ? a.y < b.y : a.x < b.x; +} +void normalize(Spread& spread){ + std::sort(spread.begin(), spread.end(), spread_less); + spread.erase(std::unique(spread.begin(), spread.end()), spread.end()); +} +struct SpreadLess{ + bool operator()(const Spread& a, const Spread& b) const{ + return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), spread_less); + } +}; + +// A leg out of a spread: where every tile of it ends, and its cost. +struct Expansion{ + long long cost = 0; + Spread next; + TileLeg leg; +}; + +// To the wall: every position walks until stopped. Nothing unless each is +// held at a wall, and one moves. +std::optional to_wall_leg(const StoryWorld& world, const Spread& spread, Direction direction, const RobustPlanCosts& costs){ + Expansion expansion; + size_t longest = 0; + int grass = 0; + int wander = 0; + for (const TilePos& pos : spread){ + const WallHit hit = slide_to_wall(world, pos, direction); + if (!hit.anchored){ + return std::nullopt; + } + if (const std::optional stepped = step_tiles(world, pos, direction, (int)hit.tiles)){ + if (stepped->along_wander){ + return std::nullopt; + } + grass = std::max(grass, stepped->grass); + wander = std::max(wander, stepped->wander); + } + longest = std::max(longest, hit.tiles); + expansion.next.push_back(hit.stop); + } + if (longest == 0){ + return std::nullopt; + } + expansion.cost = (long long)costs.per_leg + (long long)costs.per_tile * longest + + (long long)costs.per_grass_tile * grass + (long long)costs.per_wander_tile * wander; + expansion.leg = TileLeg{direction, longest, true}; + return expansion; +} + +// Open: about `tiles` tiles, give or take the error. Nothing if any +// possible end leaves the maps or enters a door. +std::optional open_leg(const StoryWorld& world, const Spread& spread, Direction direction, int tiles, const RobustPlanCosts& costs){ + Expansion expansion; + int grass = 0; + int wander = 0; + const int error = tiles <= costs.exact_open_tiles ? 0 : costs.open_error + tiles / costs.open_error_per; + for (const TilePos& pos : spread){ + for (int n = std::max(1, tiles - error); n <= tiles + error; n++){ + const std::optional stepped = step_tiles(world, pos, direction, n); + if (!stepped || stepped->along_wander){ + return std::nullopt; + } + grass = std::max(grass, stepped->grass); + wander = std::max(wander, stepped->wander); + expansion.next.push_back(stepped->end); + } + } + expansion.cost = (long long)costs.per_leg + costs.leg_not_at_wall + + (long long)(costs.per_tile + costs.per_open_tile) * tiles + + (long long)costs.per_grass_tile * grass + (long long)costs.per_wander_tile * wander; + expansion.leg = TileLeg{direction, (size_t)tiles, false}; + return expansion; +} + +// Dijkstra over sets of tiles the player may stand on. +class RobustSearch{ +public: + RobustSearch(const StoryWorld& world, const RobustPlanCosts& costs) + : m_world(world) + , m_costs(costs) + {} + + std::optional> run(Spread start, const std::function& goal){ + normalize(start); + m_start = start; + m_nodes[start] = Node{0, {}, {}}; + m_queue.emplace(0, start); + size_t searched = 0; + while (!m_queue.empty()){ + const auto [cost, spread] = m_queue.top(); + m_queue.pop(); + Node& node = m_nodes[spread]; + if (node.done || node.cost != cost){ + continue; + } + node.done = true; + if (++searched > m_costs.max_searched){ + return std::nullopt; + } + if (std::all_of(spread.begin(), spread.end(), goal)){ + return legs_to(spread); + } + expand(spread, cost); + } + return std::nullopt; + } + +private: + struct Node{ + long long cost = 0; + Spread parent; + PlannedLeg leg; + bool done = false; + }; + using Entry = std::pair; + struct EntryGreater{ + bool operator()(const Entry& a, const Entry& b) const{ return a.first > b.first; } + }; + + void expand(const Spread& spread, long long cost){ + for (Direction direction : Pokemon::ALL_DIRECTIONS){ + if (std::optional wall = to_wall_leg(m_world, spread, direction, m_costs)){ + relax(spread, cost, std::move(*wall)); + } + for (int tiles = 1; tiles <= m_costs.max_open_tiles; tiles++){ + std::optional open = open_leg(m_world, spread, direction, tiles, m_costs); + if (!open){ + break; + } + relax(spread, cost, std::move(*open)); + } + } + } + + // Only the start may be wider than costs.max_spread: every leg must + // bring the player within it. + void relax(const Spread& spread, long long cost, Expansion expansion){ + normalize(expansion.next); + if (expansion.next.size() > m_costs.max_spread || expansion.next == spread){ + return; + } + if (spread != m_start){ + const TileLeg& prev = m_nodes.at(spread).leg.leg; + if (expansion.leg.direction == prev.direction && !prev.ends_at_wall){ + expansion.cost -= m_costs.per_leg; + } + } + const long long total = cost + expansion.cost; + auto iter = m_nodes.find(expansion.next); + if (iter != m_nodes.end() && iter->second.cost <= total){ + return; + } + m_nodes[expansion.next] = Node{total, spread, PlannedLeg{expansion.leg, expansion.next}}; + m_queue.emplace(total, std::move(expansion.next)); + } + + std::vector legs_to(const Spread& end) const{ + std::vector legs; + for (Spread at = end; at != m_start; ){ + const Node& step = m_nodes.at(at); + legs.push_back(step.leg); + at = step.parent; + } + std::reverse(legs.begin(), legs.end()); + std::vector consolidated; + for (const PlannedLeg& planned : legs){ + if (!consolidated.empty() && + consolidated.back().leg.direction == planned.leg.direction && + !consolidated.back().leg.ends_at_wall + ){ + consolidated.back().leg.tiles += planned.leg.tiles; + consolidated.back().leg.ends_at_wall = planned.leg.ends_at_wall; + consolidated.back().after = planned.after; + }else{ + consolidated.push_back(planned); + } + } + return consolidated; + } + + const StoryWorld& m_world; + const RobustPlanCosts& m_costs; + Spread m_start; + std::map m_nodes; + std::priority_queue, EntryGreater> m_queue; +}; + +} // namespace + +std::optional> plan_robust_route( + const StoryWorld& world, + const TilePos& from, const TilePos& to, + const RobustPlanCosts& costs +){ + check_standable(world, from, to); + return plan_robust_route(world, std::vector{from}, [&](const TilePos& pos){ return pos == to; }, costs); +} + +std::optional> plan_robust_route( + const StoryWorld& world, + const std::vector& from, const std::function& goal, + const RobustPlanCosts& costs +){ + for (const TilePos& pos : from){ + if (!standable(world, pos)){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Route starts must be standable: " + Pokemon::to_string(pos) + "."); + } + } + return RobustSearch(world, costs).run(from, goal); +} + +long long robust_route_cost( + const StoryWorld& world, + const std::vector& from, const std::vector& legs, + const RobustPlanCosts& costs +){ + long long total = 0; + Spread spread = from; + normalize(spread); + const TileLeg* previous = nullptr; + for (const PlannedLeg& planned : legs){ + const TileLeg& leg = planned.leg; + const std::optional expansion = leg.ends_at_wall + ? to_wall_leg(world, spread, leg.direction, costs) + : open_leg(world, spread, leg.direction, (int)leg.tiles, costs); + long long cost = (long long)costs.per_leg + (long long)costs.per_tile * (long long)leg.tiles; + if (!leg.ends_at_wall){ + cost += costs.leg_not_at_wall + (long long)costs.per_open_tile * (long long)leg.tiles; + } + if (expansion){ + cost = expansion->cost; + } + if (previous != nullptr && previous->direction == leg.direction && !previous->ends_at_wall){ + cost -= costs.per_leg; + } + total += cost; + spread = planned.after; + normalize(spread); + previous = ⋚ + } + return total; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h new file mode 100644 index 0000000000..5a09e8623c --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h @@ -0,0 +1,78 @@ +/* BDSP AutoStory - Route planner + * + * From: https://github.com/PokemonAutomation/ + * + * Turns a walk on the story world from one tile to another into straight + * legs. Timed stick holds drift by a tile; a leg that ends against a wall + * does not, because the player stops there however long the stick is held. + * The planner prefers such legs. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RoutePlanner_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RoutePlanner_H + +#include +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonBDSP_AutoStory_StoryWorld.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Where the player stops when walking in one direction until stopped. +struct WallHit{ + Pokemon::TilePos stop; + size_t tiles = 0; // tiles travelled; a ledge hop counts 2 + Pokemon::TilePos wall; // the first tile the player could not enter + bool anchored = false; // the player is held at `stop` (see StoryWorld::at_wall()) +}; +// Computes straight-line sliding movement from tile position until hitting a wall. +WallHit slide_to_wall(const StoryWorld& world, const Pokemon::TilePos& from, Pokemon::Direction direction); + + +// A straight run in one direction. +struct TileLeg{ + Pokemon::Direction direction = Pokemon::Direction::NORTH; + size_t tiles = 0; // tiles travelled; a ledge hop counts 2 + bool ends_at_wall = false; // the next tile in `direction` stops the player +}; +// Formats tile movement leg into human-readable string representation. +std::string to_string(const TileLeg& leg); + +// Cost configuration parameters for tile route planning. +struct TilePlanCosts{ + int per_tile = 1; + int per_grass_tile = 4; // extra for each tall-grass tile entered + int per_wander_tile = 3; // extra for each wander hazard tile entered + int per_leg = 8; + int leg_not_at_wall = 50; // extra for a leg that stops in the open +}; + +// Cheapest legs from `from` to `to`, moving 4 ways, or nothing if `to` +// cannot be reached. Both tiles must be standable. +std::optional> plan_tile_route( + const StoryWorld& world, + const Pokemon::TilePos& from, const Pokemon::TilePos& to, + const TilePlanCosts& costs = TilePlanCosts() +); + +// The tiles a list of legs visits, starting with `from`. Throws +// InternalProgramError if a leg is stopped before its end. +std::vector trace_legs( + const StoryWorld& world, + const Pokemon::TilePos& from, + const std::vector& legs +); + + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp new file mode 100644 index 0000000000..9e72dad6ec --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp @@ -0,0 +1,177 @@ +/* BDSP AutoStory - Route records + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP_AutoStory_RouteRecords.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace RouteRecords{ + +using namespace Pokemon; + +namespace{ + +// 00.01: the house, Twinleaf, Route 201 and the Lakefront out to the lake. +std::vector checkpoint_0001_records(){ + return { + {"00.01", "The house's doorstep to Barry's door", "Twinleaf Town", "TwinleafTown", true, map_point("TwinleafTown", "house_doorstep"), { + {Direction::WEST, 7, LegEnd::COUNT, "along row 22 to column 13, clear of the south-west house"}, + {Direction::NORTH, 10, LegEnd::COUNT, "up column 13 to row 12, below Barry's mailbox"}, + {Direction::WEST, 4, LegEnd::COUNT, "onto (9, 12), the one tile that starts Barry's scene: he bursts out of his door"}, + {Direction::NORTH, 1, LegEnd::DOOR, "after the scene, into Barry's house; the stairs, his room and the way back out are replays"}, + }, "Segment00Lines line 1, not walked by the program yet; the Twinleaf grid and the scene's tile from the Diamond decomp (land_data 0000, zone_event 0389)"}, + {"00.01", "Barry's doorstep to Route 201", "Twinleaf Town", "TwinleafTown", true, map_point("TwinleafTown", "barry_doorstep"), { + {Direction::EAST, 6, LegEnd::COUNT, "along row 12 to column 15"}, + {Direction::NORTH, 12, LegEnd::COUNT, "up column 15 to (15, 0), the last tile in town; the guitarist's stop on row 3 is inert once Barry has talked upstairs"}, + {Direction::NORTH, 0, LegEnd::BANNER, "on north onto Route 201"}, + }, "Segment00Lines line 2, not walked by the program yet"}, + {"00.01", "Route 201: Barry's tall-grass warning, then west to the Lakefront", "Route 201", "Route201", true, map_point("Route201", "route_201_arrival"), { + {Direction::NORTH, 6, LegEnd::COUNT, "up the exit path to (15, 18): Barry's warning fires on that row"}, + {Direction::WEST, 1, LegEnd::COUNT, "after the scene, to (14, 18); west of it is trees (r16)"}, + {Direction::NORTH, 2, LegEnd::COUNT, "past the 201 sign at (13, 17) onto row 16, the lower level's row to the Lakefront (probe-r201-sign)"}, + {Direction::WEST, 14, LegEnd::COUNT, "to (0, 16), the route's last tile"}, + {Direction::WEST, 0, LegEnd::BANNER, "on west onto the Verity Lakefront"}, + }, "Segment00Lines lines 2 and 3, not walked by the program yet; traced on the Route201 map, the decomp's since #111"}, + {"00.01", "Verity Lakefront: to below the lake's entrance", "Verity Lakefront", "VerityLakefront", true, map_point("VerityLakefront", "lakefront_arrival"), { + {Direction::WEST, 11, LegEnd::COUNT, "along row 23 to column 20"}, + {Direction::NORTH, 2, LegEnd::COUNT, "to row 21"}, + {Direction::WEST, 3, LegEnd::COUNT, "to column 17, the entrance path's east column"}, + {Direction::NORTH, 7, LegEnd::COUNT, "up column 17 to (17, 14), two tiles short of the lake's scene; 00.01 ends here"}, + }, "Segment00Lines line 3, not walked by the program yet"}, + }; +} + +// 00.02 and 00.03: into the lake's scene, and back to Sandgem. +std::vector checkpoints_0002_0003_records(){ + return { + {"00.02", "Into the lake's scene", "Verity Lakefront", "VerityLakefront", true, map_point("VerityLakefront", "below_lake_entrance"), { + {Direction::NORTH, 2, LegEnd::COUNT, "onto (17, 12): Barry hears Rowan and the two of us walk into Lake Verity"}, + {Direction::NORTH, 0, LegEnd::SCENE, "the starter, the Starly and the way back out to (17, 12) are the game's; nothing is walked at the lake"}, + }, "starter_nav() presses north twice from where 00.01 ends; Segment00Lines line 3's last two tiles; the scene's tiles from the Diamond decomp (zone_event 0319)"}, + {"00.03", "Verity Lakefront: from the lake's entrance back onto Route 201", "Verity Lakefront", "VerityLakefront", true, map_point("VerityLakefront", "lake_entrance"), { + {Direction::SOUTH, 9, LegEnd::COUNT, "down column 17 to row 21"}, + {Direction::EAST, 12, LegEnd::COUNT, "along row 21 to column 29"}, + {Direction::EAST, 0, LegEnd::BANNER, "on east onto Route 201"}, + }, "Segment00Lines line 4, not walked by the program yet; which of the two entrance tiles the scene leaves us on is for the console"}, + {"00.03", "Route 201: Rowan's scene, then east through the grass to Sandgem", "Route 201", "Route201", true, map_point("Route201", "route_201_return"), { + {Direction::EAST, 5, LegEnd::COUNT, "to (5, 14): Rowan and Dawn's scene fires on that column"}, + {Direction::EAST, 12, LegEnd::COUNT, "after the scene, along row 14 to column 17"}, + {Direction::EAST, 12, LegEnd::COUNT, "through the tall grass to column 29; the Breeder wanders rows 14 to 16 there"}, + {Direction::EAST, 12, LegEnd::COUNT, "to column 41"}, + {Direction::NORTH, 7, LegEnd::COUNT, "up column 41 to row 7, beside the north-east grass"}, + {Direction::EAST, 1, LegEnd::COUNT, "into the grass"}, + {Direction::NORTH, 2, LegEnd::COUNT, "to row 5"}, + {Direction::EAST, 10, LegEnd::COUNT, "through the grass to (52, 5), its last tile"}, + {Direction::EAST, 11, LegEnd::COUNT, "to (63, 5), the route's last tile"}, + {Direction::EAST, 0, LegEnd::BANNER, "on east into Sandgem Town"}, + }, "Segment00Lines lines 4 and 5, not walked by the program yet; the grass legs need the wild-battle handling of the replay's walk_through_grass(); traced on the Route201 map"}, + {"00.03", "Sandgem Town: Dawn at the entrance", "Sandgem Town", "SandgemTown", true, map_point("SandgemTown", "sandgem_arrival"), { + {Direction::EAST, 4, LegEnd::COUNT, "along row 12 to (4, 12): Dawn's scene, which leads us into Rowan's lab for the Pokedex"}, + {Direction::EAST, 0, LegEnd::SCENE, "the lab is the game's; 00.03 ends in front of Rowan"}, + }, "Segment00Lines line 5, not walked by the program yet; on Sandgem's row 12, where its coord event (zone_event 0396) is"}, + }; +} + +// 01.01 to 01.05: Jubilife to Oreburgh and back out. +std::vector segment01_records_to_oreburgh(){ + return { + {"01.01", "Jubilife Pokemon Center to Barry on Route 203", "Jubilife City", "JubilifeCity", true, std::nullopt, { + {Direction::SOUTH, 0, LegEnd::NPC, "out of the Center's door; a girl below it stops us"}, + {Direction::WEST, 4, LegEnd::COUNT, "stick 720 ms: onto the main road", false}, + {Direction::NORTH, 16, LegEnd::COUNT, "stick 3960 ms: up to the street east to Route 203", false}, + {Direction::SOUTH, 2, LegEnd::COUNT, "stick 600 ms: back onto the street", false}, + {Direction::EAST, 0, LegEnd::NPC, "along the street onto Route 203 until Barry stops us; rows retried 0, +1, +1, -3, -1 when a wall comes first"}, + }, "jubilife_to_barry(); stick holds from the console, 2026-10-29, counted in tiles on the image grid's 3/4 rows: recount in taps before giving this record a start tile (task #21)"}, + {"01.02", "Barry to Oreburgh City through the Oreburgh Gate", "Route 203", "Route203", true, std::nullopt, { + {Direction::EAST, 0, LegEnd::WALL, "along the row Barry stopped us on"}, + {Direction::NORTH, 0, LegEnd::WALL, "to the top wall, then a row south at a time until east goes on (up to ten)"}, + {Direction::EAST, 0, LegEnd::NPC, "to the Hiker"}, + {Direction::EAST, 0, LegEnd::TRANSITION, "into the Oreburgh Gate"}, + {Direction::EAST, 0, LegEnd::TRANSITION, "through the Gate into Oreburgh City"}, + }, "route203_to_oreburgh(); no start tile: Barry stops us on whichever row we came along"}, + {"01.04", "Oreburgh Pokemon Center doorstep to the Gym", "Oreburgh City", "OreburghCity", true, Pokemon::TilePos{47, 21}, { + {Direction::WEST, 21, LegEnd::COUNT, "D-pad taps along the Center's row to below the Gym's door"}, + {Direction::NORTH, 1, LegEnd::DOOR, "into the Gym (the fade)"}, + }, "oreburgh_street_to_gym(); 21 taps; 20 were measured from (46, 21) on the console (r204 to r215, 3 runs on the same tile), and 01.03's heal leaves us below the Center's door (47, 21) (lab-B 2026-11-08 14:51: 20 taps from there ended a tile east of the Gym's door)"}, + {"01.04", "Inside the Oreburgh Gym", "Oreburgh Gym", "OreburghGym", true, map_point("OreburghGym", "entrance"), { + {Direction::NORTH, 0, LegEnd::NPC, "up column 5 from the entrance to Roark on row 3; the Youngsters at (4, 18) and (7, 11) see the column and stop us on rows 18 and 11 on the way"}, + }, "oreburgh_gym_battles(); the Gym's grid from the Diamond decomp (land_data 0228), its trainers and their sight from the events file (zone_event 0046)"}, + {"01.05", "Oreburgh Gym to the Gate and out onto Route 203", "Oreburgh City", "OreburghCity", true, map_point("OreburghCity", "gym_doorstep"), { + {Direction::EAST, 20, LegEnd::COUNT, "D-pad taps from the Gym's doorstep back to the Center's door"}, + {Direction::WEST, 0, LegEnd::WALL, "to the stairs' cliff"}, + {Direction::NORTH, 0, LegEnd::WALL, "along the cliff"}, + {Direction::EAST, 2, LegEnd::COUNT, "to the stairs' column"}, + {Direction::NORTH, 0, LegEnd::WALL, "up the stairs"}, + {Direction::WEST, 0, LegEnd::WALL, "along the platform"}, + {Direction::SOUTH, 1, LegEnd::COUNT, "onto the Gate's row"}, + {Direction::WEST, 0, LegEnd::TRANSITION, "into the Oreburgh Gate (a row probed when a wall comes first)"}, + {Direction::WEST, 0, LegEnd::BANNER, "through the Gate until Route 203's banner"}, + }, "oreburgh_gym_to_center(), oreburgh_to_route203(); the Center visit between the two taps legs is not a walk"}, + }; +} + +// 01.07 to 01.11: Jubilife north to Floaroma. +std::vector segment01_records_from_jubilife(){ + return { + {"01.07", "Jubilife's east edge to Rowan's scene", "Jubilife City", "JubilifeCity", true, std::nullopt, { + {Direction::WEST, 14, LegEnd::COUNT, "stick 2 x 1120 ms along the long road to the crossroads with the north street", false}, + {Direction::NORTH, 0, LegEnd::SCENE, "up the street until Rowan's scene starts (about 6 s); the green-haired man may stand in the way"}, + }, "jubilife_to_rowan(); by hand 2026-10-31 (18 presses), r230b; the stick hold's count was taken on the image grid's 3/4 rows, so no start tile yet"}, + {"01.08", "Jubilife's north street onto Route 204", "Jubilife City", "JubilifeCity", true, std::nullopt, { + {Direction::NORTH, 0, LegEnd::BANNER, "up the street until Route 204's banner; the planned walk to the Ravaged Path door follows"}, + }, "jubilife_to_ravaged_path() step 1"}, + {"01.09", "Ravaged Path's east end out onto Route 204 North", "Ravaged Path", "RavagedPath", true, map_point("RavagedPath", "east_end"), { + {Direction::WEST, 1, LegEnd::COUNT, "onto the tile above the way out"}, + {Direction::SOUTH, 0, LegEnd::TRANSITION, "out of the cave"}, + }, "ravaged_path() exit; the planned legs before it are tested as plans"}, + {"01.10", "Route 204 North's path into Floaroma", "Route 204 North", "Route204North", true, TilePos{11, 5}, { + {Direction::NORTH, 0, LegEnd::BANNER, "from (11, 5) until Floaroma Town's banner; the waypoint line before it is tested as plans"}, + }, "route204_to_floaroma(); r248a"}, + {"01.11", "Floaroma's old couple", "Floaroma Town", "FloaromaTown", true, map_point("FloaromaTown", "route_204_arrival"), { + {Direction::WEST, 8, LegEnd::COUNT, "D-pad taps along the flower field's bottom row"}, + {Direction::NORTH, 0, LegEnd::NPC, "until the old woman stops us (3 tiles on r251a)"}, + {Direction::WEST, 1, LegEnd::COUNT, "below the old man"}, + {Direction::NORTH, 0, LegEnd::NPC, "until the old man stops us (a turn)"}, + }, "floaroma_old_couple(); by hand 2026-10-31 (batches m1 to m9), r251a"}, + }; +} + +} // namespace + +// The walks planned on a grid (00.04 and 00.05's walk_route goals, 01.03's +// Mine legs, 01.06's Route 203 and Jubilife legs, 01.08's Route 204 South, +// 01.09's Ravaged Path, 01.10's waypoints) are data already, tested in +// PokemonBDSP_AutoStory_Tests.cpp; these are the rest. +// +// 00.01 to 00.03 (the house, Twinleaf, Route 201, the Lakefront and the +// lake) still replay the stick inputs Butters recorded for #1717 +// (tutorial_part_1_navigation, entry_visible, tutorial_part_2_navigation, +// starter_nav: timed holds, diagonals among them, and "move until +// transition"), off which no tile count can be read. Their records below +// are the same walks as lines on the decomp grids +// (Data/PokemonBDSP_AutoStory_Segment00Lines, task #22), legs the program +// does not walk yet: a new-game run has to confirm where each scene leaves +// the player before Segment_00 switches to them. The house interiors (the +// player's, Barry's) have no grid and stay replays. +const std::vector& all(){ + static const std::vector records = []{ + std::vector all; + for (auto part : {checkpoint_0001_records, checkpoints_0002_0003_records, segment01_records_to_oreburgh, segment01_records_from_jubilife}){ + const std::vector part_records = part(); + all.insert(all.end(), part_records.begin(), part_records.end()); + } + return all; + }(); + return records; +} + + +} // namespace RouteRecords +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h new file mode 100644 index 0000000000..37105c81d8 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h @@ -0,0 +1,70 @@ +/* BDSP AutoStory - Route records + * + * From: https://github.com/PokemonAutomation/ + * + * Every walk a checkpoint makes that is not planned on a grid, written + * down as legs: the direction, the count or the thing that ends the leg + * (a wall, a person, a door, a location banner, a map transition, a + * scene). The checkpoints run their own code today; these records say + * what that code does, so a test can trace each leg on the map once the + * map is right, and so the next version can run the record instead. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RouteRecords_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RouteRecords_H + +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace RouteRecords{ + + +// What ends a leg. +enum class LegEnd{ + COUNT, // exactly `tiles` tiles (D-pad taps, or a stick hold timed for them) + WALL, // walks until the map stops the player; `tiles` is the expected count, 0 if unknown + NPC, // walks until a person stops the player + DOOR, // walks into a door or cave mouth (a fade) + BANNER, // walks until the next map's location banner shows + TRANSITION, // walks until a map transition (the screen goes dark) + SCENE, // walks until a cutscene takes over +}; + +// Single directional leg within a recorded route with its ending condition. +struct RouteLeg{ + Pokemon::Direction direction; + size_t tiles; + LegEnd end; + std::string note; + // A counted leg walked by D-pad taps (or a leg the map ends) is exact; + // a count from a timed stick hold is an estimate, a tile or two either + // way, until someone counts it on the console in taps. + bool exact = true; +}; + +// Recorded sequence of route legs associated with a story checkpoint. +struct RouteRecord{ + std::string checkpoint; // "01.05" + std::string title; + std::string map; // the map the legs are on + std::string map_file; // that map's JSON map (story_map()) + bool traceable; // the map's tiles are the game's (decomp or console), so legs can be traced + std::optional start; // where the record starts on that map + std::vector legs; + std::string source; // the code and the console runs behind it +}; + +// Returns all defined story route records across checkpoints. +const std::vector& all(); + + +} // namespace RouteRecords +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp new file mode 100644 index 0000000000..4c8b844243 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp @@ -0,0 +1,146 @@ +/* BDSP AutoStory - Segment 00's walked lines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP_AutoStory_StoryMaps.h" +#include "PokemonBDSP_AutoStory_Segment00Lines.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace Segment00Lines{ + +using Pokemon::TilePos; + + + + +// Offsets are the decomp's world coordinates of each map's tile (0, 0): +// the Sinnoh matrix's cells are 32 tiles square, the Lakefront is cell +// (column 2, row 26), Route 201 cells (3..4, 26), Twinleaf (3, 27) and +// Sandgem (5, 26). The Route201 map leaves off the cell's seven wall rows +// at the top, so it starts 7 rows lower; story_map("SandgemTown") is its whole +// cell. +const StoryWorld& segment00_maps(){ + static const StoryWorld maps = []{ + StoryWorld world; + world.add(MAP_TWINLEAF_TOWN, story_map("TwinleafTown"), {96, 864}); + world.add(MAP_ROUTE_201, story_map("Route201"), {96, 839}); + world.add(MAP_VERITY_LAKEFRONT, story_map("VerityLakefront"), {64, 832}); + world.add(MAP_SANDGEM_TOWN, story_map("SandgemTown"), {160, 832}); + return world; + }(); + return maps; +} + + +// From the Diamond decomp's coord events (zone_event narc_0389 Twinleaf, +// 0327 Route 201, 0319 Verity Lakefront, 0396 Sandgem; Lake Verity's +// narc_0298 has none: its scene is the map's own script, run on arrival). +// Each is a rectangle in world tiles with the story variable and value it +// fires at; Platinum's readable events files name the variables and carry +// the same rectangles for Twinleaf and the Lakefront. Listed as local +// tiles of our grids. Not here, having no grid: the player's house's door +// tile (6, 10), where Mom's warning fires on the way out (narc_0392, value +// 1). +const std::vector& scene_triggers(){ + static const std::vector triggers{ + {"Barry's door", MAP_TWINLEAF_TOWN, {9, 12}, 1, 1, + "before Barry has burst out of his house (var 0x40e6 = 0)"}, + {"the guitarist stops us leaving", MAP_TWINLEAF_TOWN, {12, 3}, 8, 1, + "between Barry's door and his talk upstairs (var 0x4070 = 1; 2 after it)"}, + {"Barry's tall-grass warning", MAP_ROUTE_201, {14, 18}, 6, 1, + "the first time north of Twinleaf (var 0x4086 = 0)"}, + {"Route 201's row 19 after the warning", MAP_ROUTE_201, {14, 19}, 6, 1, + "after the warning and before the lake (var 0x4086 = 1); its script is Diamond's binary, not read"}, + {"Rowan and Dawn on the way back", MAP_ROUTE_201, {5, 14}, 1, 3, + "after the lake (var 0x4086 = 2)"}, + {"Barry at the lake's entrance", MAP_VERITY_LAKEFRONT, {16, 12}, 2, 1, + "the first visit (var 0x4082 = 0): he hears Rowan and the two walk into Lake Verity; the same tiles fire again at 3, later in the story"}, + {"Dawn at Sandgem's entrance", MAP_SANDGEM_TOWN, {4, 11}, 1, 5, + "the first time in from Route 201 (var 0x4071 = 0): she leads us to Rowan's lab"}, + }; + return triggers; +} + +bool trigger_covers(const SceneTrigger& trigger, const MapTile& tile){ + return tile.map == trigger.map && + tile.pos.x >= trigger.corner.x && tile.pos.x < trigger.corner.x + trigger.width && + tile.pos.y >= trigger.corner.y && tile.pos.y < trigger.corner.y + trigger.height; +} + + + +// Corners are chosen on the maps' features (a row clear of the houses, +// the exit path, a map's last tile, the tile a scene fires on); where a +// straight run is longer than the planner's 12-tile open leg (the row +// through the Lakefront, the row along Route 201) it is split at the +// twelfth tile. The lower level of Route 201 (rows 13 to 16) is the way +// both to and from the lake: the upper level's ledges only drop onto it. +// Row 16 is used westward and row 14 eastward: on the way out Rowan and +// the counterpart are not yet on (8, 14..15) and Barry is gone from (16, +// 16), but 16 keeps the line one row off the Breeder's range; on the way +// back 14 reaches Rowan's column with the fewest corners. +// +// What a new-game run must confirm before the segment switches to these: +// where each scene leaves the player (Barry's warning and Rowan's scene +// are assumed to leave us on the trigger tile; the lake's scene to warp +// us back onto (17, 12), the right-hand entrance tile, facing south), and +// that the stretches through tall grass are walked with the wild-battle +// handling the replay's walk_through_grass() has, which walk_waypoints() +// does not. +namespace{ +// Corners on each map, and a line from them: parentheses keep the table +// flat enough for the code-health linter's brace limit. +MapTile twinleaf(const TilePos& pos){ return {MAP_TWINLEAF_TOWN, pos}; } +MapTile route201(const TilePos& pos){ return {MAP_ROUTE_201, pos}; } +MapTile lakefront(const TilePos& pos){ return {MAP_VERITY_LAKEFRONT, pos}; } +MapTile sandgem(const TilePos& pos){ return {MAP_SANDGEM_TOWN, pos}; } +// The same, at a named point of the map. +MapTile twinleaf_point(std::string_view point){ return twinleaf(map_point("TwinleafTown", point)); } +MapTile route201_point(std::string_view point){ return route201(map_point("Route201", point)); } +MapTile lakefront_point(std::string_view point){ return lakefront(map_point("VerityLakefront", point)); } +MapTile sandgem_point(std::string_view point){ return sandgem(map_point("SandgemTown", point)); } +WalkedLine walked( + std::string checkpoint, std::string name, std::vector corners, + std::string ends_in, std::vector live_triggers +){ + return {std::move(checkpoint), std::move(name), std::move(corners), std::move(ends_in), std::move(live_triggers)}; +} + +} // namespace + +const std::vector& lines(){ + static const std::vector lines{ + walked("00.01", "the house's doorstep to Barry's door", { + twinleaf_point("house_doorstep"), twinleaf({13, 22}), twinleaf({13, 12}), twinleaf_point("barry_doorstep"), + }, "Barry's door", {"Barry's door"}), + walked("00.01", "Barry's doorstep to Route 201", { + twinleaf_point("barry_doorstep"), twinleaf({15, 12}), twinleaf_point("twinleaf_north_exit"), route201_point("barry_warning"), + }, "Barry's tall-grass warning", {"Barry's tall-grass warning"}), + walked("00.01", "Route 201's west half to the lake's entrance", { + route201_point("barry_warning"), route201({14, 18}), route201({14, 16}), route201({0, 16}), + lakefront({20, 23}), lakefront({20, 21}), lakefront({17, 21}), lakefront_point("lake_entrance"), + }, "Barry at the lake's entrance", {"Barry at the lake's entrance", "Route 201's row 19 after the warning"}), + walked("00.03", "the lake's entrance back to Rowan", { + lakefront_point("lake_entrance"), lakefront({17, 21}), lakefront({29, 21}), route201_point("rowan_stop"), + }, "Rowan and Dawn on the way back", {"Rowan and Dawn on the way back"}), + // Row 13, a row above the Breeder, who wanders (26..28, 14..16): no + // route runs along a wander zone (plan_robust_route()). + walked("00.03", "Rowan to Dawn at Sandgem's entrance", { + route201_point("rowan_stop"), route201({17, 14}), route201({17, 13}), route201({29, 13}), route201({41, 13}), + route201({41, 7}), route201({42, 7}), route201({42, 5}), route201({52, 5}), + route201_point("route_201_east_end"), sandgem_point("dawn_stop"), + }, "Dawn at Sandgem's entrance", {"Dawn at Sandgem's entrance"}), + }; + return lines; +} + +} // namespace Segment00Lines +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h new file mode 100644 index 0000000000..a814de841c --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h @@ -0,0 +1,77 @@ +/* BDSP AutoStory - Segment 00's walked lines + * + * From: https://github.com/PokemonAutomation/ + * + * Checkpoints 00.01 to 00.03 (the house, Twinleaf, Route 201, the Verity + * Lakefront, the lake, and back to Sandgem) replay recorded stick holds + * today. These are the same walks as lines on the maps: corner to corner, + * each stretch one straight leg, ending on the tile that starts the next + * scene. The scenes' trigger rectangles come from the Diamond decomp's + * events files, so a test can show each line steps into its scene on its + * last tile and not before. Nothing runs them on the console yet (task + * #22); the segment keeps its replays until a new-game run has checked + * the lines. + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Segment00Lines_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Segment00Lines_H + +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonBDSP_AutoStory_StoryWorld.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace Segment00Lines{ + + +// Map names in segment00_maps(); Route 201 and Sandgem Town go by +// StoryMaps' MAP_ROUTE_201 and MAP_SANDGEM_TOWN. +inline const std::string MAP_TWINLEAF_TOWN = "Twinleaf Town"; +// Verity Lakefront overworld map name. +inline const std::string MAP_VERITY_LAKEFRONT = "Verity Lakefront"; + +// Twinleaf Town, Route 201, the Verity Lakefront and Sandgem Town joined on +// one grid at their world offsets from the decomp. Lake Verity is not in +// it: its own matrix, and the scene walks us in and the game warps us out, +// so no line is walked there. +const StoryWorld& segment00_maps(); + +// A rectangle of tiles that starts a scene when the player steps in while +// the story is in `when`. From the decomp's coord events, as local tiles. +struct SceneTrigger{ + std::string name; + std::string map; + Pokemon::TilePos corner; // north-west tile + int width; + int height; + std::string when; // the story state it fires in +}; +// Returns all scene trigger zones for Segment 00. +const std::vector& scene_triggers(); +// Returns whether given map tile falls within the scene trigger zone. +bool trigger_covers(const SceneTrigger& trigger, const MapTile& tile); + +// A line walked corner to corner: every stretch between two corners is one +// straight open leg (whole tiles, as the D-pad walks them). +struct WalkedLine{ + std::string checkpoint; + std::string name; + std::vector corners; // the first is where the line starts + std::string ends_in; // the scene the last corner steps into, "" for none + std::vector live_triggers; // the scenes armed while this line is walked +}; +// Returns all pre-defined walked route lines for Segment 00. +const std::vector& lines(); + +// The route records start and end on named points of the maps (Twinleaf +// Town's house_doorstep, Route 201's barry_warning, ...), all on the lines. + + +} // namespace Segment00Lines +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMapNames.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMapNames.h new file mode 100644 index 0000000000..4cada07489 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMapNames.h @@ -0,0 +1,49 @@ +/* BDSP AutoStory - Story map names + * + * From: https://github.com/PokemonAutomation/ + * + * The names the story worlds give their maps. + * + */ +// code-health: allow header_symbols -- one list of every story map's name; splitting it hides which names are taken + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryMapNames_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryMapNames_H + +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Names of the maps in the story worlds (StoryMaps.h). Each is placed from the +// JSON map named without spaces ("Route 201" from Route201.json), except +// MAP_ROUTE_204, which is Route204North.json. +inline const std::string MAP_ROUTE_201 = "Route 201"; +// Sandgem Town overworld map name. +inline const std::string MAP_SANDGEM_TOWN = "Sandgem Town"; +// Route 202 overworld map name. +inline const std::string MAP_ROUTE_202 = "Route 202"; +// Jubilife City overworld map name. +inline const std::string MAP_JUBILIFE_CITY = "Jubilife City"; +// Oreburgh Mine map name. +inline const std::string MAP_OREBURGH_MINE = "Oreburgh Mine"; +// Ravaged Path map name. +inline const std::string MAP_RAVAGED_PATH = "Ravaged Path"; +// Route 204 North map name. +inline const std::string MAP_ROUTE_204 = "Route 204"; +// Route 204 South map name. +inline const std::string MAP_ROUTE_204_SOUTH = "Route 204 South"; +// Route 203 overworld map name. +inline const std::string MAP_ROUTE_203 = "Route 203"; +// Oreburgh City overworld map name. +inline const std::string MAP_OREBURGH_CITY = "Oreburgh City"; +// Floaroma Town overworld map name. +inline const std::string MAP_FLOAROMA_TOWN = "Floaroma Town"; + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp new file mode 100644 index 0000000000..343ce03228 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp @@ -0,0 +1,306 @@ +/* BDSP AutoStory - Story maps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP_AutoStory_StoryMaps.h" +#include "PokemonBDSP_AutoStory_StorySpots.h" +#include "PokemonBDSP_AutoStory_StoryTrainers.h" +#include "PokemonBDSP_AutoStory_TrainerSight.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::Direction; +using Pokemon::MapData; +using Pokemon::TilePos; + + + + +namespace{ + +// One map on its own. +StoryWorld single(std::string_view name, const std::string& json_map){ + StoryWorld world; + world.add(std::string(name), story_map(json_map), {0, 0}); + return world; +} + +// The tiles of `map` from `corner`, `width` x `height`, and the objects on +// them, as a map of its own. Its points are left out. +MapData crop(const MapData& map, const TilePos& corner, int width, int height){ + MapData cropped; + cropped.name = map.name; + cropped.source = map.source; + cropped.tiles = Pokemon::Grid{width, height, {}}; + for (int y = 0; y < height; y++){ + for (int x = 0; x < width; x++){ + cropped.tiles.cells.push_back(map.tiles.at({corner.x + x, corner.y + y})); + } + } + for (Pokemon::MapObject object : map.objects){ + object.x -= corner.x; + object.y -= corner.y; + if (object.wander){ + object.wander->x0 -= corner.x; + object.wander->x1 -= corner.x; + object.wander->y0 -= corner.y; + object.wander->y1 -= corner.y; + } + if (cropped.tiles.contains({object.x, object.y}) || (object.wander + && object.wander->x1 >= 0 && object.wander->y1 >= 0 + && object.wander->x0 < width && object.wander->y0 < height)){ + cropped.objects.push_back(std::move(object)); + } + } + for (auto warp : map.warps){ + warp.x -= corner.x; + warp.y -= corner.y; + if (cropped.tiles.contains({warp.x, warp.y})){ + cropped.warps.push_back(std::move(warp)); + } + } + return cropped; +} + +bool in_region(const std::string& map, const std::string& region, const TilePos& pos){ + const std::vector tiles = map_region(map, region); + return std::find(tiles.begin(), tiles.end(), pos) != tiles.end(); +} + +} // namespace + + +// Offsets are the maps' places in the game's world grid (the decomp's +// cells): Route 201 at world (96,839), Sandgem Town at (160,832), Route 202 +// at (159,800). Route 201's row 4 is Sandgem's row 11, below the doors, and +// Route 202's road comes down off its row 31 onto Sandgem's row 0. +const StoryWorld& story_maps(){ + static const StoryWorld maps = []{ + StoryWorld world; + world.add(MAP_ROUTE_201, story_map("Route201"), {0, 0}); + world.add(MAP_SANDGEM_TOWN, story_map("SandgemTown"), {64, -7}); + world.add(MAP_ROUTE_202, story_map("Route202"), {63, -39}); + return world; + }(); + return maps; +} + +const StoryWorld& jubilife_maps(){ + static const StoryWorld maps = single(MAP_JUBILIFE_CITY, "JubilifeCity"); + return maps; +} + +// Planned one map at a time: Route 203 and Jubilife joined ran for minutes +// without a plan (r224a, 2026-10-31). +const StoryWorld& route203_maps(){ + static const StoryWorld maps = single(MAP_ROUTE_203, "Route203"); + return maps; +} + +bool on_route203_west_line(const TilePos& pos){ + return in_region("Route203", "west_line", pos); +} + +// Columns 42..63, rows 12..25 of Jubilife (world x 170..191, z 748..761), +// as a map of its own: the cut is the map's edge, which no leg may cross +// or stop on, not a wall a plan could walk "to". +namespace{ +const TilePos JUBILIFE_EAST_CORNER{42, 12}; +const int JUBILIFE_EAST_BOTTOM = 25; +} // namespace +const StoryWorld& jubilife_east_maps(){ + static const StoryWorld maps = []{ + const MapData& city = story_map("JubilifeCity"); + StoryWorld world; + world.add(MAP_JUBILIFE_CITY, crop( + city, JUBILIFE_EAST_CORNER, city.tiles.width - JUBILIFE_EAST_CORNER.x, JUBILIFE_EAST_BOTTOM - JUBILIFE_EAST_CORNER.y + 1 + ), {0, 0}); + return world; + }(); + return maps; +} + +// Route 203's road (rows 17..19 of its map) meets Jubilife's east street, +// rows 21..24 of its map, at its east edge; the banner shows a tile or two +// in. In the corner map's tiles. +const std::vector& jubilife_east_entrance(){ + static const std::vector tiles = []{ + std::vector tiles; + for (const TilePos& pos : map_region("JubilifeCity", "east_entrance")){ + tiles.push_back({pos.x - JUBILIFE_EAST_CORNER.x, pos.y - JUBILIFE_EAST_CORNER.y}); + } + return tiles; + }(); + return tiles; +} + +bool on_jubilife_north_road(const TilePos& pos){ + return in_region("JubilifeCity", "north_road", {pos.x + JUBILIFE_EAST_CORNER.x, pos.y + JUBILIFE_EAST_CORNER.y}); +} + +const StoryWorld& oreburgh_mine_maps(){ + static const StoryWorld maps = single(MAP_OREBURGH_MINE, "OreburghMine"); + return maps; +} + +StoryWorld ravaged_path_maps(const std::vector& smashed){ + MapData map = story_map("RavagedPath"); + for (const TilePos& rock : smashed){ + if (map.tiles.contains(rock)){ + Pokemon::cell_at(rock, map.tiles) = Pokemon::TileKind::OPEN; + } + } + StoryWorld maps; + maps.add(MAP_RAVAGED_PATH, map, {0, 0}); + return maps; +} + +const StoryWorld& oreburgh_city_maps(){ + static const StoryWorld maps = single(MAP_OREBURGH_CITY, "OreburghCity"); + return maps; +} + +const StoryWorld& floaroma_maps(){ + static const StoryWorld maps = single(MAP_FLOAROMA_TOWN, "FloaromaTown"); + return maps; +} + +const StoryWorld& route204_north_maps(){ + static const StoryWorld maps = single(MAP_ROUTE_204, "Route204North"); + return maps; +} + +bool in_floaroma_path(const TilePos& pos){ + return in_region("Route204North", "floaroma_path", pos); +} + +const StoryWorld& route204_south_maps(){ + static const StoryWorld maps = single(MAP_ROUTE_204_SOUTH, "Route204South"); + return maps; +} + +bool story_map_plannable(const std::string& map){ + return map == MAP_ROUTE_201 || map == MAP_ROUTE_202; +} + +bool story_at_jubilife_exit(const TilePos& world){ + const std::optional tile = story_maps().to_local(world); + return tile && tile->map == MAP_ROUTE_202 && tile->pos.y <= 3; +} + +std::vector story_save_spots(){ + const StoryWorld& maps = story_maps(); + return { + maps.to_world(MAP_ROUTE_202, map_point("Route202", "catch_spot")), + maps.to_world(MAP_ROUTE_202, map_point("Route202", "save_spot")), + }; +} + +std::vector story_door_front(std::string_view map, const TilePos& door){ + const TilePos below = story_maps().to_world(std::string(map), door.next(Direction::SOUTH)); + return {below.next(Direction::WEST), below, below.next(Direction::EAST)}; +} + +namespace{ +// A region of Route 202, in world tiles of story_maps(). +std::vector route202_region(std::string_view region){ + std::vector tiles; + for (const TilePos& pos : map_region("Route202", region)){ + tiles.push_back(story_maps().to_world(MAP_ROUTE_202, pos)); + } + return tiles; +} +} // namespace + +std::vector story_catch_save_area(){ + return route202_region("catch_save_area"); +} + +std::vector story_after_training_area(){ + return route202_region("after_training_area"); +} + +std::vector story_trainer_sights(){ + std::vector sights = route202_trainer_sights(); + for (TrainerSight& sight : sights){ + sight.pos = story_maps().to_world(MAP_ROUTE_202, sight.pos); + } + return sights; +} + + +// From the events file: each trainer's tile, facing and sight range. +// Natalie challenged us at (22,22), walking east along the row above the +// ledge (r75), the fourth tile of her sight. +std::vector route202_trainer_sights(){ + return { + {.name = "tristan", .pos = map_point("Route202", "trainer_tristan"), .facing = Direction::SOUTH, .range = 5}, + {.name = "natalie", .pos = map_point("Route202", "trainer_natalie"), .facing = Direction::SOUTH, .range = 4}, + {.name = "logan", .pos = map_point("Route202", "trainer_logan"), .facing = Direction::SOUTH, .range = 5}, + }; +} + +std::vector route204_north_trainer_sights(){ + const auto at = [](std::string_view point){ return map_point("Route204North", point); }; + return { + {.name = "Twins (left)", .pos = at("trainer_twin_left"), .facing = Direction::SOUTH, .range = 3}, + {.name = "Twins (right)", .pos = at("trainer_twin_right"), .facing = Direction::SOUTH, .range = 4}, + {.name = "Aroma Lady Taylor", .pos = at("trainer_taylor"), .facing = Direction::SOUTH, .range = 4}, + {.name = "Aroma Lady Taylor", .pos = at("trainer_taylor"), .facing = Direction::EAST, .range = 4}, + // Bug Catcher Brandon paces east and west below the flower beds + // and stopped us on row 12 (r246a: "Say, what's your opinion on bug + // Pokemon?"); the DP map draws him at (20, 12), Platinum's data + // has him at (22, 13). The tile is a guess until a shot fixes it. + {.name = "Bug Catcher Brandon", .pos = at("trainer_brandon"), .facing = Direction::WEST, .range = 4}, + {.name = "Bug Catcher Brandon", .pos = at("trainer_brandon"), .facing = Direction::EAST, .range = 4}, + }; +} + +// Sarah turns between north and east; her east line crosses the street's +// columns, so a walk north meets it or not by luck (r233a passed, r234a +// fought). The planner cannot avoid it: she is listed so the route knows +// whom it may meet, with the range that fits. +std::vector route204_south_trainer_sights(){ + const auto at = [](std::string_view point){ return map_point("Route204South", point); }; + return { + {.name = "Lass Samantha", .pos = at("trainer_samantha"), .facing = Direction::SOUTH, .range = 4}, + {.name = "Lass Sarah", .pos = at("trainer_sarah"), .facing = Direction::NORTH, .range = 4}, + {.name = "Lass Sarah", .pos = at("trainer_sarah"), .facing = Direction::EAST, .range = 4}, + {.name = "Youngster Tyler", .pos = at("trainer_tyler"), .facing = Direction::EAST, .range = 4}, + {.name = "Youngster Tyler", .pos = at("trainer_tyler"), .facing = Direction::WEST, .range = 4}, + }; +} + +// Both see the middle column, so a walk north from the entrance is +// stopped twice before Roark (01.04's record). +std::vector oreburgh_gym_trainer_sights(){ + return { + {.name = "Youngster (first tier)", .pos = map_point("OreburghGym", "trainer_first_tier"), .facing = Direction::EAST, .range = 3}, + {.name = "Youngster (second tier)", .pos = map_point("OreburghGym", "trainer_second_tier"), .facing = Direction::WEST, .range = 4}, + }; +} + +std::vector route204_south_tiles_to_avoid(){ + std::vector tiles; + for (const TrainerSight& trainer : route204_south_trainer_sights()){ + if (trainer.name == "Lass Sarah" && trainer.facing == Direction::EAST){ + continue; + } + for (const TilePos& pos : sight_tiles(route204_south_maps(), trainer)){ + tiles.push_back(pos); + } + } + return tiles; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h new file mode 100644 index 0000000000..7b5855cd4a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h @@ -0,0 +1,80 @@ +/* BDSP AutoStory - Story maps + * + * From: https://github.com/PokemonAutomation/ + * + * The maps the story walks through, joined into story worlds, and the + * lines and entrances on them that the story's plans end at. The tiles + * and named points come from the JSON maps (PokemonBDSP_AutoStory_Maps.h); + * where the maps sit relative to each other the maps do not say, so it is + * here. Spots and trainers on the maps: StorySpots.h, StoryTrainers.h. + */ +// code-health: allow header_symbols -- each story map's world sits next to the lines and entrances on it that its plans end at + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryMaps_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryMaps_H + +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonBDSP_AutoStory_StoryMapNames.h" +#include "PokemonBDSP_AutoStory_StoryWorld.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Route 201, Sandgem Town and Route 202. +const StoryWorld& story_maps(); + +// Jubilife City on its own: 00.05 starts there after Dawn's scene, so it is +// not joined to Route 202. +const StoryWorld& jubilife_maps(); +// Route 203 on its own (01.06), and whether a tile is on row 18 between the +// two cliffs: row 18 runs straight west from there under the west cliff +// into Jubilife, so the plan ends there (no leg may leave the map) and a +// walk west until Jubilife's banner shows goes on from there. +const StoryWorld& route203_maps(); +// Returns whether given tile lies on the west line towards Jubilife. +bool on_route203_west_line(const Pokemon::TilePos& pos); +// Jubilife City's north-east corner (01.06), at its own tile coordinates: +// the rest of the city is walled off, so the plan searches only the part +// the walk needs. Where Route 203's road enters it, and whether a tile is +// on the north road below the plaza: walking north from there goes up the +// road to Route 204 (and Rowan's scene). +const StoryWorld& jubilife_east_maps(); +// Returns entrance coordinates for east entrance of Jubilife. +const std::vector& jubilife_east_entrance(); +// Returns whether given tile lies on the north road towards Route 204. +bool on_jubilife_north_road(const Pokemon::TilePos& pos); +// The Oreburgh Mine's coal room on its own (01.03). +const StoryWorld& oreburgh_mine_maps(); + +// The Ravaged Path on its own (01.05), with the rocks in `smashed` open. +StoryWorld ravaged_path_maps(const std::vector& smashed = {}); + +// Route 204's north half on its own (01.05), and whether a tile is on the +// path north into Floaroma. +const StoryWorld& route204_north_maps(); +// Returns whether given tile lies within the Floaroma entrance path. +bool in_floaroma_path(const Pokemon::TilePos& pos); + +// Route 204's south half on its own (01.08): it joins the north half only +// through the Ravaged Path, so the two are separate maps. +const StoryWorld& route204_south_maps(); + +// Oreburgh City alone (01.04, 01.05), and Floaroma Town alone (01.11). +const StoryWorld& oreburgh_city_maps(); +// Returns StoryWorld instance containing Floaroma Town alone. +const StoryWorld& floaroma_maps(); + +// Whether a plan may cross this map. Towns are crossed by screen-driven +// legs until the console has confirmed their maps. +bool story_map_plannable(const std::string& map); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StorySpots.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StorySpots.h new file mode 100644 index 0000000000..8b68450d3a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StorySpots.h @@ -0,0 +1,53 @@ +/* BDSP AutoStory - Story spots + * + * From: https://github.com/PokemonAutomation/ + * + * Spots on the Route 201 to Route 202 world (story_maps()) where + * segment 00's walks start, save and end, in world tiles. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StorySpots_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StorySpots_H + +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// The open rows at the top of Route 202, in world tiles: walking north from +// any of them enters Jubilife City. +bool story_at_jubilife_exit(const Pokemon::TilePos& world); + +// Where the post-catch half of 00.04 may start, in world tiles: the catch +// spot (00.03 saves there after the catch) and the save spot under the +// ledge (00.04 saves there once it has Potions, before Route 202's trainers). +std::vector story_save_spots(); + +// Where 00.04b's save after the catch may stand, in world tiles: wherever +// the catch's walks in the grass ended, the patch (15..20, 25..27) and the +// lawn column east of it, (21, 25..29), down to the pocket behind the tree +// row where r252's catch ended and saved (the save loads there: (21, 29) +// by the screen, the 202 sign 3 columns right and 4 rows up). +std::vector story_catch_save_area(); + +// Where a walk out of the door `door` of `map` may leave us, in world tiles: +// the tile below it and its neighbours either side, since the door opening +// is not lined up with one tile (Jubilife's Center, r85). +std::vector story_door_front(std::string_view map, const Pokemon::TilePos& door); + +// Where we may stand after training in the catch grass, in world tiles: the +// training walks up and down the catch spot's column, between the tree walls +// north and south of the grass, so a battle may stop us on any of its +// three rows. A column either side allows for where the catch left us. +std::vector story_after_training_area(); + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryTrainers.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryTrainers.h new file mode 100644 index 0000000000..f2a6becb64 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryTrainers.h @@ -0,0 +1,43 @@ +/* BDSP AutoStory - Story trainers + * + * From: https://github.com/PokemonAutomation/ + * + * The trainers on the story maps, with the sight ranges that fit the + * console: the maps do not say how far a trainer sees. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryTrainers_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryTrainers_H + +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonBDSP_AutoStory_TrainerSight.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Route 202's trainers, in world tiles of story_maps(). +std::vector story_trainer_sights(); + +// The trainers of a map, in its own tiles, with the sight ranges that fit +// the console. A trainer who looks two ways is listed once per way. +std::vector route202_trainer_sights(); +// Returns trainer sights for Route 204 North. +std::vector route204_north_trainer_sights(); +// Returns trainer sights for Route 204 South. +std::vector route204_south_trainer_sights(); +// Returns trainer sights for Oreburgh Gym. +std::vector oreburgh_gym_trainer_sights(); + +// Route 204 South's tiles in the trainers' sight that a walk can avoid: +// all but Sarah's east line, which crosses the street (see the sights). +std::vector route204_south_tiles_to_avoid(); + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp new file mode 100644 index 0000000000..d6f7a67b80 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp @@ -0,0 +1,350 @@ +/* BDSP AutoStory - Story world + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "PokemonBDSP_AutoStory_StoryWorld.h" +#include "PokemonBDSP_AutoStory_WalkRules.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::Direction; +using Pokemon::TileKind; +using Pokemon::TilePos; + + +namespace{ + +// The way a ledge is hopped, or nothing for any other tile. +std::optional ledge_direction(TileKind tile){ + switch (tile){ + case TileKind::LEDGE_NORTH: + return Direction::NORTH; + case TileKind::LEDGE_SOUTH: + return Direction::SOUTH; + case TileKind::LEDGE_WEST: + return Direction::WEST; + case TileKind::LEDGE_EAST: + return Direction::EAST; + case TileKind::WALL: + case TileKind::OPEN: + case TileKind::TALL_GRASS: + case TileKind::WATER: + case TileKind::DOOR: + case TileKind::SIGN: + case TileKind::OUTSIDE: + case TileKind::CLOSED_NORTH: + case TileKind::CLOSED_SOUTH: + case TileKind::CLOSED_WEST: + case TileKind::CLOSED_EAST: + return std::nullopt; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown TileKind."); +} + +} // namespace + + +void StoryWorld::add(std::string name, const Pokemon::MapData& map, const TilePos& offset){ + for (const Placed& placed : m_maps){ + if (placed.name == name){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Map placed twice: " + name); + } + } + Placed placed{.name = std::move(name), .tiles = map.tiles, .occupied = {}, .wander = {}, .warps = {}, .offset = offset}; + for (const Pokemon::MapObject& object : map.objects){ + if (!object.wander){ + placed.occupied.push_back({object.x, object.y}); + }else{ + placed.wander.push_back(*object.wander); + } + } + for (const auto& warp : map.warps){ + placed.warps.push_back({warp.x, warp.y}); + } + check_overlap(placed); + m_maps.push_back(std::move(placed)); + rebuild(); +} + +// Map images show a border of trees past their edges, so two maps may +// share walls with nobody on them, but nothing else. +std::optional StoryWorld::conflict(const Placed& map, const Placed& placed){ + const auto free_wall = [](const Placed& in, const TilePos& pos){ + return in.tiles.at(pos) == TileKind::WALL && + std::find(in.occupied.begin(), in.occupied.end(), pos) == in.occupied.end(); + }; + for (int y = 0; y < map.tiles.height; y++){ + for (int x = 0; x < map.tiles.width; x++){ + const TilePos other{map.offset.x + x - placed.offset.x, map.offset.y + y - placed.offset.y}; + if (placed.tiles.contains(other) && (!free_wall(map, {x, y}) || !free_wall(placed, other))){ + return TilePos{x, y}; + } + } + } + return std::nullopt; +} + +void StoryWorld::check_overlap(const Placed& map) const{ + for (const Placed& placed : m_maps){ + if (const std::optional at = conflict(map, placed)){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format( + "Map {} overlaps {} at its tile {}.", map.name, placed.name, Pokemon::to_string(*at) + )); + } + } +} + +void StoryWorld::rebuild(){ + TilePos low = m_maps[0].offset; + TilePos high = low; + for (const Placed& placed : m_maps){ + low.x = std::min(low.x, placed.offset.x); + low.y = std::min(low.y, placed.offset.y); + high.x = std::max(high.x, placed.offset.x + placed.tiles.width); + high.y = std::max(high.y, placed.offset.y + placed.tiles.height); + } + // Block and uncover lists are in world tiles of the old origin. + const TilePos shift{m_origin.x - low.x, m_origin.y - low.y}; + for (std::vector* list : {&m_blocked, &m_uncovered}){ + for (TilePos& pos : *list){ + pos = {pos.x + shift.x, pos.y + shift.y}; + } + } + m_origin = low; + m_cells = Pokemon::Grid{high.x - low.x, high.y - low.y, {}}; + m_cells.cells.resize((size_t)m_cells.width * m_cells.height); + for (auto iter = m_maps.rbegin(); iter != m_maps.rend(); ++iter){ + paint(*iter, {iter->offset.x - low.x, iter->offset.y - low.y}); + } + for (const TilePos& pos : m_blocked){ + if (Cell* blocked = cell(pos)){ + blocked->occupant = BLOCKED; + } + } + for (const TilePos& pos : m_uncovered){ + if (Cell* uncovered = cell(pos)){ + uncovered->covered = false; + } + } +} + +void StoryWorld::paint(const Placed& placed, const TilePos& corner){ + for (int y = 0; y < placed.tiles.height; y++){ + for (int x = 0; x < placed.tiles.width; x++){ + Pokemon::cell_at({corner.x + x, corner.y + y}, m_cells) = Cell{true, placed.tiles.at({x, y}), NOBODY}; + } + } + for (const TilePos& pos : placed.occupied){ + Pokemon::cell_at({corner.x + pos.x, corner.y + pos.y}, m_cells).occupant = PERSON; + } + for (const auto& box : placed.wander){ + for (int y = std::max(0, box.y0); y <= std::min(placed.tiles.height - 1, box.y1); y++){ + for (int x = std::max(0, box.x0); x <= std::min(placed.tiles.width - 1, box.x1); x++){ + Cell& c = Pokemon::cell_at({corner.x + x, corner.y + y}, m_cells); + c.recovery_hazard = true; + c.wander_hazard = true; + } + } + } + for (const auto& warp : placed.warps){ + if (placed.tiles.contains(warp)){ + Pokemon::cell_at({corner.x + warp.x, corner.y + warp.y}, m_cells).recovery_hazard = true; + } + } +} + +const StoryWorld::Cell* StoryWorld::cell(const TilePos& pos) const{ + if (!m_cells.contains(pos) || !m_cells.at(pos).covered){ + return nullptr; + } + return &m_cells.at(pos); +} +StoryWorld::Cell* StoryWorld::cell(const TilePos& pos){ + if (!m_cells.contains(pos) || !m_cells.at(pos).covered){ + return nullptr; + } + return &Pokemon::cell_at(pos, m_cells); +} + + +std::optional StoryWorld::tile(const TilePos& pos) const{ + const Cell* found = cell(pos); + if (found == nullptr){ + return std::nullopt; + } + return found->tile; +} + +StoryWorld::Occupant StoryWorld::occupied(const TilePos& pos, OccupancyUse use) const{ + const Cell* found = cell(pos); + if (found && use == OccupancyUse::WALL_RECOVERY && found->recovery_hazard){ + return PERSON; + } + return found == nullptr ? NOBODY : found->occupant; +} + +namespace{ + +void add_box_tiles(std::vector& out, const TilePos& corner, const Pokemon::TileBox& box, int max_w, int max_h){ + const int y0 = std::max(0, box.y0); + const int y1 = std::min(max_h - 1, box.y1); + const int x0 = std::max(0, box.x0); + const int x1 = std::min(max_w - 1, box.x1); + for (int y = y0; y <= y1; y++){ + for (int x = x0; x <= x1; x++){ + out.push_back({corner.x + x, corner.y + y}); + } + } +} + +} // namespace + +std::vector wandering_hazards(const StoryWorld& world){ + std::vector result; + for (const auto& placed : world.m_maps){ + const TilePos corner{placed.offset.x - world.m_origin.x, placed.offset.y - world.m_origin.y}; + for (const auto& box : placed.wander){ + add_box_tiles(result, corner, box, placed.tiles.width, placed.tiles.height); + } + } + std::sort(result.begin(), result.end(), [](const TilePos& a, const TilePos& b){ + if (a.y != b.y){ + return a.y < b.y; + } + return a.x < b.x; + }); + result.erase(std::unique(result.begin(), result.end()), result.end()); + return result; +} + +bool wandering_hazard(const StoryWorld& world, const TilePos& pos){ + const StoryWorld::Cell* found = world.cell(pos); + return found != nullptr && found->wander_hazard; +} + +bool recovery_hazard(const StoryWorld& world, const TilePos& pos){ + const StoryWorld::Cell* found = world.cell(pos); + return found != nullptr && found->recovery_hazard; +} + +void StoryWorld::block(const TilePos& pos){ + if (Cell* found = cell(pos)){ + found->occupant = BLOCKED; + m_blocked.push_back(pos); + } +} + +void StoryWorld::uncover(const TilePos& pos){ + if (Cell* found = cell(pos)){ + found->covered = false; + m_uncovered.push_back(pos); + } +} + + +TilePos StoryWorld::to_world(const std::string& map, const TilePos& local) const{ + for (const Placed& placed : m_maps){ + if (placed.name == map){ + return {placed.offset.x - m_origin.x + local.x, placed.offset.y - m_origin.y + local.y}; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown map: " + map); +} + +std::optional StoryWorld::to_local(const TilePos& world) const{ + for (const Placed& placed : m_maps){ + const TilePos local{world.x + m_origin.x - placed.offset.x, world.y + m_origin.y - placed.offset.y}; + if (placed.tiles.contains(local)){ + return MapTile{placed.name, local}; + } + } + return std::nullopt; +} + + + +bool covered(const StoryWorld& world, const TilePos& pos){ + return world.tile(pos).has_value(); +} + +bool standable(const StoryWorld& world, const TilePos& pos){ + const std::optional tile = world.tile(pos); + return tile && (*tile == TileKind::OPEN || *tile == TileKind::TALL_GRASS) && !world.occupied(pos); +} + +std::optional step(const StoryWorld& world, const TilePos& from, Direction direction){ + const TilePos next = from.next(direction); + if (standable(world, next)){ + return next; + } + const std::optional tile = world.tile(next); + if (!tile || world.occupied(next) || ledge_direction(*tile) != direction){ + return std::nullopt; + } + const TilePos landing = next.next(direction); + if (standable(world, landing)){ + return landing; + } + return std::nullopt; +} + +std::vector leg_path(const StoryWorld& grid, TilePos from, Direction direction, size_t tiles){ + std::vector path; + size_t travelled = 0; + while (travelled < tiles){ + const std::optional next = step(grid, from, direction); + if (!next){ + break; + } + travelled += std::abs(next->x - from.x) + std::abs(next->y - from.y); + from = *next; + path.push_back(from); + } + return path; +} + +bool warp_within(const StoryWorld& world, const std::vector& from, Direction direction, size_t reach){ + for (TilePos pos : from){ + for (size_t i = 0; i < reach; i++){ + if (world.tile(pos.next(direction)) == TileKind::DOOR){ + return true; + } + const std::optional next = step(world, pos, direction); + if (!next){ + break; + } + pos = *next; + } + } + return false; +} + +// Someone standing in the way stops us too, but is no wall to stop against: +// they may turn and talk, or walk off (r29 ran east into Mom, who talked). +bool at_wall(const StoryWorld& world, const TilePos& pos, Direction direction){ + const std::optional next = world.tile(pos.next(direction)); + return next && *next != TileKind::DOOR && world.occupied(pos.next(direction)) != StoryWorld::PERSON && + !step(world, pos, direction).has_value(); +} + +std::string describe(const StoryWorld& world, const TilePos& pos){ + const std::optional local = world.to_local(pos); + if (!local){ + return "world " + Pokemon::to_string(pos); + } + return local->map + " " + Pokemon::to_string(local->pos); +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h new file mode 100644 index 0000000000..cf46b6f0c5 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h @@ -0,0 +1,128 @@ +/* BDSP AutoStory - Story world + * + * From: https://github.com/PokemonAutomation/ + * + * Several story maps placed side by side on one world grid, so one plan can + * cross from a route into a town. What the tiles mean for walking in BDSP: + * open ground and tall grass are stood on; a ledge is hopped the arrow's + * way; walls, water and signs stop the player; a door is walked into. A + * person or an item standing still blocks their tile; a wanderer does not + * (the walker waits for them). Tiles no map covers are off the maps: a + * plan may not end there, but walking into one is not a wall, since it may + * be an exit. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryWorld_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryWorld_H + +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "Pokemon/Navigation/Pokemon_MapData.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// A tile of one of the maps, in that map's own coordinates. +struct MapTile{ + std::string map; + Pokemon::TilePos pos; +}; + + +// Composite coordinate space combining multiple contiguous maps into one +// traversable overworld representation. +class StoryWorld{ +public: + // Places `map` under `name` with its tile (0,0) at `offset`. Offsets are + // relative to each other and may be negative. Maps may overlap only + // where both are walls with nobody on them; the map placed first holds + // those tiles. Throws InternalProgramError if the name is taken or the + // maps conflict. World tile (0,0) is the top-left corner of all the + // maps together. + void add(std::string name, const Pokemon::MapData& map, const Pokemon::TilePos& offset); + + // The tile, or nothing off the maps. + std::optional tile(const Pokemon::TilePos& pos) const; + // Who or what stands still on a tile: one of the maps' people, or a + // tile blocked with block(). NOBODY is false, the others true. + enum Occupant{ + NOBODY = 0, + PERSON, + BLOCKED, + }; + // Recovery also excludes wandering areas and declared warps. + enum class OccupancyUse{ MOVEMENT, WALL_RECOVERY }; + Occupant occupied(const Pokemon::TilePos& pos, OccupancyUse use = OccupancyUse::MOVEMENT) const; + + // Blocks a tile found in the way on the console. Tiles off the maps + // are left alone. + void block(const Pokemon::TilePos& pos); + // Takes a tile off the maps: a tile a walk must not cross or stop on + // that the game lets us walk (a trainer's line of sight). + void uncover(const Pokemon::TilePos& pos); + + // Throws InternalProgramError for a map name it does not have. + Pokemon::TilePos to_world(const std::string& map, const Pokemon::TilePos& local) const; + // The map that holds a world tile, or nothing between maps. + std::optional to_local(const Pokemon::TilePos& world) const; + + friend std::vector wandering_hazards(const StoryWorld& world); + friend bool wandering_hazard(const StoryWorld& world, const Pokemon::TilePos& pos); + friend bool recovery_hazard(const StoryWorld& world, const Pokemon::TilePos& pos); + +private: + struct Placed{ + std::string name; + Pokemon::Grid tiles; + std::vector occupied; // local tiles + std::vector wander; // recovery hazards, not terrain + std::vector warps; + Pokemon::TilePos offset; + }; + struct Cell{ + bool covered = false; + Pokemon::TileKind tile = Pokemon::TileKind::WALL; + Occupant occupant = NOBODY; + bool recovery_hazard = false; + bool wander_hazard = false; + }; + + void check_overlap(const Placed& map) const; + // The first tile of `map` that `placed` holds as anything but a wall + // with nobody on it, or nothing. + static std::optional conflict(const Placed& map, const Placed& placed); + void rebuild(); + void paint(const Placed& placed, const Pokemon::TilePos& corner); + const Cell* cell(const Pokemon::TilePos& pos) const; + Cell* cell(const Pokemon::TilePos& pos); + + std::vector m_maps; + Pokemon::TilePos m_origin; // offset of world tile (0,0) + Pokemon::Grid m_cells; + std::vector m_blocked; // world tiles, kept across add() + std::vector m_uncovered; +}; + + +// The rules of walking on a story world, from its tiles. + +// All tiles where someone wanders on the maps, in world coordinates. +std::vector wandering_hazards(const StoryWorld& world); +// Whether a world tile is within a wandering hazard box. +bool wandering_hazard(const StoryWorld& world, const Pokemon::TilePos& pos); +// Whether a world tile is a recovery hazard (wander box or warp). +bool recovery_hazard(const StoryWorld& world, const Pokemon::TilePos& pos); +// "Route 201 (45, 3)", or "world (x, y)" if no map holds it. +std::string describe(const StoryWorld& world, const Pokemon::TilePos& pos); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TrainerSight.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TrainerSight.h new file mode 100644 index 0000000000..30f9130372 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TrainerSight.h @@ -0,0 +1,47 @@ +/* BDSP AutoStory - Trainer sight + * + * From: https://github.com/PokemonAutomation/ + * + * Which tiles a trainer sees, and which legs of a walk cross them. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_TrainerSight_H +#define PokemonAutomation_PokemonBDSP_AutoStory_TrainerSight_H + +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP_AutoStory_StoryWorld.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// A trainer sees the tiles in a straight line in front of them, up to +// `range` tiles or the first tile the player cannot stand on. The maps +// have no sight ranges, so story code lists them. +struct TrainerSight{ + std::string name; + Pokemon::TilePos pos; + Pokemon::Direction facing = Pokemon::Direction::NORTH; + int range = 4; +}; +// Computes straight line-of-sight tiles for a trainer. +std::vector sight_tiles(const StoryWorld& world, const TrainerSight& trainer); + +// For each leg, the trainers whose sight line it enters. +std::vector> legs_crossing_sight( + const StoryWorld& world, + const Pokemon::TilePos& from, + const std::vector& legs, + const std::vector& trainers +); + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WalkRules.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WalkRules.h new file mode 100644 index 0000000000..d6a5c6f90a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WalkRules.h @@ -0,0 +1,46 @@ +/* BDSP AutoStory - Walk rules + * + * From: https://github.com/PokemonAutomation/ + * + * Where the player can stand and step on a story world, from its tiles. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_WalkRules_H +#define PokemonAutomation_PokemonBDSP_AutoStory_WalkRules_H + +#include +#include +#include +#include "Pokemon/Navigation/Pokemon_Grid.h" +#include "PokemonBDSP_AutoStory_StoryWorld.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Whether a map holds this world tile. +bool covered(const StoryWorld& world, const Pokemon::TilePos& pos); +// Whether the player can stand on this tile. +bool standable(const StoryWorld& world, const Pokemon::TilePos& pos); +// Where one step from `from` lands, or nothing if the player is stopped. +// A step onto a ledge the arrow's way hops to the tile past it. +std::optional step(const StoryWorld& world, const Pokemon::TilePos& from, Pokemon::Direction direction); +// Whether a step from `pos` is refused by a tile that holds the player +// in place. Doors and tiles off the maps are not walls: walking into a +// door enters the building, and ground off the maps may be an exit. +bool at_wall(const StoryWorld& world, const Pokemon::TilePos& pos, Pokemon::Direction direction); +// The tiles the player passes when walking `tiles` tiles from `from`, the +// first one after `from` first. Stops early where the player is stopped. +std::vector leg_path(const StoryWorld& grid, Pokemon::TilePos from, Pokemon::Direction direction, size_t tiles); +// Whether a warp (a door's tile) lies within `reach` tiles `direction` of +// one of `from`, nothing stopping the player before it: where a walk that +// ran on past its leg's end may have gone through (#268 slice 2). +bool warp_within(const StoryWorld& world, const std::vector& from, Pokemon::Direction direction, size_t reach); + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp new file mode 100644 index 0000000000..b26f8caf51 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp @@ -0,0 +1,165 @@ +/* BDSP Wall Recovery + * + * From: https://github.com/PokemonAutomation/ + */ +#include +#include "PokemonBDSP_AutoStory_RobustRoute.h" +#include "PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP_AutoStory_WalkRules.h" +#include "PokemonBDSP_AutoStory_WallRecovery.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +namespace{ + +using Pokemon::Direction; +using Pokemon::TilePos; + +// A wall ray must stay on the same map and walk one tile per step. A +// ledge may be legal travel but must not become a localization anchor. +std::optional safe_wall(const StoryWorld& world, TilePos from, Direction direction){ + const auto map = world.to_local(from); + if (!map || !standable(world, from) + || world.occupied(from, StoryWorld::OccupancyUse::WALL_RECOVERY) == StoryWorld::PERSON){ + return std::nullopt; + } + const WallHit wall = slide_to_wall(world, from, direction); + if (!wall.anchored + || world.occupied(wall.wall, StoryWorld::OccupancyUse::WALL_RECOVERY) == StoryWorld::PERSON){ + return std::nullopt; + } + while (from != wall.stop){ + const auto next = step(world, from, direction); + const auto local = next ? world.to_local(*next) : std::nullopt; + if (!next || *next != from.next(direction) || !local || local->map != map->map + || world.occupied(*next, StoryWorld::OccupancyUse::WALL_RECOVERY) == StoryWorld::PERSON){ + return std::nullopt; + } + from = *next; + } + return wall; +} + +class WallPolicy{ +public: + using Hypothesis = TilePos; + using Position = TilePos; + using Hold = TileLeg; + + static Position position(const Hypothesis& at){ return at; } + static int tiles(const Hold& hold){ return (int)hold.tiles; } + static std::optional> hold( + const StoryWorld& world, const std::vector& from, Direction direction + ){ + std::vector ends; + size_t longest = 0; + for (const auto& start : from){ + const auto wall = safe_wall(world, start, direction); + if (!wall){ + return std::nullopt; + } + longest = std::max(longest, wall->tiles); + if (std::find(ends.begin(), ends.end(), wall->stop) == ends.end()){ + ends.push_back(wall->stop); + } + } + return Pokemon::WallRecoveryStep{ + .positions = std::move(ends), + .hold = {.direction = direction, .tiles = longest, .ends_at_wall = true}, + }; + } + +}; + +} // namespace + +std::vector> wall_recovery_candidates( + const StoryWorld& world, const std::vector& from, + const Pokemon::WallRecoveryLimits& limits +){ + for (const auto& tile : from){ + if (!standable(world, tile)){ + return {}; + } + } + return Pokemon::find_wall_anchors(from, world, limits); +} + +std::vector interrupted_leg_positions( + const StoryWorld& world, const std::vector& from, Direction direction, size_t tiles +){ + std::vector positions; + for (TilePos at : from){ + for (size_t count = 0; count <= tiles; count++){ + if (std::find(positions.begin(), positions.end(), at) == positions.end()){ + positions.push_back(at); + } + const auto next = step(world, at, direction); + if (count == tiles || !next){ + break; + } + at = *next; + } + } + return positions; +} + +namespace{ +std::vector recovery_legs( + const StoryWorld& world, std::vector from, const std::vector& holds +){ + std::vector legs; + for (const auto& hold : holds){ + std::vector after; + for (const auto& at : from){ + const TilePos end = slide_to_wall(world, at, hold.direction).stop; + if (std::find(after.begin(), after.end(), end) == after.end()){ + after.push_back(end); + } + } + legs.push_back({.leg = hold, .after = after}); + from = std::move(after); + } + return legs; +} +} // namespace + +std::optional> plan_recovered_route( + const StoryWorld& world, const std::vector& from, + const std::function& goal, const RobustPlanCosts& costs +){ + if (from.empty()){ + return std::nullopt; + } + if (std::all_of(from.begin(), from.end(), goal)){ + return std::vector(); + } + if (from.size() == 1){ + return plan_robust_route(world, from, goal, costs); + } + // The cheapest whole walk, holds and the way on from the wall: the + // fewest held tiles alone chose "south 12 (to wall), north 12 (open)" + // over "north 13 (to wall), south 5 (open)" for 01.10's line 5 (lab-B + // 2026-11-08 18:15:47). Ties keep find_wall_anchors()' order. + std::optional> best; + long long best_cost = 0; + for (const auto& anchor : wall_recovery_candidates(world, from)){ + const auto back = plan_robust_route(world, std::vector{anchor.at}, goal, costs); + if (!back){ + continue; + } + auto route = recovery_legs(world, from, anchor.holds); + route.insert(route.end(), back->begin(), back->end()); + const long long cost = robust_route_cost(world, from, route, costs); + if (!best || cost < best_cost){ + best = std::move(route); + best_cost = cost; + } + } + return best; +} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h new file mode 100644 index 0000000000..fbf95a6f2a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h @@ -0,0 +1,47 @@ +/* BDSP Wall Recovery + * + * From: https://github.com/PokemonAutomation/ + * + * BDSP's movement adapter for shared native wall convergence. Predictions + * do not confirm controller execution; the walker must establish arrival. + */ +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_WallRecovery_H +#define PokemonAutomation_PokemonBDSP_AutoStory_WallRecovery_H + +#include "Pokemon/Navigation/Pokemon_WallRecovery.h" +#include "PokemonBDSP_AutoStory_RobustRoute.h" +#include "PokemonBDSP_AutoStory_RoutePlanner.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +// Safe holds for every possible position, within one explicitly placed map. +// Never anchors against a person, crosses a door/map edge or hops a ledge. +// Caller must uncover trainer sight/scene hazards absent from StoryWorld. +std::vector> wall_recovery_candidates( + const StoryWorld& world, const std::vector& from, + const Pokemon::WallRecoveryLimits& limits = Pokemon::WallRecoveryLimits() +); + +// Every legal prefix, including zero movement, of an interrupted counted leg. +std::vector interrupted_leg_positions( + const StoryWorld& world, const std::vector& from, + Pokemon::Direction direction, size_t tiles +); + +// Establish a common wall anchor before continuing from an uncertain pose. +// Single positions retain the existing planner. Ambiguous positions without +// a safe anchor fail instead of choosing one. Goals already held need no walk. +// Of the anchors, the one whose whole walk, holds and the way on to the +// goal, costs least (robust_route_cost()). +std::optional> plan_recovered_route( + const StoryWorld& world, const std::vector& from, + const std::function& goal, + const RobustPlanCosts& costs +); + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp new file mode 100644 index 0000000000..6c055847d0 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp @@ -0,0 +1,323 @@ +/* BDSP AutoStory Route Planner Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The route planner (Data/PokemonBDSP_AutoStory_RoutePlanner.h) on small + * synthetic maps: walks to a wall, plans that end on walls, robust plans + * that bring several possible tiles together, and trainers' sight lines. + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/PokemonBDSP_AutoStory_RobustRoute.h" +#include "Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "Data/PokemonBDSP_AutoStory_TrainerSight.h" +#include "Data/PokemonBDSP_AutoStory_WalkRules.h" +#include "Data/PokemonBDSP_AutoStory_WallRecovery.h" +#include "Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP_AutoStory_RoutePlanner_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using Pokemon::Direction; +using Pokemon::TilePos; + +StoryWorld make_world(const std::vector& rows){ + Pokemon::MapData map; + map.name = "Test"; + map.tiles = Pokemon::Grid{(int)rows[0].size(), (int)rows.size(), {}}; + for (const std::string& row : rows){ + for (char glyph : row){ + map.tiles.cells.push_back(*Pokemon::tile_from_glyph(glyph)); + } + } + StoryWorld world; + world.add("Test", map, {0, 0}); + return world; +} + +std::string describe(const std::vector& legs){ + std::string text; + for (const PlannedLeg& leg : legs){ + text += (text.empty() ? "" : "; ") + to_string(leg); + } + return text; +} + + +struct WallCase{ + std::string name; + std::vector rows; + TilePos from = {}; + Direction direction = Direction::EAST; + TilePos stop = {}; + size_t tiles = 0; + bool anchored = false; +}; + +UnitTestResult test_walk_to_wall(Logger&){ + const std::vector cases{ + {.name = "to a wall", .rows = {"....#"}, .stop = {3, 0}, .tiles = 3, .anchored = true}, + {.name = "off the map", .rows = {"...."}, .stop = {3, 0}, .tiles = 3, .anchored = false}, + {.name = "into a door", .rows = {"..D"}, .stop = {1, 0}, .tiles = 1, .anchored = false}, + {.name = "over a ledge, which counts 2", .rows = {".", "v", ".", "#"}, .direction = Direction::SOUTH, + .stop = {0, 2}, .tiles = 2, .anchored = true}, + }; + for (const WallCase& item : cases){ + const WallHit hit = slide_to_wall(make_world(item.rows), item.from, item.direction); + if (!(hit.stop == item.stop) || hit.tiles != item.tiles || hit.anchored != item.anchored){ + return std::format("{}: stops at {} after {} tiles, anchored {}; expected {} after {}, anchored {}.", item.name, + Pokemon::to_string(hit.stop), hit.tiles, hit.anchored, Pokemon::to_string(item.stop), item.tiles, item.anchored); + } + } + return true; +} + + +// plan_tile_route() around a pillar: two legs, both to a wall, that trace +// to the goal. +UnitTestResult test_plan_tile_route(Logger& logger){ + const StoryWorld world = make_world({"#####", "#...#", "#.#.#", "#...#", "#####"}); + const std::optional> legs = plan_tile_route(world, {1, 1}, {3, 3}); + if (!legs || legs->size() != 2 || !(*legs)[0].ends_at_wall || !(*legs)[1].ends_at_wall){ + return std::string("Expected two legs, both to a wall."); + } + if (!(trace_legs(world, {1, 1}, *legs).back() == TilePos{3, 3})){ + return std::string("The legs do not end on (3, 3)."); + } + logger.log(std::format("{}, {}", to_string((*legs)[0]), to_string((*legs)[1]))); + const std::optional> none = plan_tile_route(world, {1, 1}, {1, 1}); + if (!none || !none->empty()){ + return std::string("A route to the start is not empty."); + } + return true; +} + + +// plan_robust_route() from one or several tiles to a goal, with the open +// legs' error as the costs give it. +struct RobustCase{ + std::string name; + std::vector from; + TilePos goal; + RobustPlanCosts costs = {}; + // The plan as to_string() writes it, or empty when there is none. + std::string legs; +}; + +UnitTestResult test_plan_robust_route(Logger&){ + const StoryWorld world = make_world({"######", "#....#", "######"}); + RobustPlanCosts exact_step; + exact_step.exact_open_tiles = 1; + const std::vector cases{ + {.name = "two starts meet at the wall", .from = {{1, 1}, {2, 1}}, .goal = {4, 1}, .legs = "east 3 (to wall) to (4, 1)"}, + {.name = "an open stop is never sure", .from = {{1, 1}}, .goal = {3, 1}, .legs = ""}, + {.name = "unless a one-tile step is exact", .from = {{1, 1}}, .goal = {3, 1}, .costs = exact_step, + .legs = "east 3 (to wall) to (4, 1); west 1 (open) to (3, 1)"}, + }; + for (const RobustCase& item : cases){ + const auto legs = plan_robust_route(world, item.from, [&](const TilePos& pos){ return pos == item.goal; }, item.costs); + const std::string read = legs ? describe(*legs) : ""; + if (read != item.legs){ + return std::format("{}: planned \"{}\", expected \"{}\".", item.name, read, item.legs); + } + } + try{ + plan_robust_route(world, TilePos{0, 0}, TilePos{4, 1}); + return std::string("A start on a wall did not throw."); + }catch (InternalProgramError&){} + return true; +} + + +// Empty map name selects a synthetic corridor: ####### / #.....# / #######. +// Both possible starts (1,1)/(5,1) must share a safe wall ray. NPCs and +// warps on that ray or its wall invalidate it; ordinary terrain is unchanged. +struct RecoveryGeometryInput{ + std::string name; + std::string map = {}; + std::vector from; + std::optional wander = {}; + std::vector warps = {}; +}; +struct RecoveryGeometryExpectation{ + std::optional anchor; + Direction direction = Direction::SOUTH; + size_t holds = 1; + std::optional free_tile = {}; +}; +struct RecoveryGeometryCase{ + RecoveryGeometryInput input; + RecoveryGeometryExpectation expectation; +}; + +Pokemon::MapData recovery_map(const RecoveryGeometryInput& input){ + Pokemon::MapData map; + if (!input.map.empty()){ + return story_map(input.map); + } + map.name = "RecoveryDiagnostic"; + map.tiles = Pokemon::Grid{7, 3, {}}; + for (std::string_view row : {"#######", "#.....#", "#######"}){ + for (char glyph : std::string(row)){ + map.tiles.cells.push_back(*Pokemon::tile_from_glyph(glyph)); + } + } + if (input.wander){ + map.objects.push_back({.name = "wanderer", .x = 3, .y = 1, .facing = std::nullopt, + .wander = input.wander, .trainer = std::nullopt, .hide_flag = std::nullopt}); + } + for (const auto& warp : input.warps){ + map.warps.push_back({.x = warp.x, .y = warp.y, .to = std::nullopt}); + } + return map; +} + +class Test_RecoveryGeometry : public UnitTest{ +public: + explicit Test_RecoveryGeometry(RecoveryGeometryCase scenario) + : UnitTest("PokemonBDSP::AutoStory - Recovery geometry: " + scenario.input.name), m_case(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const auto& expected = m_case.expectation; + const auto map = recovery_map(m_case.input); + StoryWorld world; + world.add(map.name, map, {0, 0}); + if (expected.free_tile && (!standable(world, *expected.free_tile) + || world.occupied(*expected.free_tile) != StoryWorld::NOBODY)){ + return "Expected ordinary movement to remain free at " + Pokemon::to_string(*expected.free_tile); + } + const auto anchors = wall_recovery_candidates(world, m_case.input.from); + const auto actual = anchors.empty() ? std::optional() : std::optional(anchors.front().at); + if (actual != expected.anchor){ + return std::format("Expected anchor {}, got {}.", + expected.anchor ? Pokemon::to_string(*expected.anchor) : "none", + actual ? Pokemon::to_string(*actual) : "none"); + } + if (anchors.empty()){ + return true; + } + const auto& holds = anchors.front().holds; + if (holds.size() != expected.holds || holds.empty() || holds.front().direction != expected.direction){ + return std::format("Expected {} holds beginning {}, got {} beginning {}.", + expected.holds, Pokemon::direction_name(expected.direction), holds.size(), + holds.empty() ? "none" : Pokemon::direction_name(holds.front().direction)); + } + return true; + } +private: + RecoveryGeometryCase m_case; +}; + +// A trainer's sight stops at the first tile the player cannot stand on, +// and a leg through it is reported; a leg that is stopped throws. +UnitTestResult test_trainer_sight(Logger&){ + const StoryWorld world = make_world({".....", ".....", "..#.."}); + const TrainerSight trainer{.name = "lass", .pos = {2, 0}, .facing = Direction::SOUTH, .range = 4}; + if (sight_tiles(world, trainer) != std::vector{{2, 1}}){ + return std::string("The lass's sight is not the one tile above the rock."); + } + const std::vector legs{{Direction::EAST, 4, true}, {Direction::SOUTH, 1, false}}; + const auto crossings = legs_crossing_sight(world, {0, 1}, legs, {trainer}); + if (crossings != std::vector>{{"lass"}, {}}){ + return std::string("Only the first leg crosses the lass's sight."); + } + try{ + trace_legs(world, {0, 1}, {{Direction::SOUTH, 2, false}}); + return std::string("A leg off the map did not throw."); + }catch (InternalProgramError&){} + return true; +} + + +struct RoutePlannerInput{ + std::string name; + std::function body; +}; + +struct RoutePlannerExpectation{ +}; + +struct RoutePlannerCase{ + RoutePlannerInput input; + RoutePlannerExpectation expectation; +}; + +class Test_RoutePlanner : public UnitTest{ +public: + explicit Test_RoutePlanner(RoutePlannerCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Route planner: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + RoutePlannerCase m_case; +}; + +} // namespace + + +const RoutePlannerCase ROUTE_PLANNER_CASES[] = { + { + .input = {"walking until stopped", test_walk_to_wall}, + .expectation = {}, + }, + { + .input = {"legs to walls around a pillar", test_plan_tile_route}, + .expectation = {}, + }, + { + .input = {"robust plans", test_plan_robust_route}, + .expectation = {}, + }, + { + .input = {"trainers' sight lines", test_trainer_sight}, + .expectation = {}, + }, +}; + +const RecoveryGeometryCase GEOMETRY_CASES[] = { + {.input = {.name = "mine rows converge south", .map = "OreburghMine", .from = {{15, 15}, {15, 16}, {15, 17}}}, + .expectation = {.anchor = TilePos{.x = 15, .y = 17}}}, + {.input = {.name = "r55 tiles converge east", .map = "Route202", .from = {{27, 5}, {26, 5}}}, + .expectation = {.anchor = TilePos{.x = 30, .y = 5}, .direction = Direction::EAST}}, + {.input = {.name = "wandering area is unsafe", .from = {{1, 1}, {5, 1}}, + .wander = Pokemon::TileBox{.x0 = 2, .y0 = 1, .x1 = 4, .y1 = 1}}, + .expectation = {.anchor = std::nullopt, .free_tile = TilePos{.x = 3, .y = 1}}}, + {.input = {.name = "warp crossings are unsafe", .from = {{1, 1}, {5, 1}}, .warps = {{3, 1}}}, + .expectation = {.anchor = std::nullopt}}, + {.input = {.name = "warps on blocked glyphs are unsafe", .from = {{1, 1}, {5, 1}}, .warps = {{0, 1}, {6, 1}}}, + .expectation = {.anchor = std::nullopt}}, +}; + +void add_tests_AutoStory_RoutePlanner(UnitTestDatabase& database){ + for (const auto& item : ROUTE_PLANNER_CASES){ + database.add(item); + } + for (const auto& scenario : GEOMETRY_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h new file mode 100644 index 0000000000..1a75a9811f --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h @@ -0,0 +1,24 @@ +/* BDSP AutoStory Route Planner Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RoutePlanner_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RoutePlanner_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Offline checks of the route planner on synthetic maps. +void add_tests_AutoStory_RoutePlanner(UnitTestDatabase& database); + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp new file mode 100644 index 0000000000..d417b27ea2 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp @@ -0,0 +1,252 @@ +/* BDSP AutoStory Segment 00 Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/PokemonBDSP_AutoStory_Maps.h" +#include "Data/PokemonBDSP_AutoStory_RobustRoute.h" +#include "Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "Data/PokemonBDSP_AutoStory_Segment00Lines.h" +#include "Data/PokemonBDSP_AutoStory_StoryMaps.h" +#include "Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP_AutoStory_Segment00_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using Pokemon::TilePos; +using Segment00Lines::SceneTrigger; +using Segment00Lines::WalkedLine; + +std::string describe(const MapTile& tile){ + return tile.map + " " + Pokemon::to_string(tile.pos); +} + +const SceneTrigger* find_trigger(const std::string& name){ + for (const SceneTrigger& trigger : Segment00Lines::scene_triggers()){ + if (trigger.name == name){ + return &trigger; + } + } + return nullptr; +} + +// Plans one stretch of a line with the waypoint costs and returns the leg, +// or an error. The stretch must be the one straight leg a human took: to a +// wall or open, as the grid has it, ending exactly on the corner. +struct Stretch{ + TileLeg leg; + std::string error; +}; +Stretch plan_stretch(const StoryWorld& maps, const TilePos& from, const TilePos& to, const std::string& name){ + const auto plan = plan_robust_route(maps, std::vector{from}, + [&](const TilePos& pos){ return pos == to; }, waypoint_plan_costs()); + if (!plan){ + return {{}, name + ": no plan."}; + } + if (plan->size() != 1){ + std::string text = name + ": " + std::to_string(plan->size()) + " legs, expected the one straight leg:"; + for (const PlannedLeg& leg : *plan){ + text += " " + to_string(leg.leg); + } + return {{}, text}; + } + const PlannedLeg& leg = (*plan)[0]; + if (leg.after.size() != 1 || !(leg.after[0] == to)){ + return {{}, name + ": the leg " + to_string(leg.leg) + " does not end exactly on the corner."}; + } + return {leg.leg, ""}; +} + +// Every tile a line stands on, its start first, as local tiles; logs each +// stretch's leg. Empty with `error` set when a stretch does not plan. +std::vector line_tiles(Logger& logger, const StoryWorld& maps, const WalkedLine& line, std::string& error){ + const std::string name = line.checkpoint + " " + line.name; + std::vector tiles{line.corners[0]}; + TilePos at = maps.to_world(line.corners[0].map, line.corners[0].pos); + std::string text = name + ": from " + describe(line.corners[0]); + for (size_t i = 1; i < line.corners.size(); i++){ + const MapTile& corner = line.corners[i]; + const TilePos goal = maps.to_world(corner.map, corner.pos); + const Stretch stretch = plan_stretch(maps, at, goal, name + " stretch " + std::to_string(i) + " to " + describe(corner)); + if (!stretch.error.empty()){ + error = stretch.error; + return {}; + } + text += "\n " + to_string(stretch.leg) + " to " + describe(corner); + for (size_t k = 0; k < stretch.leg.tiles; k++){ + at = at.next(stretch.leg.direction); + const std::optional local = maps.to_local(at); + if (!local){ + error = name + ": the line leaves the maps at " + Pokemon::to_string(at) + "."; + return {}; + } + tiles.push_back(*local); + } + } + logger.log(text); + return tiles; +} + +// The last tile steps into the line's scene; no earlier tile is in any +// scene armed while the line is walked (an inert one is only logged). +std::string check_triggers(Logger& logger, const WalkedLine& line, const std::vector& tiles){ + const std::string name = line.checkpoint + " " + line.name; + for (const std::string& live : line.live_triggers){ + if (find_trigger(live) == nullptr){ + return name + ": no scene trigger named \"" + live + "\"."; + } + } + const auto armed = [&](const std::string& trigger){ + return std::ranges::find(line.live_triggers, trigger) != line.live_triggers.end(); + }; + if (!line.ends_in.empty() && !armed(line.ends_in)){ + return name + ": the scene it ends in, \"" + line.ends_in + "\", is not among its live triggers."; + } + for (size_t i = 0; i < tiles.size(); i++){ + for (const SceneTrigger& trigger : Segment00Lines::scene_triggers()){ + if (!Segment00Lines::trigger_covers(trigger, tiles[i])){ + continue; + } + const bool live = armed(trigger.name); + const bool last = i + 1 == tiles.size(); + logger.log(name + ": tile " + std::to_string(i + 1) + " of " + std::to_string(tiles.size()) + ", " + describe(tiles[i]) + + ", is in \"" + trigger.name + "\" (" + (live ? "armed" : "inert: " + trigger.when) + ")."); + if (live && !(last && trigger.name == line.ends_in)){ + return name + ": steps into the armed scene \"" + trigger.name + "\" at " + describe(tiles[i]) + ", before its end."; + } + } + } + if (!line.ends_in.empty() && !Segment00Lines::trigger_covers(*find_trigger(line.ends_in), tiles.back())){ + return name + ": its last tile " + describe(tiles.back()) + " is not in \"" + line.ends_in + "\"."; + } + return ""; +} + +// The points the route records start and end on, each of which must lie +// on one of the lines. +struct NamedTile{ + std::string map; // in segment00_maps() + std::string json_map; + std::string point; +}; +std::vector named_tiles(){ + const std::string& twinleaf = Segment00Lines::MAP_TWINLEAF_TOWN; + const std::string& lakefront = Segment00Lines::MAP_VERITY_LAKEFRONT; + return { + {.map = twinleaf, .json_map = "TwinleafTown", .point = "house_doorstep"}, + {.map = twinleaf, .json_map = "TwinleafTown", .point = "barry_doorstep"}, + {.map = twinleaf, .json_map = "TwinleafTown", .point = "twinleaf_north_exit"}, + {.map = MAP_ROUTE_201, .json_map = "Route201", .point = "route_201_arrival"}, + {.map = MAP_ROUTE_201, .json_map = "Route201", .point = "barry_warning"}, + {.map = lakefront, .json_map = "VerityLakefront", .point = "lakefront_arrival"}, + {.map = lakefront, .json_map = "VerityLakefront", .point = "below_lake_entrance"}, + {.map = lakefront, .json_map = "VerityLakefront", .point = "lake_entrance"}, + {.map = MAP_ROUTE_201, .json_map = "Route201", .point = "route_201_return"}, + {.map = MAP_ROUTE_201, .json_map = "Route201", .point = "rowan_stop"}, + {.map = MAP_ROUTE_201, .json_map = "Route201", .point = "route_201_east_end"}, + {.map = MAP_SANDGEM_TOWN, .json_map = "SandgemTown", .point = "sandgem_arrival"}, + {.map = MAP_SANDGEM_TOWN, .json_map = "SandgemTown", .point = "dawn_stop"}, + }; +} + +// The lines 00.01 to 00.03 would walk (Data/PokemonBDSP_AutoStory_Segment00Lines): +// every stretch plans as one straight leg on the decomp maps, and each +// line enters its scene's trigger rectangle on its last tile only. The +// named tiles the route records start from all lie on the lines. +UnitTestResult test_segment00_lines(Logger& logger){ + const StoryWorld& maps = Segment00Lines::segment00_maps(); + for (const SceneTrigger& trigger : Segment00Lines::scene_triggers()){ + if (trigger.width <= 0 || trigger.height <= 0){ + return "Scene trigger \"" + trigger.name + "\" has no tiles."; + } + maps.to_world(trigger.map, trigger.corner); // throws for a map not in the set + } + std::vector walked; + for (const WalkedLine& line : Segment00Lines::lines()){ + if (line.corners.size() < 2){ + return line.checkpoint + " " + line.name + ": a line needs two corners."; + } + std::string error; + const std::vector tiles = line_tiles(logger, maps, line, error); + if (!error.empty()){ + return error; + } + error = check_triggers(logger, line, tiles); + if (!error.empty()){ + return error; + } + walked.insert(walked.end(), tiles.begin(), tiles.end()); + } + for (const NamedTile& tile : named_tiles()){ + const MapTile named{tile.map, map_point(tile.json_map, tile.point)}; + const bool on_a_line = std::ranges::any_of(walked, [&](const MapTile& t){ + return t.map == named.map && t.pos == named.pos; + }); + if (!on_a_line){ + return std::string(tile.point) + " " + describe(named) + " is on none of the lines."; + } + } + return true; +} + + +struct Segment00Input{ + std::string name; + std::function body; +}; + +struct Segment00Expectation{ +}; + +struct Segment00Case{ + Segment00Input input; + Segment00Expectation expectation; +}; + +class Test_Segment00 : public UnitTest{ +public: + explicit Test_Segment00(Segment00Case test_case) + : UnitTest("PokemonBDSP::AutoStory - Segment 00: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + Segment00Case m_case; +}; + +} // namespace + + +const Segment00Case SEGMENT00_CASES[] = { + { + .input = {"the lines into each scene", test_segment00_lines}, + .expectation = {}, + }, +}; + +void add_tests_AutoStory_Segment00(UnitTestDatabase& database){ + for (const auto& item : SEGMENT00_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h new file mode 100644 index 0000000000..dfd010c7f4 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h @@ -0,0 +1,27 @@ +/* BDSP AutoStory Segment 00 Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Segment00_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Segment00_Tests_H + +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// Offline checks of Segment 00's walked lines against the maps and the +// scenes' trigger rectangles. +void add_tests_AutoStory_Segment00(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp new file mode 100644 index 0000000000..6d181824fc --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp @@ -0,0 +1,341 @@ +/* BDSP AutoStory Story Maps Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The story's walks on its maps: Route 202's catch grass and the way into + * Sandgem, Sandgem's Center, the Oreburgh Gym's column, and the route + * records traced on their maps. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/PokemonBDSP_AutoStory_Maps.h" +#include "Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "Data/PokemonBDSP_AutoStory_RobustRoute.h" +#include "Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "Data/PokemonBDSP_AutoStory_RouteRecords.h" +#include "Data/PokemonBDSP_AutoStory_StoryMaps.h" +#include "Data/PokemonBDSP_AutoStory_StorySpots.h" +#include "Data/PokemonBDSP_AutoStory_StoryTrainers.h" +#include "Data/PokemonBDSP_AutoStory_TrainerSight.h" +#include "Data/PokemonBDSP_AutoStory_WalkRules.h" +#include "PokemonBDSP_AutoStory_StoryMaps_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using Pokemon::Direction; +using Pokemon::TileKind; +using Pokemon::TilePos; + +StoryWorld alone(const std::string& json_map){ + StoryWorld world; + world.add(json_map, story_map(json_map), {0, 0}); + return world; +} + +// 00.04's training walks up and down the catch patch, three grass rows +// between tree rows, and needs the walk there to end in its grass: r253 +// and r254 loaded the catch's save in the pocket behind the trees at +// (21, 29), planned from the catch spot instead, and walked up and down +// the lawn east of the grass for three minutes without a battle. +UnitTestResult test_route202_catch_grass(Logger& logger){ + const StoryWorld route = alone("Route202"); + for (int x = 15; x <= 20; x++){ + const WallHit up = slide_to_wall(route, {x, 27}, Direction::NORTH); + const WallHit down = slide_to_wall(route, {x, 25}, Direction::SOUTH); + if (!(up.stop == TilePos{x, 25}) || !(down.stop == TilePos{x, 27})){ + return std::format("Catch patch column {}: north from row 27 stops at {}, south from row 25 at {}; expected rows 25 and 27, between tree rows.", + x, Pokemon::to_string(up.stop), Pokemon::to_string(down.stop)); + } + } + const StoryWorld& maps = story_maps(); + const std::vector area = story_after_training_area(); + const auto in_grass = [&](const TilePos& pos){ + return maps.tile(pos) == TileKind::TALL_GRASS && std::find(area.begin(), area.end(), pos) != area.end(); + }; + // As walk_route() plans: the route costs, else the default costs. + // From the whole area the catch's save may stand in, and from the + // pocket behind the trees alone, where r252 saved. + const std::vector>> starts{ + {"the catch's save area", story_catch_save_area()}, + {"the pocket behind the trees", {maps.to_world(MAP_ROUTE_202, {21, 29})}}, + }; + for (const auto& [name, from] : starts){ + std::optional> legs = plan_robust_route(maps, from, in_grass, route_plan_costs()); + if (!legs){ + legs = plan_robust_route(maps, from, in_grass, RobustPlanCosts()); + } + if (!legs || legs->empty()){ + return "From " + name + " to the catch grass: no plan."; + } + for (const TilePos& pos : legs->back().after){ + if (!in_grass(pos)){ + return "From " + name + " to the catch grass: the walk may end on " + describe(maps, pos) + ", not in the grass."; + } + } + logger.log(std::format("From {} to the catch grass: {} legs, ending in the grass.", name, legs->size())); + } + return true; +} + +// 00.04's way to Sandgem's Pokemon Center ends below the Center's sign, +// walking north into it, then taps west along the doors' row to below the +// door: the row must be open there, the door straight north of where the +// taps end, and nothing else (a sign, the Mart's door) on the way. +UnitTestResult test_sandgem_center_approach(Logger& logger){ + const StoryWorld town = alone("SandgemTown"); + const TilePos sign = map_point("SandgemTown", "pokemon_center_sign"); + const TilePos door = map_point("SandgemTown", "pokemon_center_door"); + if (town.tile(sign) != TileKind::SIGN || town.tile(door) != TileKind::DOOR || door.y != sign.y || door.x >= sign.x){ + return std::format("The Center's sign {} and door {} are not a sign and a door west of it on one row.", + Pokemon::to_string(sign), Pokemon::to_string(door)); + } + TilePos pos = sign.next(Direction::SOUTH); + for (int tap = 0; tap < sign.x - door.x; tap++){ + const std::optional next = step(town, pos, Direction::WEST); + if (!next){ + return "West from " + Pokemon::to_string(pos) + " is blocked."; + } + if (town.tile(next->next(Direction::NORTH)) != TileKind::WALL && *next != door.next(Direction::SOUTH)){ + return "Above " + Pokemon::to_string(*next) + " is not the Center's wall."; + } + pos = *next; + } + if (!(pos == door.next(Direction::SOUTH))){ + return std::format("The taps end at {}, not below the door {}.", Pokemon::to_string(pos), Pokemon::to_string(door)); + } + logger.log(std::format("Sandgem: below the sign {}, {} taps west to below the door {}.", + Pokemon::to_string(sign.next(Direction::SOUTH)), sign.x - door.x, Pokemon::to_string(door))); + return true; +} + +// After training, 00.04 walks from wherever the training left us into +// Sandgem, to where the road stops above the Mart, with the default costs +// (heal_at_sandgem_center()): from the whole area and from each of its +// tiles alone, a plan must exist and end there. +UnitTestResult test_training_to_sandgem(Logger& logger){ + const StoryWorld& maps = story_maps(); + const TilePos entry = maps.to_world(MAP_SANDGEM_TOWN, map_point("SandgemTown", "route_202_entry_stop")); + const std::vector area = story_after_training_area(); + std::vector> starts{area}; + for (const TilePos& pos : area){ + starts.push_back({pos}); + } + for (const std::vector& from : starts){ + const auto legs = plan_robust_route(maps, from, [&](const TilePos& pos){ return pos == entry; }, RobustPlanCosts()); + const std::string name = from.size() == 1 ? describe(maps, from[0]) : "the whole training area"; + if (!legs || legs->empty()){ + return "From " + name + " into Sandgem: no plan."; + } + if (legs->back().after.size() != 1 || !(legs->back().after[0] == entry)){ + return "From " + name + " into Sandgem: the plan does not end on " + describe(maps, entry) + "."; + } + logger.log(std::format("From {} into Sandgem: {} legs.", name, legs->size())); + } + return true; +} + +// The Oreburgh Gym's inside: the column up from the entrance runs to Roark +// with nothing in the way but the two Youngsters' sight lines, which is +// what 01.04's "north until a trainer stops us" relies on. +UnitTestResult test_oreburgh_gym_column(Logger& logger){ + const StoryWorld gym = alone("OreburghGym"); + const TilePos entrance = map_point("OreburghGym", "entrance"); + const TilePos roark = map_point("OreburghGym", "roark"); + if (!standable(gym, entrance) || gym.tile(entrance.next(Direction::SOUTH)) != TileKind::DOOR){ + return std::string("The entrance tile is not standable above the door."); + } + if (!gym.occupied(roark)){ + return std::string("Nobody stands on Roark's tile."); + } + const WallHit up = slide_to_wall(gym, entrance, Direction::NORTH); + if (!(up.wall == roark)){ + return "North from the entrance stops at " + Pokemon::to_string(up.stop) + ", not in front of Roark."; + } + logger.log(std::format("Oreburgh Gym: north from the entrance walks {} tiles to Roark.", up.tiles)); + for (const TrainerSight& trainer : oreburgh_gym_trainer_sights()){ + if (!gym.occupied(trainer.pos)){ + return trainer.name + " does not stand on their tile."; + } + const std::vector seen = sight_tiles(gym, trainer); + const bool sees_column = std::ranges::any_of(seen, [&](const TilePos& pos){ + return pos.x == entrance.x && pos.y < entrance.y && pos.y > roark.y; + }); + if (!sees_column){ + return trainer.name + " does not see the column up to Roark."; + } + } + return true; +} + +// Oreburgh Mine B1F (the entrance hall): +// The hallway connects Oreburgh City above with the Coal Room below. +// Row 1 contains warp doors (11..13, 1) leading to the city. +// Row 21 contains warp doors (11..13, 21) leading to the coal room. +// Column 12 is unobstructed south from landing (12, 1) to warp door (12, 21). +// Column 11 is unobstructed north from landing (11, 21) to warp door (11, 1). +UnitTestResult test_oreburgh_mine_hall(Logger& logger){ + const StoryWorld hall = alone("OreburghMineB1F"); + for (int x = 11; x <= 13; x++){ + if (hall.tile({x, 1}) != TileKind::DOOR){ + return std::format("OreburghMineB1F ({}, 1) is not a DOOR tile (exit to city).", x); + } + if (hall.tile({x, 21}) != TileKind::DOOR){ + return std::format("OreburghMineB1F ({}, 21) is not a DOOR tile (entrance to coal room).", x); + } + } + for (int y = 2; y <= 20; y++){ + if (!standable(hall, {12, y})){ + return std::format("OreburghMineB1F column 12 row {} is blocked; expected clear path to coal room.", y); + } + if (!standable(hall, {11, y})){ + return std::format("OreburghMineB1F column 11 row {} is blocked; expected clear path to city exit.", y); + } + } + logger.log("OreburghMineB1F: columns 11 and 12 are clear between row 1 and row 21 warp doors."); + return true; +} + +// 01.04: the D-pad taps west from below Oreburgh's Center door end below +// the Gym's door, where the step north goes in. Red with 20 taps: they ended +// on (27, 21), a tile east of the door (lab-B, 2026-11-08 14:51). +UnitTestResult test_oreburgh_center_to_gym_taps(Logger& logger){ + const RouteRecords::RouteRecord* record = nullptr; + for (const RouteRecords::RouteRecord& item : RouteRecords::all()){ + if (item.checkpoint == "01.04" && item.map_file == "OreburghCity"){ + record = &item; + } + } + if (record == nullptr || !record->start || record->legs.empty()){ + return "No 01.04 record on Oreburgh City with a start tile and legs."; + } + const StoryWorld city = alone("OreburghCity"); + const RouteRecords::RouteLeg& west = record->legs.front(); + const TilePos end = trace_legs(city, *record->start, {{west.direction, west.tiles, false}}).back(); + const TilePos doorstep = map_point("OreburghCity", "gym_doorstep"); + if (end != doorstep){ + return std::format("{} taps west end on ({}, {}), not below the Gym's door ({}, {}).", west.tiles, end.x, end.y, doorstep.x, doorstep.y); + } + logger.log(std::format("Oreburgh: {} taps west from below the Center's door reach the Gym's doorstep.", west.tiles)); + return true; +} + +// Each traceable record with a start tile starts on ground, and its legs +// counted in whole tiles trace on its map up to the first leg that ends +// some other way. +UnitTestResult test_route_records(Logger& logger){ + for (const RouteRecords::RouteRecord& record : RouteRecords::all()){ + const std::string name = record.checkpoint + " " + record.title; + const StoryWorld world = alone(record.map_file); + if (!record.traceable || !record.start){ + continue; + } + if (!standable(world, *record.start)){ + return name + ": starts on " + Pokemon::to_string(*record.start) + ", where nobody can stand."; + } + std::vector counted; + for (const RouteRecords::RouteLeg& leg : record.legs){ + if (leg.end != RouteRecords::LegEnd::COUNT || !leg.exact){ + break; + } + counted.push_back({leg.direction, leg.tiles, false}); + } + try{ + const TilePos end = trace_legs(world, *record.start, counted).back(); + logger.log(std::format("{}: {} counted legs to {}.", name, counted.size(), describe(world, end))); + }catch (InternalProgramError& e){ + return name + ": " + e.message(); + } + } + return true; +} + + +struct StoryMapsInput{ + std::string name; + std::function body; +}; + +struct StoryMapsExpectation{ +}; + +struct StoryMapsCase{ + StoryMapsInput input; + StoryMapsExpectation expectation; +}; + +class Test_StoryMaps : public UnitTest{ +public: + explicit Test_StoryMaps(StoryMapsCase test_case) + : UnitTest("PokemonBDSP::AutoStory - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + StoryMapsCase m_case; +}; + +} // namespace + + +const StoryMapsCase STORY_MAPS_CASES[] = { + { + .input = {"Route 202: the catch patch and the walk to it", test_route202_catch_grass}, + .expectation = {}, + }, + { + .input = {"Sandgem Town: below the Center's sign to below its door", test_sandgem_center_approach}, + .expectation = {}, + }, + { + .input = {"Route 202: from every tile of the training area into Sandgem", test_training_to_sandgem}, + .expectation = {}, + }, + { + .input = {"Oreburgh Gym: the column up to Roark", test_oreburgh_gym_column}, + .expectation = {}, + }, + { + .input = {"Oreburgh Mine B1F: the entrance hall corridor and warps", test_oreburgh_mine_hall}, + .expectation = {}, + }, + { + .input = {"Oreburgh: 01.04's taps from the Center's door to the Gym's", test_oreburgh_center_to_gym_taps}, + .expectation = {}, + }, + { + .input = {"Route records: counted legs trace on their maps", test_route_records}, + .expectation = {}, + }, +}; + +void add_tests_AutoStory_StoryMaps(UnitTestDatabase& database){ + for (const auto& item : STORY_MAPS_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h new file mode 100644 index 0000000000..c0ed36bd5b --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h @@ -0,0 +1,24 @@ +/* BDSP AutoStory Story Maps Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryMaps_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryMaps_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Offline checks of the story's walks on its maps: Route 202, Sandgem, the Oreburgh Gym and the route records. +void add_tests_AutoStory_StoryMaps(UnitTestDatabase& database); + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp new file mode 100644 index 0000000000..99cb510515 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp @@ -0,0 +1,232 @@ +/* BDSP AutoStory Story World Tests + * + * From: https://github.com/PokemonAutomation/ + * + * StoryWorld on small synthetic maps: what each tile does to a step, maps + * joined at offsets, and tiles blocked or taken off the maps. + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Data/PokemonBDSP_AutoStory_StoryWorld.h" +#include "Data/PokemonBDSP_AutoStory_WalkRules.h" +#include "PokemonBDSP_AutoStory_StoryWorld_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using Pokemon::Direction; +using Pokemon::MapData; +using Pokemon::TilePos; + +// A map of these rows, with a person standing still on each `standing` +// tile and one wandering on each `wandering` tile. +MapData make_map( + const std::vector& rows, + const std::vector& standing = {}, + const std::vector& wandering = {} +){ + MapData map; + map.name = "Test"; + map.tiles = Pokemon::Grid{(int)rows[0].size(), (int)rows.size(), {}}; + for (const std::string& row : rows){ + for (char glyph : row){ + map.tiles.cells.push_back(*Pokemon::tile_from_glyph(glyph)); + } + } + for (const TilePos& pos : standing){ + map.objects.push_back({ + .name = "standing", .kind = Pokemon::ObjectKind::NPC, .x = pos.x, .y = pos.y, + .facing = std::nullopt, .wander = std::nullopt, + .trainer = std::nullopt, .hide_flag = std::nullopt, + }); + } + for (const TilePos& pos : wandering){ + map.objects.push_back({ + .name = "wandering", .kind = Pokemon::ObjectKind::NPC, .x = pos.x, .y = pos.y, + .facing = std::nullopt, .wander = Pokemon::TileBox{pos.x, pos.y, pos.x, pos.y}, + .trainer = std::nullopt, .hide_flag = std::nullopt, + }); + } + return map; +} + +StoryWorld make_world(const MapData& map){ + StoryWorld world; + world.add("Test", map, {0, 0}); + return world; +} + + +// One step from (1, 1) of a 3 x 3 map whose middle tile (the step's +// target) is `target`, and whether the player is held at a wall there. +struct StepCase{ + std::string name; + std::vector rows; + std::vector standing = {}; + std::vector wandering = {}; + TilePos from = {}; + Direction direction = Direction::NORTH; + std::optional lands = std::nullopt; + bool at_wall = false; +}; + +UnitTestResult test_story_world_steps(Logger&){ + const std::vector cases{ + {.name = "open ground", .rows = {".", "."}, .from = {0, 1}, .lands = TilePos{0, 0}}, + {.name = "tall grass", .rows = {"~", "."}, .from = {0, 1}, .lands = TilePos{0, 0}}, + {.name = "a wall", .rows = {"#", "."}, .from = {0, 1}, .at_wall = true}, + {.name = "water", .rows = {"w", "."}, .from = {0, 1}, .at_wall = true}, + {.name = "a sign", .rows = {"S", "."}, .from = {0, 1}, .at_wall = true}, + {.name = "a door is not a wall", .rows = {"D", "."}, .from = {0, 1}}, + {.name = "off the map is not a wall", .rows = {"."}, .from = {0, 0}}, + {.name = "a south ledge hops south", .rows = {".", "v", "."}, .direction = Direction::SOUTH, .lands = TilePos{0, 2}}, + {.name = "a south ledge stops north", .rows = {".", "v", "."}, .from = {0, 2}, .at_wall = true}, + {.name = "a west ledge hops west", .rows = {".<."}, .from = {2, 0}, .direction = Direction::WEST, .lands = TilePos{0, 0}}, + {.name = "a west ledge stops east", .rows = {".<."}, .direction = Direction::EAST, .at_wall = true}, + {.name = "a ledge onto a wall stops", .rows = {".", "v", "#"}, .direction = Direction::SOUTH, .at_wall = true}, + {.name = "a person standing still", .rows = {".", "."}, .standing = {{0, 0}}, .from = {0, 1}, .at_wall = false}, + {.name = "a wanderer does not block", .rows = {".", "."}, .wandering = {{0, 0}}, .from = {0, 1}, .lands = TilePos{0, 0}}, + }; + for (const StepCase& item : cases){ + const StoryWorld world = make_world(make_map(item.rows, item.standing, item.wandering)); + const std::optional lands = step(world, item.from, item.direction); + if (lands != item.lands){ + return std::format("{}: lands on {}, expected {}.", item.name, + lands ? Pokemon::to_string(*lands) : "nothing", item.lands ? Pokemon::to_string(*item.lands) : "nothing"); + } + if (at_wall(world, item.from, item.direction) != item.at_wall){ + return std::format("{}: at_wall() is {}, expected {}.", item.name, !item.at_wall, item.at_wall); + } + } + return true; +} + + +// Two maps joined: tiles of each at their offsets, the gap between them +// off the maps, and a shared wall border allowed where nothing else is. +UnitTestResult test_story_world_join(Logger&){ + StoryWorld world; + world.add("West", make_map({"##", ".#"}), {0, 0}); + world.add("East", make_map({"#.", "#~"}), {1, -1}); + const std::vector> described{ + {{0, 2}, "West (0, 1)"}, + {{2, 0}, "East (1, 0)"}, + {{1, 1}, "West (1, 0)"}, // the shared wall: the first map holds it + {{2, 2}, "world (2, 2)"}, + }; + for (const auto& [pos, text] : described){ + if (describe(world, pos) != text){ + return std::format("{}: described as \"{}\", expected \"{}\".", Pokemon::to_string(pos), describe(world, pos), text); + } + } + if (!covered(world, {0, 2}) || covered(world, {3, 0}) || covered(world, {0, 3}) || covered(world, {2, 2}) || !standable(world, {2, 1})){ + return std::string("The joined world is not 3 x 3 with East's grass at (2, 1) and nothing at (2, 2)."); + } + if (!(world.to_world("East", {0, 0}) == TilePos{1, 0})){ + return "East (0, 0) is world " + Pokemon::to_string(world.to_world("East", {0, 0})) + ", expected (1, 0)."; + } + try{ + world.add("Overlap", make_map({"."}), {0, 1}); + return std::string("Adding a map over open ground did not throw."); + }catch (InternalProgramError&){} + try{ + world.to_world("North", {0, 0}); + return std::string("to_world() of an unknown map did not throw."); + }catch (InternalProgramError&){} + return true; +} + + +// block() and uncover() change what a tile does, and survive a map added +// later that moves the world's origin. +UnitTestResult test_story_world_block_uncover(Logger&){ + StoryWorld world; + world.add("Road", make_map({"...."}), {0, 0}); + world.block({1, 0}); + world.uncover({2, 0}); + if (step(world, {0, 0}, Direction::EAST) || !at_wall(world, {0, 0}, Direction::EAST)){ + return std::string("A blocked tile is not a wall."); + } + if (covered(world, {2, 0}) || at_wall(world, {3, 0}, Direction::WEST)){ + return std::string("An uncovered tile is still on the map, or a wall."); + } + world.add("North", make_map({"#"}), {0, -1}); + const TilePos blocked = world.to_world("Road", {1, 0}); + const TilePos uncovered = world.to_world("Road", {2, 0}); + if (!world.occupied(blocked) || covered(world, uncovered) || !standable(world, world.to_world("Road", {3, 0}))){ + return std::string("Adding a map lost the blocked or uncovered tile."); + } + return true; +} + + +struct StoryWorldInput{ + std::string name; + std::function body; +}; + +struct StoryWorldExpectation{ +}; + +struct StoryWorldCase{ + StoryWorldInput input; + StoryWorldExpectation expectation; +}; + +class Test_StoryWorld : public UnitTest{ +public: + explicit Test_StoryWorld(StoryWorldCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Story world: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + StoryWorldCase m_case; +}; + +} // namespace + + +const StoryWorldCase STORY_WORLD_CASES[] = { + { + .input = {"what each tile does to a step", test_story_world_steps}, + .expectation = {}, + }, + { + .input = {"maps joined at offsets", test_story_world_join}, + .expectation = {}, + }, + { + .input = {"blocked and uncovered tiles", test_story_world_block_uncover}, + .expectation = {}, + }, +}; + +void add_tests_AutoStory_StoryWorld(UnitTestDatabase& database){ + for (const auto& item : STORY_WORLD_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h new file mode 100644 index 0000000000..de4006d340 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h @@ -0,0 +1,24 @@ +/* BDSP AutoStory Story World Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryWorld_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryWorld_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Offline checks of the story world: tile rules, joins, blocked and uncovered tiles. +void add_tests_AutoStory_StoryWorld(UnitTestDatabase& database); + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index a1349c3d6b..f379ca7282 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1787,8 +1787,36 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/PokemonBDSP_Tests.h Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.cpp Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RobustRoute.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RouteRecords.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Segment00Lines.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMapNames.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StorySpots.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryTrainers.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TrainerSight.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WalkRules.h + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp + Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.cpp Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.h Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomousState.cpp