diff --git a/.github/workflows/cpp-ci-serial-programs-base.yml b/.github/workflows/cpp-ci-serial-programs-base.yml index c21b13ec85..358de17122 100644 --- a/.github/workflows/cpp-ci-serial-programs-base.yml +++ b/.github/workflows/cpp-ci-serial-programs-base.yml @@ -96,6 +96,46 @@ jobs: operation: prepare consumer-directory: Arduino-Source + - name: Checkout authored BDSP story simulator + if: startsWith(inputs.os, 'ubuntu') && inputs.run-tests + uses: actions/checkout@v7 + with: + repository: dayfine/PokemonSimulation + ref: 913a5e3eaa22865e1aeab52f23c9e23ea7141ced + path: AuthoredStorySource + + - name: Replay the authoritative Arduino mine plan + if: startsWith(inputs.os, 'ubuntu') && inputs.run-tests + env: + PYTHONPATH: AuthoredStorySource/src + run: | + python3 - <<'PYTHON' + from pathlib import Path + import hashlib, json, tempfile + from pokesim.story.replay_binding import load_binding + from pokesim.story.replay_cases import read_cases, check_case + from pokesim.story.checkpoint_replay import run + source = Path('AuthoredStorySource').resolve() + folder = source / 'data/story/bdsp-mine-pilot' + native = Path('Arduino-Source/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData') + # The Arduino plan is authoritative; bind these exact bytes explicitly. + # The simulator's checked-in plan is only a frozen regression snapshot. + with tempfile.TemporaryDirectory(prefix='.native-story-', dir=source) as temporary: + stage = Path(temporary) + raw = (native / 'bdsp-mine-01.03.plan.json').read_bytes() + (stage / 'plan.json').write_bytes(raw) + profile = json.loads((folder / 'binding.json').read_text()) + profile['plan'] = {'file': str((stage / 'plan.json').relative_to(source)), + 'sha256': hashlib.sha256(raw).hexdigest()} + (stage / 'binding.json').write_text(json.dumps(profile)) + binding = load_binding(stage / 'binding.json', source) + cases = read_cases(folder / 'cases.json') + for case in cases: + check_case(case, run(binding, case['input'])) + print(case['id'] + ': current Arduino plan replay passed') + assert len(cases) == 9 + PYTHON + - name: Install Qt uses: jurplel/install-qt-action@v4 with: diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index c362957808..58a39e28bc 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -243,6 +243,18 @@ pa_pokesim_map_directory(BDSP_MAP_DIRECTORY bdsp "${POKESIM_CONSUMER}" "${POKESI file(RELATIVE_PATH BDSP_MAP_RESOURCES "${CMAKE_CURRENT_SOURCE_DIR}" "${BDSP_MAP_DIRECTORY}") pa_embed_text_files(SerialProgramsLib "${BDSP_MAP_RESOURCES}" PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h PokemonAutomation::NintendoSwitch::PokemonBDSP bdsp_map_json) +# TODO: Move JSON syntax preflight into pa_embed_text_files so map and story +# resources share it. Keep game/schema/semantic checks in their native tests. +# Catch JSON syntax errors during a lab build, before static table initialization. +# Native tests still validate the schema, game policy and execution semantics. +file(GLOB BDSP_STORY_FILES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/Source/PokemonBDSP/Programs/AutoStory/StoryData/*.json") +foreach(BDSP_STORY_FILE IN LISTS BDSP_STORY_FILES) + file(READ "${BDSP_STORY_FILE}" BDSP_STORY_TEXT) + string(JSON BDSP_STORY_TYPE ERROR_VARIABLE BDSP_STORY_ERROR TYPE "${BDSP_STORY_TEXT}") + if(BDSP_STORY_ERROR OR NOT BDSP_STORY_TYPE STREQUAL "OBJECT") + message(FATAL_ERROR "Invalid authored checkpoint ${BDSP_STORY_FILE}: ${BDSP_STORY_ERROR}") + endif() +endforeach() pa_embed_text_files(SerialProgramsLib Source/PokemonBDSP/Programs/AutoStory/StoryData PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.h PokemonAutomation::NintendoSwitch::PokemonBDSP bdsp_checkpoint_json) diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index f905de3a60..8f5d1256d3 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -39,6 +39,7 @@ #include "Pokemon/Navigation/Pokemon_LegWalker_Tests.h" #include "Pokemon/Navigation/Pokemon_MapData_Tests.h" #include "Pokemon/Navigation/Pokemon_RouteLog_Tests.h" +#include "Pokemon/Navigation/Pokemon_RouteScorer_Tests.h" #include "Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h" #include "Pokemon/Navigation/Pokemon_WallRecovery_Tests.h" #include "PokemonBDSP/PokemonBDSP_Tests.h" @@ -62,7 +63,6 @@ namespace ComputerPrograms{ UnitTestDatabase make_UNIT_TESTS_ALL(){ UnitTestDatabase ret; - add_tests_QtEventThreadPool(ret, GlobalThreadPools::computation_normal()); add_tests_Sockets(ret, GlobalThreadPools::unlimited_normal()); add_tests_BlackBorderDetector(ret); @@ -86,6 +86,7 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_MapData(ret); Pokemon::add_tests_RuntimeMap(ret); Pokemon::add_tests_RouteLog(ret); + Pokemon::add_tests_RouteScorer(ret); Pokemon::add_tests_AutoStory(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace.cpp new file mode 100644 index 0000000000..8043c6c8f4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace.cpp @@ -0,0 +1,267 @@ +/* Leg Trace + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Pokemon_LegTrace.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string_view leg_end_kind_name(LegEndKind kind){ + switch (kind){ + case LegEndKind::OPEN: + return "open"; + case LegEndKind::WALL: + return "wall"; + case LegEndKind::TILE: + return "tile"; + } + return "?"; +} + +std::string_view leg_end_known_name(LegEndKnown known){ + switch (known){ + case LegEndKnown::WALL: + return "wall"; + case LegEndKnown::FADE: + return "fade"; + case LegEndKnown::DIALOGUE: + return "dialogue"; + case LegEndKnown::COUNTED: + return "counted"; + case LegEndKnown::DEAD_RECKONED: + return "dead_reckoned"; + case LegEndKnown::SEEN: + return "seen"; + case LegEndKnown::UNKNOWN: + return "unknown"; + } + return "?"; +} + +std::string_view leg_interrupt_name(LegInterrupt interrupt){ + switch (interrupt){ + case LegInterrupt::WILD_BATTLE: + return "wild_battle"; + case LegInterrupt::TRAINER: + return "trainer"; + case LegInterrupt::SCENE: + return "scene"; + case LegInterrupt::DIALOGUE: + return "dialogue"; + case LegInterrupt::BLOCKED: + return "blocked"; + } + return "?"; +} + + +namespace{ + +// [["Route 202", 23, 25], ...] +JsonArray tiles_json(const std::vector& tiles){ + JsonArray out; + for (const RouteTile& tile : tiles){ + JsonArray entry; + entry.push_back(tile.map); + entry.push_back((int64_t)tile.pos.x); + entry.push_back((int64_t)tile.pos.y); + out.push_back(std::move(entry)); + } + return out; +} + +} // namespace + +std::string leg_trace_json(const LegRecord& record){ + JsonObject out; + out["checkpoint"] = record.checkpoint; + out["event"] = record.event; + out["leg"] = (int64_t)record.leg; + out["dir"] = direction_name(record.plan.direction); + out["tiles"] = (int64_t)record.plan.tiles; + out["end_kind"] = std::string(leg_end_kind_name(record.plan.end_kind)); + out["planned_end"] = tiles_json(record.plan.ends); + if (record.moved){ + out["moved"] = (int64_t)*record.moved; + } + out["chunks"] = (int64_t)record.chunks; + out["ms"] = record.walked_ms; + out["end"] = tiles_json(record.end); + out["known"] = std::string(leg_end_known_name(record.known)); + JsonArray interrupts; + for (LegInterrupt interrupt : record.interrupts){ + interrupts.push_back(std::string(leg_interrupt_name(interrupt))); + } + out["interrupts"] = std::move(interrupts); + if (!record.note.empty()){ + out["note"] = record.note; + } + return out.dump(-1); +} + +std::string leg_trace_line(const LegRecord& record){ + return std::string(LEG_TRACE_TAG) + leg_trace_json(record); +} + + +namespace{ + +std::optional parse_int(std::string_view text){ + int value = 0; + const auto result = std::from_chars(text.data(), text.data() + text.size(), value); + if (result.ec != std::errc() || result.ptr != text.data() + text.size()){ + return std::nullopt; + } + return value; +} + +// "Route 202 (23, 25)". +std::optional parse_route_tile(std::string_view text){ + const size_t open = text.rfind(" ("); + const size_t comma = text.rfind(", "); + if (open == std::string_view::npos || comma == std::string_view::npos || comma < open || !text.ends_with(")")){ + return std::nullopt; + } + const std::optional x = parse_int(text.substr(open + 2, comma - open - 2)); + const std::optional y = parse_int(text.substr(comma + 2, text.size() - comma - 3)); + if (open == 0 || !x || !y){ + return std::nullopt; + } + return RouteTile{std::string(text.substr(0, open)), TilePos{*x, *y}}; +} + +std::optional parse_direction(std::string_view text){ + for (Direction direction : ALL_DIRECTIONS){ + if (text == direction_name(direction)){ + return direction; + } + } + return std::nullopt; +} + +} // namespace + +std::vector parse_route_tiles(std::string_view text){ + std::vector out; + while (!text.empty()){ + // Each tile ends at its ")"; ", " separates them. + const size_t close = text.find(')'); + if (close == std::string_view::npos){ + return {}; + } + const std::optional tile = parse_route_tile(text.substr(0, close + 1)); + if (!tile){ + return {}; + } + out.push_back(*tile); + text.remove_prefix(close + 1); + if (text.starts_with(", ")){ + text.remove_prefix(2); + }else if (!text.empty()){ + return {}; + } + } + return out; +} + +std::optional parse_route_leg_line(std::string_view text){ + // "Leg /: () to " + if (!text.starts_with("Leg ")){ + return std::nullopt; + } + const size_t colon = text.find(": "); + if (colon == std::string_view::npos){ + return std::nullopt; + } + text.remove_prefix(colon + 2); + const size_t space = text.find(' '); + const size_t open = text.find(" ("); + const size_t close = text.find(") to "); + if (space == std::string_view::npos || open == std::string_view::npos || close == std::string_view::npos + || !(space <= open && open < close)){ + return std::nullopt; + } + const std::optional direction = parse_direction(text.substr(0, space)); + const std::optional tiles = parse_int(text.substr(space + 1, open - space - 1)); + const std::string_view end = text.substr(open + 2, close - open - 2); + if (!direction || !tiles || *tiles < 0){ + return std::nullopt; + } + LegPlan plan{.direction = *direction, .tiles = (size_t)*tiles}; + if (end == "to wall"){ + plan.end_kind = LegEndKind::WALL; + }else if (end == "warp"){ + plan.end_kind = LegEndKind::TILE; + }else if (end == "open"){ + plan.end_kind = LegEndKind::OPEN; + }else{ + return std::nullopt; + } + plan.ends = parse_route_tiles(text.substr(close + 5)); + return plan; +} + + +void LegTracer::begin_event(const std::string& checkpoint, const std::string& event){ + end_event(); + m_checkpoint = checkpoint; + m_event = event; + m_legs = 0; +} + +void LegTracer::end_event(){ + if (m_leg){ + end_leg({}, LegEndKnown::UNKNOWN); + } +} + +void LegTracer::begin_leg(LegPlan plan){ + end_event(); + m_leg = LegRecord{.checkpoint = m_checkpoint, .event = m_event, .leg = ++m_legs, .plan = std::move(plan)}; +} + +void LegTracer::walked(const LegWalk& walk){ + if (!m_leg){ + return; + } + m_leg->chunks += walk.chunks; + m_leg->walked_ms += walk.walked_ms; + for (size_t i = 0; i < walk.wild_battles; i++){ + m_leg->interrupts.push_back(LegInterrupt::WILD_BATTLE); + } + if (walk.tapped){ + m_leg->moved = m_leg->moved.value_or(0) + *walk.tapped; + } +} + +void LegTracer::interrupted(LegInterrupt interrupt){ + if (m_leg){ + m_leg->interrupts.push_back(interrupt); + } +} + +void LegTracer::end_leg(std::vector end, LegEndKnown known, std::string note){ + if (!m_leg){ + return; + } + LegRecord record = std::move(*m_leg); + m_leg.reset(); + record.end = std::move(end); + record.known = known; + record.note = std::move(note); + m_emit(leg_trace_line(record)); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace.h new file mode 100644 index 0000000000..d177c6e09b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace.h @@ -0,0 +1,167 @@ +/* Leg Trace + * + * From: https://github.com/PokemonAutomation/ + * + * One structured record per walked leg, shared by the games' walkers and + * their simulations, so a console run's route can be compared leg by leg + * with the simulation's (devtools/maps/leg_trace.py). Each leg is one log + * line beside the free-text route lines: + * + * [Leg] {"checkpoint":"00.04","event":"to_the_signs_row","leg":1, + * "dir":"north","tiles":1,"end_kind":"tile","moved":1,...} + * + * A record holds what was planned (direction, tiles, how the leg ends and + * the tiles it may end on), what was measured (taps that moved, the + * walk's moved chunks and held time), where the leg ended and how that is + * known, and what interrupted it. + * +// code-health: allow header_symbols -- leg trace diagnostic models and route execution logging types + */ + +#ifndef PokemonAutomation_Pokemon_LegTrace_H +#define PokemonAutomation_Pokemon_LegTrace_H + +#include +#include +#include +#include +#include +#include +#include +#include "Pokemon_Grid.h" +#include "Pokemon_RouteLog.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Prefix tag of a leg record's log line. +inline constexpr std::string_view LEG_TRACE_TAG = "[Leg] "; + +// How a leg is planned to end. +enum class LegEndKind{ + OPEN, // timed or tapped into the open + WALL, // held until a wall stops it + TILE, // counted taps onto an exact tile +}; +// "open", "wall", "tile". +std::string_view leg_end_kind_name(LegEndKind kind); + +// How the end of a leg is known. +enum class LegEndKnown{ + WALL, // a wall stopped the walk + FADE, // a warp's fade or banner ended it + DIALOGUE, // a dialogue stopped it + COUNTED, // taps that moved, counted against the map + DEAD_RECKONED, // taken to have ended as planned + SEEN, // stopped short, where the walker found itself + UNKNOWN, // not known: the leg was cut off +}; +// "wall", "fade", "dialogue", "counted", "dead_reckoned", "seen", "unknown". +std::string_view leg_end_known_name(LegEndKnown known); + +// What stopped or delayed a leg on the way. +enum class LegInterrupt{ + WILD_BATTLE, + TRAINER, + SCENE, + DIALOGUE, + BLOCKED, // someone the map lacks stood in the way +}; +// "wild_battle", "trainer", "scene", "dialogue", "blocked". +std::string_view leg_interrupt_name(LegInterrupt interrupt); + +// What a leg is planned to do. +struct LegPlan{ + Direction direction = Direction::NORTH; + size_t tiles = 0; + LegEndKind end_kind = LegEndKind::OPEN; + // Every tile the leg may end on; empty where the plan does not say. + std::vector ends; +}; + +// One walked leg. +struct LegRecord{ + std::string checkpoint; + std::string event; + // 1-based, counted through the event, replans included. + size_t leg = 0; + LegPlan plan; + // The taps that moved, where the leg counts them. + std::optional moved; + // What the walks of the leg report: chunks of screen movement, and the + // time the direction was held. + size_t chunks = 0; + int64_t walked_ms = 0; + // The tiles the leg ended on, as the walker knows them. + std::vector end; + LegEndKnown known = LegEndKnown::UNKNOWN; + std::vector interrupts; + // Why the leg ended other than as planned ("replan", "warp"), or "". + std::string note; +}; + +// The record as one line of compact JSON, keys sorted. +std::string leg_trace_json(const LegRecord& record); +// LEG_TRACE_TAG and the record's JSON. +std::string leg_trace_line(const LegRecord& record); + + +// The route log's text read back: "Route 202 (23, 25), Route 202 (30, 26)". +// Nothing for text that is not a list of tiles. +std::vector parse_route_tiles(std::string_view text); +// A route_leg_line() read back: "Leg 1/2: east 15 (to wall) to ". +// A warp leg ends at its tiles, as a tile leg. +std::optional parse_route_leg_line(std::string_view text); + + +// What one walk of a leg reports. +struct LegWalk{ + // Chunks of screen movement, and the time the direction was held. + size_t chunks = 0; + int64_t walked_ms = 0; + size_t wild_battles = 0; + // The taps that moved, for a walk of taps. + std::optional tapped; +}; + +// Builds a walker's leg records from what it does, and hands each, as its +// log line, to `emit` once the leg ends. A leg still open when the next +// starts, or when its event ends, is emitted with its end unknown. +class LegTracer{ +public: + explicit LegTracer(std::function emit) + : m_emit(std::move(emit)) + {} + + // The legs from here on are `event`'s of `checkpoint`. + void begin_event(const std::string& checkpoint, const std::string& event); + // Emits the leg still open, if one is. + void end_event(); + + // A leg starts. + void begin_leg(LegPlan plan); + // The open leg's plan; null if no leg is open. + const LegPlan* open_leg() const{ + return m_leg ? &m_leg->plan : nullptr; + } + // A walk of the open leg ended. A leg can take several (a walk on to + // the wall after a battle); they add up. + void walked(const LegWalk& walk); + void interrupted(LegInterrupt interrupt); + // The open leg ended on `end`, known by `known`; emits it. + void end_leg(std::vector end, LegEndKnown known, std::string note = ""); + +private: + std::function m_emit; + std::string m_checkpoint; + std::string m_event; + size_t m_legs = 0; + std::optional m_leg; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace_Tests.cpp new file mode 100644 index 0000000000..dc2c889309 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace_Tests.cpp @@ -0,0 +1,167 @@ +/* Leg Trace Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The leg record's line word for word, the route log's leg lines read + * back, and the tracer's records for a leg that ends, one cut off by the + * next, and one with a wild battle on the way. + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_LegTrace.h" +#include "Pokemon_LegTrace_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +struct LegTraceInput{ + std::string name; + std::function actual; +}; +struct LegTraceExpectation{ + std::string expected; +}; +struct LegTraceTestCase{ + LegTraceInput input; + LegTraceExpectation expectation; +}; + +class Test_LegTrace : public UnitTest{ +public: + explicit Test_LegTrace(LegTraceTestCase scenario) + : UnitTest("Pokemon::LegTrace - " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string actual = m_scenario.input.actual(); + if (actual == m_scenario.expectation.expected){ + return true; + } + return "expected:\n" + m_scenario.expectation.expected + "\ngot:\n" + actual; + } + +private: + LegTraceTestCase m_scenario; +}; + +std::string tiles_text(const std::vector& tiles){ + return tiles.empty() ? "none" : describe(tiles); +} + +std::string plan_text(const std::optional& plan){ + if (!plan){ + return "none"; + } + return std::string(direction_name(plan->direction)) + " " + std::to_string(plan->tiles) + " " + + std::string(leg_end_kind_name(plan->end_kind)) + " -> " + tiles_text(plan->ends); +} + +// The lines a tracer emits for `script`, one a line. +std::string traced(const std::function& script){ + std::string out; + LegTracer tracer([&](const std::string& line){ out += line + "\n"; }); + script(tracer); + return out; +} + +const LegTraceTestCase CASES[] = { + { + .input = {.name = "a tap leg's line", .actual = []{ + LegRecord record{ + .checkpoint = "00.04", .event = "to_the_signs_row", .leg = 1, + .plan = {.direction = Direction::NORTH, .tiles = 1, .end_kind = LegEndKind::TILE, + .ends = {{"Route 201", {57, 4}}}}, + .moved = 1, .chunks = 1, .walked_ms = 800, + .end = {{"Route 201", {57, 4}}}, .known = LegEndKnown::COUNTED, + }; + return leg_trace_line(record); + }}, + .expectation = {.expected = + "[Leg] {\"checkpoint\":\"00.04\",\"chunks\":1,\"dir\":\"north\",\"end\":[[\"Route 201\",57,4]]," + "\"end_kind\":\"tile\",\"event\":\"to_the_signs_row\",\"interrupts\":[],\"known\":\"counted\"," + "\"leg\":1,\"moved\":1,\"ms\":800,\"planned_end\":[[\"Route 201\",57,4]],\"tiles\":1}"}, + }, + { + .input = {.name = "tiles read back", .actual = []{ + return tiles_text(parse_route_tiles("Route 202 (23, 25), Mom's House (30, -1)")); + }}, + .expectation = {.expected = "Route 202 (23, 25), Mom's House (30, -1)"}, + }, + { + .input = {.name = "no tiles in other text", .actual = []{ + return tiles_text(parse_route_tiles("an unknown tile")); + }}, + .expectation = {.expected = "none"}, + }, + { + .input = {.name = "a wall leg line read back", .actual = []{ + return plan_text(parse_route_leg_line("Leg 1/2: east 15 (to wall) to Route 202 (23, 25), Route 202 (30, 26)")); + }}, + .expectation = {.expected = "east 15 wall -> Route 202 (23, 25), Route 202 (30, 26)"}, + }, + { + .input = {.name = "an open leg line read back", .actual = []{ + return plan_text(parse_route_leg_line("Leg 3/3: west 1 (open) to Twinleaf Town (7, 9)")); + }}, + .expectation = {.expected = "west 1 open -> Twinleaf Town (7, 9)"}, + }, + { + .input = {.name = "not a leg line", .actual = []{ + return plan_text(parse_route_leg_line("[Route] Turning west.")); + }}, + .expectation = {.expected = "none"}, + }, + { + .input = {.name = "a leg cut off by the next, and by its event's end", .actual = []{ + return traced([](LegTracer& tracer){ + tracer.begin_event("00.04", "beside_mom"); + tracer.begin_leg({.direction = Direction::WEST, .tiles = 2, .end_kind = LegEndKind::OPEN}); + tracer.begin_leg({.direction = Direction::NORTH, .tiles = 1, .end_kind = LegEndKind::WALL}); + tracer.walked({.chunks = 3, .walked_ms = 640}); + tracer.begin_event("00.04", "mom"); + }); + }}, + .expectation = {.expected = + "[Leg] {\"checkpoint\":\"00.04\",\"chunks\":0,\"dir\":\"west\",\"end\":[],\"end_kind\":\"open\"," + "\"event\":\"beside_mom\",\"interrupts\":[],\"known\":\"unknown\",\"leg\":1,\"ms\":0,\"planned_end\":[],\"tiles\":2}\n" + "[Leg] {\"checkpoint\":\"00.04\",\"chunks\":3,\"dir\":\"north\",\"end\":[],\"end_kind\":\"wall\"," + "\"event\":\"beside_mom\",\"interrupts\":[],\"known\":\"unknown\",\"leg\":2,\"ms\":640,\"planned_end\":[],\"tiles\":1}\n"}, + }, + { + .input = {.name = "a wild battle on the way, two walks to the wall", .actual = []{ + return traced([](LegTracer& tracer){ + tracer.begin_event("00.04b", "to_catch_grass"); + tracer.begin_leg({.direction = Direction::SOUTH, .tiles = 4, .end_kind = LegEndKind::WALL}); + tracer.walked({.chunks = 2, .walked_ms = 500, .wild_battles = 1}); + tracer.walked({.chunks = 2, .walked_ms = 400}); + tracer.end_leg({{"Route 202", {20, 27}}}, LegEndKnown::WALL); + tracer.end_event(); + }); + }}, + .expectation = {.expected = + "[Leg] {\"checkpoint\":\"00.04b\",\"chunks\":4,\"dir\":\"south\",\"end\":[[\"Route 202\",20,27]],\"end_kind\":\"wall\"," + "\"event\":\"to_catch_grass\",\"interrupts\":[\"wild_battle\"],\"known\":\"wall\",\"leg\":1,\"ms\":900,\"planned_end\":[],\"tiles\":4}\n"}, + }, +}; + +} // namespace + + +void add_tests_LegTrace(UnitTestDatabase& database){ + for (const auto& scenario : CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace_Tests.h new file mode 100644 index 0000000000..a81561fa7f --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTrace_Tests.h @@ -0,0 +1,23 @@ +/* Leg Trace Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_LegTrace_Tests_H +#define PokemonAutomation_Pokemon_LegTrace_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers leg trace record and tracer unit tests. +void add_tests_LegTrace(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp index 843fc32db0..2039c5c62e 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp @@ -13,6 +13,7 @@ #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_LegTrace_Tests.h" #include "Pokemon_RouteLog.h" #include "Pokemon_RouteLog_Tests.h" @@ -198,6 +199,8 @@ void add_tests_RouteLog(UnitTestDatabase& database){ for (const auto& scenario : CASES){ database.add(scenario); } + // The leg records read the route lines back. + add_tests_LegTrace(database); } diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.cpp new file mode 100644 index 0000000000..9e216d8791 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.cpp @@ -0,0 +1,504 @@ +/* Route Scorer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Pokemon_RouteScorer.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +std::string to_string(const ScoredLeg& leg){ + std::string_view how = "taps"; + switch (leg.kind){ + case ScoredLegKind::TO_WALL: + how = leg.run ? "run to wall" : "walk to wall"; + break; + case ScoredLegKind::OPEN_HOLD: + how = leg.run ? "run, open" : "walk, open"; + break; + case ScoredLegKind::TAPS: + break; + } + return std::format("{} {} ({})", direction_name(leg.direction), leg.tiles, how); +} + +size_t tiles_walked_back(const std::vector& legs){ + size_t tiles = 0; + for (size_t i = 0; i < legs.size(); i++){ + const Direction back = Direction(((int)legs[i].direction + 2) % 4); + if (i > 0 && legs[i - 1].kind == ScoredLegKind::TO_WALL && legs[i - 1].direction == back){ + continue; + } + for (size_t j = 0; j < i; j++){ + if (legs[j].direction == back){ + tiles += legs[i].tiles; + break; + } + } + } + return tiles; +} + +std::string_view verdict_name(RouteVerdict verdict){ + switch (verdict){ + case RouteVerdict::PASS: + return "PASS"; + case RouteVerdict::FAIL: + return "FAIL"; + case RouteVerdict::STRAND: + return "STRAND"; + case RouteVerdict::RETRIES: + return "RETRIES"; + } + return "?"; +} + + +namespace{ + +size_t distance(const TilePos& a, const TilePos& b){ + return (size_t)(std::abs(a.x - b.x) + std::abs(a.y - b.y)); +} + +bool stops_on(TileRisk risk){ + return risk == TileRisk::WARP || risk == TileRisk::TRIGGER; +} + +// One leg walked from one tile, nothing interrupting. +struct LegWalk{ + std::vector path; // tiles surely walked, in order, the first after the start + std::vector ends; // where the leg may end + long long ms = 0; + bool stop = false; // ended at a wall (a re-localization) + size_t taps = 0; + std::string unsafe; // why the leg may end somewhere it must not +}; + +// Steps from `from` until stopped, at most `most` steps; stops on a warp +// or a trigger. +std::vector walk_steps(const ScoreMap& map, const TilePos& from, Direction direction, size_t most){ + std::vector path; + TilePos at = from; + while (path.size() < most){ + const std::optional next = map.step(at, direction); + if (!next){ + break; + } + path.push_back(*next); + at = *next; + if (stops_on(map.risk(at))){ + break; + } + } + return path; +} + +size_t path_tiles(const TilePos& from, const std::vector& path){ + size_t tiles = 0; + TilePos at = from; + for (const TilePos& pos : path){ + tiles += distance(at, pos); + at = pos; + } + return tiles; +} + +LegWalk walk_to_wall(const ScoreMap& map, const TilePos& from, const ScoredLeg& leg, const RoutePaces& paces){ + LegWalk walk; + walk.path = walk_steps(map, from, leg.direction, (size_t)-1); + walk.ends = {walk.path.empty() ? from : walk.path.back()}; + walk.stop = walk.path.empty() || !stops_on(map.risk(walk.path.back())); + walk.ms = paces.start_ms + (long long)path_tiles(from, walk.path) * paces.ms_per_tile(leg.direction, leg.run) + + (walk.stop ? paces.stop_ms : 0); + return walk; +} + +LegWalk walk_taps(const ScoreMap& map, const TilePos& from, const ScoredLeg& leg, const RoutePaces& paces){ + LegWalk walk; + walk.path = walk_steps(map, from, leg.direction, leg.tiles); + walk.ends = {walk.path.empty() ? from : walk.path.back()}; + const bool blocked = walk.path.size() < leg.tiles && (walk.path.empty() || !stops_on(map.risk(walk.path.back()))); + // A blocked walk of taps ends after two taps that move nothing. + walk.taps = walk.path.size() + (blocked ? 2 : 0); + walk.ms = (long long)walk.taps * paces.tap_ms; + return walk; +} + +// Why a tile in a held leg's uncertain end must not be reached, or "". +std::string unsafe_overshoot(const ScoreMap& map, const TilePos& before, const TilePos& pos, + const std::function& goal +){ + if (distance(before, pos) > 1){ + return "a ledge hop at " + to_string(pos); + } + switch (map.risk(pos)){ + case TileRisk::NONE: + return ""; + case TileRisk::TRIGGER: + return goal(pos) ? "" : "a trigger at " + to_string(pos); + case TileRisk::WARP: + return goal(pos) ? "" : "a warp at " + to_string(pos); + case TileRisk::ENCOUNTER: + return "grass at " + to_string(pos); + case TileRisk::WANDERER: + return "a wanderer's tile at " + to_string(pos); + case TileRisk::SIGHT: + return "a trainer's sight at " + to_string(pos); + } + return ""; +} + +LegWalk walk_open_hold(const ScoreMap& map, const TilePos& from, const ScoredLeg& leg, + const RoutePaces& paces, const std::function& goal +){ + const size_t error = paces.open_hold_error ? paces.open_hold_error(leg.tiles) : 0; + const size_t fewest = leg.tiles > error ? leg.tiles - error : 0; + const std::vector all = walk_steps(map, from, leg.direction, leg.tiles + error); + LegWalk walk; + walk.path.assign(all.begin(), all.begin() + std::min(fewest, all.size())); + for (size_t k = fewest; k <= all.size(); k++){ + walk.ends.push_back(k == 0 ? from : all[k - 1]); + if (k > fewest && walk.unsafe.empty()){ + walk.unsafe = unsafe_overshoot(map, k == 1 ? from : all[k - 2], all[k - 1], goal); + } + } + walk.ms = paces.start_ms + (long long)leg.tiles * paces.ms_per_tile(leg.direction, leg.run); + return walk; +} + +LegWalk walk_leg(const ScoreMap& map, const TilePos& from, const ScoredLeg& leg, + const RoutePaces& paces, const std::function& goal +){ + LegWalk walk; + switch (leg.kind){ + case ScoredLegKind::TO_WALL: + walk = walk_to_wall(map, from, leg, paces); + break; + case ScoredLegKind::TAPS: + walk = walk_taps(map, from, leg, paces); + break; + case ScoredLegKind::OPEN_HOLD: + walk = walk_open_hold(map, from, leg, paces, goal); + break; + } + walk.ms += paces.press_ms; + return walk; +} + + +// One way the walk may have gone so far, from one start tile. +struct Branch{ + TilePos pos; + long long ms = 0; + double weight = 0; // chance of this branch, the starts equally likely + bool sighted = false; // a trainer has seen us (and been fought) +}; + +// Where an interruption may happen, and what it costs. +struct Interruption{ + size_t leg; + size_t steps; // steps of the leg walked when it happens + TilePos from; // where the leg started + TilePos at; + double chance; + long long cost_ms; + double weight; +}; + +// The plan from where an interruption leaves the player on: the rest of +// the interrupted leg, then the legs after it. +std::vector rest_of_plan(const std::vector& legs, const Interruption& stop){ + const ScoredLeg& leg = legs[stop.leg]; + std::vector rest; + if (leg.kind == ScoredLegKind::TO_WALL || stop.steps < leg.tiles){ + ScoredLeg left = leg; + left.tiles = leg.kind == ScoredLegKind::TO_WALL ? leg.tiles : leg.tiles - stop.steps; + rest.push_back(left); + } + rest.insert(rest.end(), legs.begin() + stop.leg + 1, legs.end()); + return rest; +} + +// The tiles an interruption on a leg without a wall may leave us on: a +// tap lost or one too many either way. +std::vector unsure_tiles(const ScoreMap& map, const ScoredLeg& leg, const Interruption& stop){ + std::vector tiles{stop.at}; + if (leg.kind == ScoredLegKind::TO_WALL){ + return tiles; + } + const std::vector back = walk_steps(map, stop.at, Direction((int(leg.direction) + 2) % 4), 1); + const std::vector ahead = walk_steps(map, stop.at, leg.direction, 1); + tiles.insert(tiles.end(), back.begin(), back.end()); + tiles.insert(tiles.end(), ahead.begin(), ahead.end()); + return tiles; +} + +std::string key_of(std::vector tiles){ + std::sort(tiles.begin(), tiles.end(), [](const TilePos& a, const TilePos& b){ + return a.y != b.y ? a.y < b.y : a.x < b.x; + }); + std::string key; + for (const TilePos& pos : tiles){ + key += to_string(pos); + } + return key; +} + + +// What a nominal walk of a plan gives: the branches at its end, the +// interruptions it may meet, and how it may fail. +struct PlanWalk{ + std::vector branches; + std::vector interruptions; + size_t stops = 0; + size_t presses = 0; + std::string fail; +}; + +class Scorer{ +public: + Scorer(const ScoreMap& map, const std::function& goal, + const RoutePaces& paces, const InterruptModel& model, const RouteReplanner& replan + ) + : m_map(map), m_goal(goal), m_paces(paces), m_model(model), m_replan(replan) + {} + + RouteScore score(const std::vector& from, const std::vector& legs, size_t depth); + +private: + PlanWalk walk_plan(const std::vector& from, const std::vector& legs) const; + void walk_branch(PlanWalk& out, const Branch& branch, size_t index, const ScoredLeg& leg, + bool last, std::map& next) const; + void add_interruptions(PlanWalk& out, Branch& branch, size_t index, const TilePos& from, const LegWalk& walk) const; + void recover(RouteScore& score, const std::vector& legs, const Interruption& stop, size_t depth); + RouteScore recovery_score(const std::vector& unsure, size_t depth); + bool relocalizes(const std::vector& unsure, const std::vector& legs) const; + static void fail(RouteScore& score, RouteVerdict verdict, const std::string& why); + + const ScoreMap& m_map; + const std::function& m_goal; + const RoutePaces& m_paces; + const InterruptModel& m_model; + const RouteReplanner& m_replan; + std::map m_done; + std::set m_open; + // Recoveries in progress whose plan first stops every tile at one wall + // out of harm's way (relocalizes()). + std::set m_relocalizing; +}; + +// Whether `legs` from `unsure` first walk every tile to one wall tile +// where nothing interrupts. A recovery that does is a retry from a known +// place: if it is interrupted where it was before, the walk does the same +// again, each time with the interruption's chance, so it ends. +bool Scorer::relocalizes(const std::vector& unsure, const std::vector& legs) const{ + if (legs.empty() || legs.front().kind != ScoredLegKind::TO_WALL){ + return false; + } + std::optional end; + for (const TilePos& pos : unsure){ + const LegWalk walk = walk_to_wall(m_map, pos, legs.front(), m_paces); + if (!walk.stop || (end && *end != walk.ends.front())){ + return false; + } + end = walk.ends.front(); + } + return end && m_map.risk(*end) == TileRisk::NONE; +} + +void Scorer::fail(RouteScore& score, RouteVerdict verdict, const std::string& why){ + if (score.verdict == RouteVerdict::PASS){ + score.verdict = verdict; + score.why = why; + } +} + +void Scorer::add_interruptions(PlanWalk& out, Branch& branch, size_t index, const TilePos& from, const LegWalk& walk) const{ + for (size_t k = 0; k < walk.path.size(); k++){ + const TilePos& at = walk.path[k]; + Interruption stop{.leg = index, .steps = k + 1, .from = from, .at = at, .chance = 0, .cost_ms = 0, .weight = branch.weight}; + switch (m_map.risk(at)){ + case TileRisk::ENCOUNTER: + stop.chance = m_model.encounter_per_tile; + stop.cost_ms = m_model.encounter_ms; + break; + case TileRisk::WANDERER: + stop.chance = m_model.wanderer_per_tile; + stop.cost_ms = m_model.wanderer_ms; + break; + case TileRisk::SIGHT: + stop.chance = branch.sighted ? 0 : 1; + stop.cost_ms = m_model.trainer_ms; + branch.sighted = true; + break; + default: + break; + } + if (stop.chance > 0){ + out.interruptions.push_back(stop); + } + } +} + +void Scorer::walk_branch(PlanWalk& out, const Branch& branch, size_t index, const ScoredLeg& leg, + bool last, std::map& next +) const{ + const LegWalk walk = walk_leg(m_map, branch.pos, leg, m_paces, m_goal); + if (!walk.unsafe.empty() && out.fail.empty()){ + out.fail = std::format("leg {} ({}) from {} may overshoot onto {}", index + 1, to_string(leg), to_string(branch.pos), walk.unsafe); + } + for (const TilePos& pos : walk.path){ + if (m_map.risk(pos) == TileRisk::WARP && !(last && pos == walk.path.back() && m_goal(pos)) && out.fail.empty()){ + out.fail = std::format("leg {} ({}) from {} walks into the warp at {}", index + 1, to_string(leg), to_string(branch.pos), to_string(pos)); + } + } + Branch walked = branch; + walked.ms += walk.ms; + add_interruptions(out, walked, index, branch.pos, walk); + for (const TilePos& end : walk.ends){ + Branch b = walked; + b.pos = end; + b.weight = walked.weight / (double)walk.ends.size(); + auto [it, added] = next.try_emplace(key_of({end}), b); + if (!added){ + it->second.weight += b.weight; + it->second.ms = std::max(it->second.ms, b.ms); + } + } +} + +PlanWalk Scorer::walk_plan(const std::vector& from, const std::vector& legs) const{ + PlanWalk out; + for (const TilePos& pos : from){ + out.branches.push_back({.pos = pos, .ms = 0, .weight = 1.0 / (double)from.size(), .sighted = false}); + } + for (size_t i = 0; i < legs.size(); i++){ + std::map next; + for (const Branch& branch : out.branches){ + walk_branch(out, branch, i, legs[i], i + 1 == legs.size(), next); + } + out.branches.clear(); + for (auto& item : next){ + out.branches.push_back(item.second); + } + if (out.branches.size() > m_model.max_spread && out.fail.empty()){ + out.fail = std::format("after leg {} the player may be on {} tiles", i + 1, out.branches.size()); + } + out.presses += legs[i].kind == ScoredLegKind::TAPS ? legs[i].tiles : 1; + out.stops += legs[i].kind == ScoredLegKind::TO_WALL ? 1 : 0; + } + for (const Branch& branch : out.branches){ + if (!m_goal(branch.pos) && out.fail.empty()){ + out.fail = "may end on " + to_string(branch.pos) + ", off the goal"; + } + } + return out; +} + +RouteScore Scorer::recovery_score(const std::vector& unsure, size_t depth){ + RouteScore score; + const std::string key = key_of(unsure); + if (m_open.contains(key)){ + // A retry from a wall: charged its replan alone (recover()). + if (!m_relocalizing.contains(key)){ + fail(score, RouteVerdict::STRAND, "the recovery from " + key + " leads back to itself"); + } + return score; + } + const auto done = m_done.find(key); + if (done != m_done.end()){ + return done->second; + } + if (depth > m_model.max_recoveries){ + fail(score, RouteVerdict::RETRIES, std::format("more than {} recoveries in a row, at {}", m_model.max_recoveries, key)); + return score; + } + const std::optional> legs = m_replan ? m_replan(unsure) : std::nullopt; + if (!legs){ + fail(score, RouteVerdict::FAIL, "no recovery from " + key); + return score; + } + m_open.insert(key); + if (relocalizes(unsure, *legs)){ + m_relocalizing.insert(key); + } + score = this->score(unsure, *legs, depth); + m_open.erase(key); + m_relocalizing.erase(key); + if (score.verdict != RouteVerdict::PASS){ + score.why = "recovery from " + key + ": " + score.why; + } + m_done[key] = score; + return score; +} + +void Scorer::recover(RouteScore& score, const std::vector& legs, const Interruption& stop, size_t depth){ + score.recoveries++; + const ScoredLeg& leg = legs[stop.leg]; + const std::vector rest = rest_of_plan(legs, stop); + const PlanWalk resumed_exact = walk_plan({stop.at}, rest); + const long long rest_ms = resumed_exact.branches.empty() ? 0 : resumed_exact.branches.front().ms; + const std::vector unsure = unsure_tiles(m_map, leg, stop); + const PlanWalk resumed = walk_plan(unsure, rest); + long long extra_ms = m_paces.start_ms + m_paces.press_ms; + long long extra_worst = extra_ms; + if (!resumed.fail.empty()){ + score.replans++; + const RouteScore again = recovery_score(unsure, depth + 1); + if (again.verdict != RouteVerdict::PASS){ + fail(score, again.verdict, std::format("leg {} interrupted at {}: {}", stop.leg + 1, to_string(stop.at), again.why)); + return; + } + extra_ms = std::max(0, m_model.replan_ms + (long long)again.expected_ms - rest_ms); + extra_worst = std::max(0, m_model.replan_ms + again.worst_ms - rest_ms); + } + score.expected_ms += stop.weight * stop.chance * (double)(stop.cost_ms + extra_ms); + score.worst_ms = std::max(score.worst_ms, score.nominal_ms + stop.cost_ms + extra_worst); +} + +RouteScore Scorer::score(const std::vector& from, const std::vector& legs, size_t depth){ + RouteScore score; + const PlanWalk walk = walk_plan(from, legs); + score.stops = walk.stops; + score.presses = walk.presses; + for (const Branch& branch : walk.branches){ + score.nominal_ms = std::max(score.nominal_ms, branch.ms); + score.expected_ms += branch.weight * (double)branch.ms; + } + score.worst_ms = score.nominal_ms; + if (!walk.fail.empty()){ + fail(score, RouteVerdict::FAIL, walk.fail); + return score; + } + for (const Interruption& stop : walk.interruptions){ + recover(score, legs, stop, depth); + } + return score; +} + +} // namespace + + +RouteScore score_route( + const ScoreMap& map, const std::vector& from, + const std::function& goal, + const std::vector& legs, + const RoutePaces& paces, const InterruptModel& model, + const RouteReplanner& replan +){ + Scorer scorer(map, goal, paces, model, replan); + return scorer.score(from, legs, 0); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.h new file mode 100644 index 0000000000..4c844da83b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer.h @@ -0,0 +1,150 @@ +/* Route Scorer + * +// code-health: allow header_symbols -- route scoring profile definitions and path evaluation criteria + * + * From: https://github.com/PokemonAutomation/ + * + * Scores a walk plan on a tile grid: how long it takes on the game's + * measured paces, from every tile the player may start on, and whether it + * can go wrong. A leg held to a wall ends where the wall stops it; a leg of + * taps moves exactly its taps; a held open leg may end a few tiles short or + * long, and those tiles must be safe. Interruptions on the way (a wild + * battle in grass, someone walking about, a trainer's sight) are charged by + * their chance times the recovery they need, and a recovery that can lead + * back into itself strands the player: the plan fails. + * + * Game-neutral: the game supplies the step rules, the tile risks, its + * paces and hold error (RoutePaces), how often and how dearly it is + * interrupted (InterruptModel) and, for recoveries, its replanner. Nothing + * here defaults to one game's numbers: BDSP's profile is in + * PokemonBDSP_AutoStory_RouteChoice. FRLG, to use it, must supply its own + * paces (walk, run and the bike's, as RoutePaces::ms_per_tile's "run" is + * one faster pace), its hold error, its encounter rates, and later the + * tiles that move the player on their own (spinners, currents), which + * ScoreMap::step does not model yet. + * + */ + +#ifndef PokemonAutomation_Pokemon_RouteScorer_H +#define PokemonAutomation_Pokemon_RouteScorer_H + +#include +#include +#include +#include +#include +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What walking onto a tile risks. +enum class TileRisk{ + NONE, + ENCOUNTER, // tall grass: a wild battle may start + WANDERER, // someone walking about may stand in the way + SIGHT, // a trainer sees the player and walks over + WARP, // a door or warp: walking onto it leaves the map + TRIGGER, // a scene starts here and stops the player +}; + +// The grid a plan is scored on. +struct ScoreMap{ + // Where one step from a tile lands (a ledge hop lands two tiles on), or + // nothing if the player is stopped. A warp's tile is landed on. + std::function(const TilePos&, Direction)> step; + std::function risk; +}; + +// How a leg is walked. +enum class ScoredLegKind{ + TO_WALL, // held until the player stops: lands exactly + TAPS, // one D-pad tap per tile: lands exactly + OPEN_HOLD, // held for its tiles' time: may land a few tiles off +}; +// One leg of a plan. +struct ScoredLeg{ + Direction direction = Direction::NORTH; + size_t tiles = 0; + ScoredLegKind kind = ScoredLegKind::TAPS; + bool run = false; // held at a run (B), not a walk +}; +// "west 16 (taps)", "south 33 (run to wall)". +std::string to_string(const ScoredLeg& leg); + +// Tiles `legs` walk back: each leg opposite to a leg before it. A planned +// stop at a wall re-localizes and is not counted, nor are the taps back +// from it right after (running past the goal to a wall and tapping back, +// as the user walks into Twinleaf). +size_t tiles_walked_back(const std::vector& legs); + +// The game's measured times. The game sets every field. +struct RoutePaces{ + // Time per tile held in a direction, walking or running. + std::function ms_per_tile; + long long start_ms = 0; // from pressing to the first step + long long tap_ms = 0; // one tap and its release + long long press_ms = 0; // a leg's overhead: the turn, the watch + long long stop_ms = 0; // confirming a stop at a wall (a re-localization) + // How many tiles short or long a held open leg of so many tiles may + // end. Null: a hold ends exactly. + std::function open_hold_error; +}; + +// How interruptions are charged. The game sets the chances and costs; +// none charges nothing. +struct InterruptModel{ + double encounter_per_tile = 0; + long long encounter_ms = 0; // a wild battle run from + double wanderer_per_tile = 0; + long long wanderer_ms = 0; // waiting for them to move on + long long trainer_ms = 0; // a trainer battle + long long replan_ms = 0; // a stop and a new plan + // Most recoveries in a row before the plan counts as stuck. + size_t max_recoveries = 3; + // Most tiles the player may be on at once, before a plan is too loose. + size_t max_spread = 32; +}; + +// A new plan from where an interruption left the player, or nothing if +// none exists. Null: a recovery that needs a new plan fails. +using RouteReplanner = std::function>(const std::vector& from)>; + +// Whether a plan gets there, from every start and through every recovery. +enum class RouteVerdict{ + PASS, + FAIL, // may end off the goal, overshoot onto a hazard, or never arrive + STRAND, // a recovery can lead back into itself without first stopping at a wall out of harm's way + RETRIES, // more recoveries in a row than InterruptModel::max_recoveries +}; +// "PASS", "FAIL", "STRAND", "RETRIES". +std::string_view verdict_name(RouteVerdict verdict); + +// A plan's score. +struct RouteScore{ + RouteVerdict verdict = RouteVerdict::PASS; + std::string why; // for a verdict other than PASS + long long nominal_ms = 0; // slowest start, nothing interrupting + double expected_ms = 0; // average start, interruptions by their chance + long long worst_ms = 0; // slowest start and the costliest single interruption + size_t stops = 0; // legs that end on a wall: each re-localizes + size_t presses = 0; // legs plus taps + size_t recoveries = 0; // places an interruption may happen + size_t replans = 0; // of those, the ones the plan's own legs cannot absorb +}; + +// Scores `legs` walked from any of `from` toward tiles `goal` accepts. +RouteScore score_route( + const ScoreMap& map, const std::vector& from, + const std::function& goal, + const std::vector& legs, + const RoutePaces& paces, const InterruptModel& model, + const RouteReplanner& replan = nullptr +); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp new file mode 100644 index 0000000000..a80bb7f59d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.cpp @@ -0,0 +1,382 @@ +/* Route Scorer Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The scorer on small made-up grids. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_RouteScorer_Tests.h" +#include "Pokemon_RouteScorer.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// '#' wall, '.' floor, '"' tall grass, 'D' a warp, 'T' a scene's trigger, +// 'w' a wanderer's tile, 's' a trainer's sight, 'v' a ledge hopped south. +class ToyMap{ +public: + explicit ToyMap(std::vector rows) + : m_rows(std::move(rows)) + {} + + char at(const TilePos& pos) const{ + if (pos.y < 0 || pos.y >= (int)m_rows.size() || pos.x < 0 || pos.x >= (int)m_rows[pos.y].size()){ + return '#'; + } + return m_rows[pos.y][pos.x]; + } + ScoreMap score_map() const{ + return { + .step = [this](const TilePos& from, Direction direction) -> std::optional{ + const TilePos next = from.next(direction); + if (at(next) == 'v'){ + return direction == Direction::SOUTH ? std::optional(next.next(direction)) : std::nullopt; + } + return at(next) == '#' ? std::nullopt : std::optional(next); + }, + .risk = [this](const TilePos& pos){ + switch (at(pos)){ + case '"': + return TileRisk::ENCOUNTER; + case 'D': + return TileRisk::WARP; + case 'T': + return TileRisk::TRIGGER; + case 'w': + return TileRisk::WANDERER; + case 's': + return TileRisk::SIGHT; + default: + return TileRisk::NONE; + } + }, + }; + } + +private: + std::vector m_rows; +}; + +RoutePaces toy_paces(){ + return { + .ms_per_tile = [](Direction, bool run){ return run ? 100LL : 250LL; }, + .start_ms = 250, .tap_ms = 800, .press_ms = 100, .stop_ms = 1000, + .open_hold_error = [](size_t tiles){ return 1 + tiles / 5; }, + }; +} + +InterruptModel toy_model(){ + InterruptModel model; + model.encounter_per_tile = 0.1; + model.encounter_ms = 12000; + model.wanderer_per_tile = 0.25; + model.wanderer_ms = 2500; + model.trainer_ms = 45000; + model.replan_ms = 2000; + return model; +} + +std::function exactly(const TilePos& goal){ + return [goal](const TilePos& pos){ return pos == goal; }; +} + +RouteScore score(const ToyMap& toy, const std::vector& from, const TilePos& goal, + const std::vector& legs, const RouteReplanner& replan = nullptr, const InterruptModel& model = toy_model() +){ + return score_route(toy.score_map(), from, exactly(goal), legs, toy_paces(), model, replan); +} + +// "" if `got` has `verdict`, else why not. +std::string expect(const RouteScore& got, RouteVerdict verdict, const std::string& what){ + if (got.verdict != verdict){ + return std::format("{}: expected {}, got {} ({})", what, verdict_name(verdict), verdict_name(got.verdict), got.why); + } + return ""; +} + +// Passes if every check is "". +UnitTestResult all_of(std::initializer_list checks){ + for (const std::string& check : checks){ + if (!check.empty()){ + return check; + } + } + return true; +} + +UnitTestResult test_taps_time(){ + const ToyMap toy({"......"}); + const RouteScore got = score(toy, {{0, 0}}, {4, 0}, {{.direction = Direction::EAST, .tiles = 4, .kind = ScoredLegKind::TAPS}}); + if (got.verdict != RouteVerdict::PASS || got.nominal_ms != 4 * 800 + 100 || got.presses != 4 || got.stops != 0){ + return std::format("4 taps: {} {} ms, {} presses, {} stops", verdict_name(got.verdict), got.nominal_ms, got.presses, got.stops); + } + return true; +} + +UnitTestResult test_run_to_wall_beats_taps(){ + const ToyMap toy({"......#"}); + const RouteScore taps = score(toy, {{0, 0}}, {5, 0}, {{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}); + const RouteScore run = score(toy, {{0, 0}}, {5, 0}, {{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TO_WALL, .run = true}}); + if (run.verdict != RouteVerdict::PASS || run.nominal_ms != 250 + 500 + 1000 + 100 || run.stops != 1){ + return std::format("run: {} {} ms ({})", verdict_name(run.verdict), run.nominal_ms, run.why); + } + return run.expected_ms < taps.expected_ms ? UnitTestResult(true) : UnitTestResult("the run is not faster than the taps"); +} + +UnitTestResult test_wall_collapses_a_set(){ + // Three columns, all stopped by row 2's wall, then taps west. + const ToyMap toy({".....", ".....", "#####"}); + const RouteScore got = score(toy, {{2, 0}}, {0, 1}, { + {.direction = Direction::EAST, .tiles = 2, .kind = ScoredLegKind::OPEN_HOLD, .run = true}, + {.direction = Direction::SOUTH, .tiles = 1, .kind = ScoredLegKind::TO_WALL}, + {.direction = Direction::WEST, .tiles = 4, .kind = ScoredLegKind::TO_WALL}, + }); + return all_of({expect(got, RouteVerdict::PASS, "open run east, then walls south and west")}); +} + +UnitTestResult test_open_hold_off_the_goal(){ + const ToyMap toy({"........"}); + const RouteScore got = score(toy, {{0, 0}}, {3, 0}, {{.direction = Direction::EAST, .tiles = 3, .kind = ScoredLegKind::OPEN_HOLD}}); + return all_of({expect(got, RouteVerdict::FAIL, "an open hold with nothing to stop it")}); +} + +UnitTestResult test_open_hold_into_grass(){ + const ToyMap toy({"....\"\"\"#"}); + const RouteScore got = score(toy, {{0, 0}}, {6, 0}, { + {.direction = Direction::EAST, .tiles = 3, .kind = ScoredLegKind::OPEN_HOLD}, + {.direction = Direction::EAST, .tiles = 3, .kind = ScoredLegKind::TO_WALL}, + }); + return all_of({expect(got, RouteVerdict::FAIL, "an open hold whose overshoot reaches grass")}); +} + +UnitTestResult test_open_hold_onto_a_ledge(){ + const ToyMap toy({".", ".", ".", "v", ".", "#"}); + const RouteScore got = score(toy, {{0, 0}}, {0, 4}, { + {.direction = Direction::SOUTH, .tiles = 2, .kind = ScoredLegKind::OPEN_HOLD}, + {.direction = Direction::SOUTH, .tiles = 2, .kind = ScoredLegKind::TO_WALL}, + }); + return all_of({expect(got, RouteVerdict::FAIL, "an open hold whose overshoot hops a ledge")}); +} + +UnitTestResult test_open_hold_before_a_wall(){ + const ToyMap toy({".....#"}); + const RouteScore got = score(toy, {{0, 0}}, {4, 0}, {{.direction = Direction::EAST, .tiles = 4, .kind = ScoredLegKind::OPEN_HOLD, .run = true}}); + return all_of({ + expect(got, RouteVerdict::FAIL, "an open hold that may stop a tile short"), + expect(score(toy, {{0, 0}}, {4, 0}, {{.direction = Direction::EAST, .tiles = 3, .kind = ScoredLegKind::OPEN_HOLD, .run = true}, + {.direction = Direction::EAST, .tiles = 2, .kind = ScoredLegKind::TO_WALL, .run = true}}), + RouteVerdict::PASS, "an open hold that overshoots only toward a wall, then the wall"), + }); +} + +UnitTestResult test_wall_leg_through_a_warp(){ + const ToyMap toy({"..D..#"}); + const RouteScore got = score(toy, {{0, 0}}, {4, 0}, {{.direction = Direction::EAST, .tiles = 4, .kind = ScoredLegKind::TO_WALL}}); + return all_of({ + expect(got, RouteVerdict::FAIL, "a hold that walks into a warp"), + expect(score(toy, {{0, 0}}, {2, 0}, {{.direction = Direction::EAST, .tiles = 2, .kind = ScoredLegKind::TO_WALL}}), + RouteVerdict::PASS, "a hold that ends in the warp it is for"), + }); +} + +UnitTestResult test_trigger_stops_a_run(){ + const ToyMap toy({"..T...."}); + return all_of({expect(score(toy, {{0, 0}}, {2, 0}, {{.direction = Direction::EAST, .tiles = 2, .kind = ScoredLegKind::TO_WALL, .run = true}}), + RouteVerdict::PASS, "a run that the goal's trigger stops")}); +} + +UnitTestResult test_grass_charges_interruptions(){ + const ToyMap toy({".\"\"\"..#"}); + const RouteScore got = score(toy, {{0, 0}}, {5, 0}, {{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TO_WALL}}); + if (got.verdict != RouteVerdict::PASS || got.recoveries != 3 || got.replans != 0){ + return std::format("{}: {} recoveries, {} replans ({})", verdict_name(got.verdict), got.recoveries, got.replans, got.why); + } + if (got.expected_ms <= (double)got.nominal_ms || got.worst_ms <= got.nominal_ms){ + return std::format("expected {} ms, worst {} ms, nominal {} ms", got.expected_ms, got.worst_ms, got.nominal_ms); + } + return true; +} + +UnitTestResult test_taps_in_grass_need_a_replan(){ + // A lost tap in the grass leaves us a tile either way; the taps after it + // cannot tell, so without a replanner the plan fails. + const ToyMap toy({".\"\"\"...."}); + const std::vector taps{{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}; + const RouteScore failed = score(toy, {{0, 0}}, {5, 0}, taps); + // A replanner that goes east to the wall absorbs it. + const ToyMap walled({".\"\"\"..#"}); + const RouteReplanner to_wall = [](const std::vector&){ + return std::optional>({{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TO_WALL}}); + }; + const RouteScore replanned = score(walled, {{0, 0}}, {5, 0}, taps, to_wall); + if (replanned.replans != 3){ + return std::format("{} replans", replanned.replans); + } + return all_of({ + expect(failed, RouteVerdict::FAIL, "taps in grass without a replanner"), + expect(replanned, RouteVerdict::PASS, "taps in grass with a wall to replan to"), + }); +} + +UnitTestResult test_recovery_back_through_the_grass_strands(){ + // The recovery walks back to the west wall, still in the grass, and + // taps east through it: an interruption there leads to the same + // recovery again, from tiles never known. + const ToyMap toy({"#\"\"\"\"...."}); + const std::vector taps{{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}; + const RouteReplanner back = [](const std::vector&){ + return std::optional>({{.direction = Direction::WEST, .tiles = 4, .kind = ScoredLegKind::TO_WALL}, + {.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}); + }; + return all_of({expect(score(toy, {{1, 0}}, {6, 0}, taps, back), RouteVerdict::STRAND, "a recovery back through the grass")}); +} + +UnitTestResult test_recovery_from_a_wall_out_of_the_grass_retries(){ + // The same, but the west wall stops us on a tile out of the grass: the + // recovery starts from a known tile each time, so an interruption on + // the way back is a retry that ends, not a strand (00.04b + // to_catch_grass, whose goal is in the grass). + const ToyMap toy({"#.\"\"\"...."}); + const std::vector taps{{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}; + const RouteReplanner back = [](const std::vector&){ + return std::optional>({{.direction = Direction::WEST, .tiles = 4, .kind = ScoredLegKind::TO_WALL}, + {.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}); + }; + return all_of({expect(score(toy, {{1, 0}}, {6, 0}, taps, back), RouteVerdict::PASS, "a recovery from a wall out of the grass")}); +} + +UnitTestResult test_too_many_recoveries(){ + const ToyMap toy({".\"\"\"..#"}); + const RouteReplanner to_wall = [](const std::vector&){ + return std::optional>({{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TO_WALL}}); + }; + InterruptModel model = toy_model(); + model.max_recoveries = 0; + return all_of({expect(score(toy, {{0, 0}}, {5, 0}, {{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TAPS}}, to_wall, model), + RouteVerdict::RETRIES, "a replan with no recoveries allowed")}); +} + +UnitTestResult test_trainer_sight_once(){ + const ToyMap toy({".ss...#"}); + const RouteScore got = score(toy, {{0, 0}}, {5, 0}, {{.direction = Direction::EAST, .tiles = 5, .kind = ScoredLegKind::TO_WALL}}); + if (got.recoveries != 1 || got.expected_ms < (double)(got.nominal_ms + 45000)){ + return std::format("{} recoveries, expected {} ms", got.recoveries, got.expected_ms); + } + return true; +} + + +struct RouteScorerInput{ + std::string name; + UnitTestResult (*test)(); +}; + +struct RouteScorerExpectation{ + std::string_view description; +}; + +struct RouteScorerCase{ + RouteScorerInput input; + RouteScorerExpectation expectation; +}; + +class Test_RouteScorer : public UnitTest{ +public: + explicit Test_RouteScorer(RouteScorerCase scenario) + : UnitTest("Pokemon::Navigation - RouteScorer: " + scenario.input.name) + , m_case(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_case.input.test(); + } + +private: + RouteScorerCase m_case; +}; + +const RouteScorerCase ROUTE_SCORER_CASES[] = { + { + .input = {.name = "taps take a tap each", .test = test_taps_time}, + .expectation = {.description = "4 taps cost 4 taps and a press"}, + }, + { + .input = {.name = "a run to a wall beats taps", .test = test_run_to_wall_beats_taps}, + .expectation = {.description = "run to the wall is faster than the same tiles in taps"}, + }, + { + .input = {.name = "walls bring a set of tiles to one", .test = test_wall_collapses_a_set}, + .expectation = {.description = "PASS"}, + }, + { + .input = {.name = "an open hold with nothing to stop it fails", .test = test_open_hold_off_the_goal}, + .expectation = {.description = "FAIL: may end off the goal"}, + }, + { + .input = {.name = "an open hold may not overshoot into grass", .test = test_open_hold_into_grass}, + .expectation = {.description = "FAIL: overshoot onto grass"}, + }, + { + .input = {.name = "an open hold may not overshoot onto a ledge", .test = test_open_hold_onto_a_ledge}, + .expectation = {.description = "FAIL: overshoot over a ledge"}, + }, + { + .input = {.name = "an open hold may overshoot toward a wall", .test = test_open_hold_before_a_wall}, + .expectation = {.description = "FAIL when short of the goal, PASS with the wall after it"}, + }, + { + .input = {.name = "a hold may not walk into a warp", .test = test_wall_leg_through_a_warp}, + .expectation = {.description = "FAIL through a warp, PASS into the goal warp"}, + }, + { + .input = {.name = "the goal's trigger stops a run", .test = test_trigger_stops_a_run}, + .expectation = {.description = "PASS"}, + }, + { + .input = {.name = "grass charges interruptions", .test = test_grass_charges_interruptions}, + .expectation = {.description = "3 recoveries, expected and worst above nominal"}, + }, + { + .input = {.name = "taps in grass need a replan", .test = test_taps_in_grass_need_a_replan}, + .expectation = {.description = "FAIL without a replanner, PASS with 3 replans"}, + }, + { + .input = {.name = "a recovery back through the grass strands", .test = test_recovery_back_through_the_grass_strands}, + .expectation = {.description = "STRAND"}, + }, + { + .input = {.name = "a recovery from a wall out of the grass retries", .test = test_recovery_from_a_wall_out_of_the_grass_retries}, + .expectation = {.description = "PASS"}, + }, + { + .input = {.name = "recoveries in a row are capped", .test = test_too_many_recoveries}, + .expectation = {.description = "RETRIES"}, + }, + { + .input = {.name = "a trainer sees us once", .test = test_trainer_sight_once}, + .expectation = {.description = "one trainer battle charged"}, + }, +}; + +} // namespace + + +void add_tests_RouteScorer(UnitTestDatabase& database){ + for (const auto& scenario : ROUTE_SCORER_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.h new file mode 100644 index 0000000000..db3576e784 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteScorer_Tests.h @@ -0,0 +1,23 @@ +/* Route Scorer Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_RouteScorer_Tests_H +#define PokemonAutomation_Pokemon_RouteScorer_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers route scorer unit tests. +void add_tests_RouteScorer(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index c5e1c86862..6432ab7c74 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -9,6 +9,8 @@ #include "Inference/PokemonBDSP_MenuDetector.h" #include "Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.h" +#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.h" +#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.h" @@ -16,10 +18,15 @@ #include "Programs/AutoStory/PokemonBDSP_AutoStory_Segment00_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryWorld_Tests.h" +#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.h" +#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h" #include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.h" -#include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.h" +#include "Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h" +#include "Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy_Tests.h" +#include "Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h" #include "PokemonBDSP_Tests.h" namespace PokemonAutomation{ @@ -35,15 +42,22 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_Maps(database); add_tests_AutoStory_StoryWorld(database); add_tests_AutoStory_RoutePlanner(database); + add_tests_AutoStory_RouteBench(database); add_tests_AutoStory_StoryMaps(database); add_tests_AutoStory_Segment00(database); add_tests_AutoStory_StorySimulation(database); - add_tests_AutoStory_StoryTable(database); add_tests_AutoStory_StoryData(database); + add_tests_AutoStory_StoryTable(database); add_tests_AutoStory_Walk(database); + add_tests_AutoStory_WildBattlePolicy(database); add_tests_AutoStory_PlannedRoute(database); add_tests_AutoStory_GridSim(database); + add_tests_AutoStory_WallBattleSim(database); add_tests_AutoStory_RecoveryWalk(database); + add_tests_AutoStory_StorySim(database); + add_tests_AutoStory_SimFailureCases(database); + add_tests_AutoStory_FaultSweep(database); + add_tests_AutoStory_StoryActions(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.cpp index 4163e95907..446a771ed8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions_Tests.cpp @@ -21,7 +21,10 @@ #include "CommonFramework/ImageTypes/ImageRGB32.h" #include "CommonFramework/Logging/Logger.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryMaps.h" +#include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_BattleMenuReader.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_StoryLanguage.h" +#include "PokemonBDSP_AutoStory_BattleMoves.h" #include "PokemonBDSP_AutoStory_Center.h" #include "PokemonBDSP_AutoStory_IntroProbe.h" #include "PokemonBDSP_AutoStory_IntroSteps.h" @@ -434,6 +437,80 @@ UnitTestResult test_school_lamp(Logger& logger){ } +// The move picked from names and PP as read. lab-B 2026-11-09, French: +// no name read, Piplup's Pound at 35 PP and Growl at 22 PP, and the old +// "newest move that is not a status move" fallback used Growl until the +// training gave up after 25 turns. +UnitTestResult test_choose_move(Logger&){ + struct Case{ std::string_view name; std::vector slots; size_t best; }; + const Case cases[] = { + {"no name read, PP 35 and 22", {{"", 35}, {"", 22}}, 1}, + {"no name read, PP 35 and 30", {{"", 35}, {"", 30}}, 1}, + {"no name or PP read", {{"", -1}, {"", -1}}, 1}, + {"Scratch and Leer", {{"scratch", 35}, {"leer", 30}}, 1}, + {"Pound, Growl, Water Gun and Charm", {{"pound", 35}, {"growl", 40}, {"water-gun", 10}, {"charm", 20}}, 3}, + {"Water Gun out of PP", {{"pound", 35}, {"growl", 40}, {"water-gun", 0}, {"charm", 20}}, 1}, + {"slot 1 unread at 38 PP: a status move", {{"", 38}, {"", 40}, {"", 20}}, 3}, + {"Growl unread, Tackle read", {{"", 40}, {"tackle", 35}}, 2}, + }; + for (const Case& c : cases){ + const size_t best = choose_move(c.slots); + if (best != c.best){ + return std::string(c.name) + ": picked move " + std::to_string(best) + ", expected " + std::to_string(c.best) + "."; + } + } + return true; +} + +// Move menus saved on lab-B (SCREENSHOTS_PATH()/AutoStory/moves/), read in +// the game's language. The French ones read nothing before the names came +// from the move name dictionary. +UnitTestResult test_move_menu_screenshots(Logger& logger){ + struct Case{ + std::string file; + Language language; + std::vector slots; + size_t best; + }; + const Case cases[] = { + {"PokemonBDSP/AutoStory/MoveMenuFrenchPoundGrowl-20261109-192734.png", Language::French, + {{"pound", 35}, {"growl", 40}}, 1}, + {"PokemonBDSP/AutoStory/MoveMenuFrenchPoundGrowl16-20261109-193035.png", Language::French, + {{"pound", 35}, {"growl", 16}}, 1}, + {"PokemonBDSP/AutoStory/MoveMenuEnglishPiplup-20261108-181435.png", Language::English, + {{"pound", 35}, {"growl", 40}, {"water-gun", 10}, {"charm", 20}}, 3}, + }; + const Language story = story_language(); + for (const Case& c : cases){ + const std::string path = UNIT_TEST_RESOURCE_PATH() + c.file; + if (!Filesystem::is_regular_file(path)){ + return UnitTestResult(UnitTestResult::SKIPPED, "Screenshot not found: " + path); + } + const ImageRGB32 screen(path); + set_story_language(c.language); + const std::vector slots = read_move_menu(screen, detect_battle_move_menu(screen)); + set_story_language(story); + std::string read; + for (size_t i = 0; i < slots.size(); i++){ + read += " [" + slots[i].describe(i) + "]"; + } + logger.log(std::string(c.file) + ":" + read); + if (slots.size() != c.slots.size()){ + return std::string(c.file) + ": " + std::to_string(slots.size()) + " moves, expected " + std::to_string(c.slots.size()) + "."; + } + for (size_t i = 0; i < slots.size(); i++){ + if (slots[i].slug != c.slots[i].slug || slots[i].pp != c.slots[i].pp){ + return std::string(c.file) + ": move " + std::to_string(i + 1) + " read as" + read + "."; + } + } + if (choose_move(slots) != c.best){ + return std::string(c.file) + ": picked move " + std::to_string(choose_move(slots)) + ", expected " + std::to_string(c.best) + "."; + } + } + return true; +} + + struct AutoStoryActionsInput{ std::string name; std::function body; @@ -509,6 +586,14 @@ const AutoStoryActionsCase AUTO_STORY_ACTIONS_CASES[] = { .input = {"Jubilife School lamp", test_school_lamp}, .expectation = {}, }, + { + .input = {"battle moves: the pick from names and PP", test_choose_move}, + .expectation = {}, + }, + { + .input = {"battle moves: move menu screenshots in each language", test_move_menu_screenshots}, + .expectation = {}, + }, }; void add_tests_AutoStory_Actions(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.cpp index 568247aba4..e177f711a6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.cpp @@ -19,7 +19,6 @@ #include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" #include "CommonTools/Async/InferenceRoutines.h" #include "CommonTools/OCR/OCR_RawTesseractOCR.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" #include "PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h" @@ -30,6 +29,7 @@ #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP_AutoStory_Bag.h" #include "PokemonBDSP_AutoStory_BattleMoves.h" +#include "PokemonBDSP_AutoStory_TalkOver.h" #include "PokemonBDSP_AutoStory_Battle.h" namespace PokemonAutomation{ @@ -378,37 +378,7 @@ void fight_with_best_move(VideoStream& stream, ProControllerContext& context, co void confirm_battle_overworld(VideoStream& stream, ProControllerContext& context, const std::string& label){ - OverworldDetector overworld; - ShortDialogDetector dialogue(COLOR_YELLOW); - BlackScreenDetector black; - VideoOverlaySet overlays(stream.overlay()); - overworld.make_overlays(overlays); - dialogue.make_overlays(overlays); - black.make_overlays(overlays); - const auto deadline = std::chrono::steady_clock::now() + 180s; - auto quiet_since = std::chrono::steady_clock::now(); - bool finished = false; - while (std::chrono::steady_clock::now() < deadline){ - const auto frame = stream.video().snapshot(); - if (!frame){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": No video frame.", stream); - } - const auto now = std::chrono::steady_clock::now(); - if (dialogue.detect(frame) || black.detect(frame) || !overworld.detect(frame)){ - quiet_since = now; - }else if (now - quiet_since >= 4s){ - finished = true; - break; - } - pbf_mash_button(context, BUTTON_B, 100ms); - context.wait_for_all_requests(); - } - if (!finished){ - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - label + ": Dialogue-free overworld not confirmed for four seconds.", stream); - } - context.wait_for_all_requests(); + talk_over(stream, context, label); } void fight_story_battle(VideoStream& stream, ProControllerContext& context, const std::string& label, BattleFormat format){ @@ -417,12 +387,12 @@ void fight_story_battle(VideoStream& stream, ProControllerContext& context, cons } void fight_trainer(VideoStream& stream, ProControllerContext& context, const std::string& label){ - // The best move on the menu each turn, whatever the starter. - fight_with_best_move(stream, context, {.battle_type = BattleType::TRAINER, .format = BattleFormat::SINGLES, .switch_on_faint = false}, label); + // The best move on the menu each turn, whatever the starter; the next Pokemon after a faint. + fight_with_best_move(stream, context, {.battle_type = BattleType::TRAINER, .format = BattleFormat::SINGLES, .switch_on_faint = true}, label); } void fight_wild_battle(VideoStream& stream, ProControllerContext& context, const std::string& label){ - fight_with_best_move(stream, context, {.battle_type = BattleType::STANDARD, .format = BattleFormat::SINGLES, .switch_on_faint = false}, label); + fight_with_best_move(stream, context, {.battle_type = BattleType::STANDARD, .format = BattleFormat::SINGLES, .switch_on_faint = true}, label); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.h index 13dfe78cf5..371ab3877e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Battle.h @@ -35,8 +35,10 @@ enum class BattleFormat{ DOUBLES, }; -// Mashes B until the overworld has shown with no dialogue for four seconds. -// Fails with a screenshot after three minutes. +// The speeches after a battle, to their end: talk_over(), B through the +// lines until the overworld is quiet. Roark's badge lines pause for the +// fanfare, and someone may walk off before the next line, so a moment +// with no box is not the end. Fails with a screenshot after two minutes. void confirm_battle_overworld(VideoStream& stream, ProControllerContext& context, const std::string& label); // A story battle that may go badly: the best move each turn, Potions diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_BattleMoves.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_BattleMoves.cpp index 6044540aa9..cae25a7d4d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_BattleMoves.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_BattleMoves.cpp @@ -10,13 +10,17 @@ #include #include #include +#include #include #include "Common/Cpp/Filesystem/Filesystem.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Cpp/Json/JsonValue.h" #include "Common/Cpp/PrettyPrint.h" #include "CommonFramework/GlobalAutoPaths.h" #include "CommonFramework/ImageTools/ImageBoxes.h" #include "CommonFramework/ImageTypes/ImageRGB32.h" #include "CommonTools/OCR/OCR_RawTesseractOCR.h" +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_StoryLanguage.h" #include "PokemonBDSP_AutoStory_BattleMoves.h" @@ -28,25 +32,106 @@ namespace PokemonBDSP{ namespace{ -// Early moves the starters and their foes have, as type, power and -// most PP. A status move has power 0. +// How close a read must come to a move's name, as the other move readers. +constexpr double MOVE_NAME_MAX_LOG10P = -1.30; +constexpr double MOVE_NAME_LOG10P_SPREAD = 0.50; + +// Early moves the starters and their foes have, by the slug of the move +// name dictionary, as type, power and most PP. A status move has power 0. struct KnownMove{ - std::string name; + std::string slug; std::string type; int power; int pp; }; const KnownMove KNOWN_MOVES[] = { {"pound", "normal", 40, 35}, {"tackle", "normal", 40, 35}, {"scratch", "normal", 40, 35}, - {"quickattack", "normal", 40, 30}, {"headbutt", "normal", 70, 15}, - {"watergun", "water", 40, 25}, {"bubble", "water", 40, 30}, {"bubblebeam", "water", 65, 20}, - {"ember", "fire", 40, 25}, {"flamewheel", "fire", 60, 25}, {"machpunch", "fighting", 40, 30}, - {"absorb", "grass", 20, 25}, {"razorleaf", "grass", 55, 25}, {"bite", "dark", 60, 25}, - {"peck", "flying", 35, 35}, {"wingattack", "flying", 60, 35}, {"metalclaw", "steel", 50, 35}, - {"growl", "normal", 0, 40}, {"leer", "normal", 0, 30}, {"tailwhip", "normal", 0, 30}, - {"withdraw", "water", 0, 40}, {"taunt", "dark", 0, 20}, + {"quick-attack", "normal", 40, 30}, {"headbutt", "normal", 70, 15}, + {"water-gun", "water", 40, 25}, {"bubble", "water", 40, 30}, {"bubble-beam", "water", 65, 20}, + {"ember", "fire", 40, 25}, {"flame-wheel", "fire", 60, 25}, {"mach-punch", "fighting", 40, 30}, + {"absorb", "grass", 20, 25}, {"razor-leaf", "grass", 55, 25}, {"bite", "dark", 60, 25}, + {"peck", "flying", 35, 35}, {"pluck", "flying", 60, 20}, {"wing-attack", "flying", 60, 35}, + {"metal-claw", "steel", 50, 35}, + {"growl", "normal", 0, 40}, {"leer", "normal", 0, 30}, {"tail-whip", "normal", 0, 30}, + {"withdraw", "water", 0, 40}, {"taunt", "dark", 0, 20}, {"charm", "fairy", 0, 20}, + {"curse", "ghost", 0, 10}, +}; + +const KnownMove* known_move(std::string_view slug){ + for (const KnownMove& move : KNOWN_MOVES){ + if (slug == move.slug){ + return &move; + } + } + return nullptr; +} + +// What each starter has in each slot as BDSP teaches it, learnt in this +// order up to level 13: slot 1 is a Normal attack, slot 2 a status move, +// slot 3 the starter's own-type attack, slot 4 either. +const std::vector> STARTER_SLOTS = { + {"tackle", "scratch", "pound"}, + {"withdraw", "leer", "growl"}, + {"absorb", "ember", "water-gun"}, + {"razor-leaf", "taunt", "charm"}, }; +// A slot whose name was not read, from its PP, which rules out any move +// with less most PP, among what the starters have in that slot (any known +// move if none of those is left): a known move when every move left is an +// attack (the weakest) or every one a status move. +const KnownMove* guess_unread_move(size_t slot, int pp){ + std::vector left; + if (slot < STARTER_SLOTS.size()){ + for (std::string_view slug : STARTER_SLOTS[slot]){ + left.push_back(known_move(slug)); + } + } + auto pp_rules_out = [&](const KnownMove* move){ return pp > move->pp; }; + std::erase_if(left, pp_rules_out); + if (left.empty()){ + for (const KnownMove& move : KNOWN_MOVES){ + left.push_back(&move); + } + std::erase_if(left, pp_rules_out); + } + if (left.empty()){ + return nullptr; + } + const KnownMove* weakest = left[0]; + for (const KnownMove* move : left){ + if ((move->power > 0) != (weakest->power > 0)){ + return nullptr; + } + if (move->power < weakest->power){ + weakest = move; + } + } + return weakest; +} + +// Every language's names of the known moves, from the move name dictionary. +JsonObject known_move_names(){ + const JsonValue all = load_json_file(RESOURCE_PATH() + "PokemonSV/PokemonMovesOCR.json"); + JsonObject known; + for (const auto& [language, names] : all.to_object_throw()){ + JsonObject names_known; + for (const KnownMove& move : KNOWN_MOVES){ + const JsonValue* name = names.to_object_throw().get_value(move.slug); + if (name){ + names_known[move.slug] = name->clone(); + } + } + known[language] = std::move(names_known); + } + return known; +} + +const OCR::SmallDictionaryMatcher& move_name_matcher(){ + static const OCR::SmallDictionaryMatcher matcher(known_move_names()); + return matcher; +} + // The box's text, whatever differs from its median colour by more than // 120, as black on white with an 8-pixel margin. ImageRGB32 pp_text_image(const ImageViewRGB32& box){ @@ -165,11 +250,11 @@ std::pair tallest_text_band(const GrayBox& box){ return {band_top, band_bottom}; } -// The name is dark text on a light button (grey, or light blue under the -// cursor). Take the box right of the type icon and left of the PP, tall -// enough for a status move's name, which sits lower: it has no "Effective" -// line under it. Read as lower-case letters; nothing where there is no -// reader for the game's language (an unread move counts as a plain attack). +// The name is dark text on a light button (grey, or light blue under the +// cursor). Take the box right of the type icon and left of the PP, tall +// enough for a status move's name, which sits lower: it has no "Effective" +// line under it. Returns the slug of the known move it reads as, in the +// story's language; "" if none. std::string read_move_name(const ImageViewRGB32& screen, const ImageFloatBox& button){ const ImageFloatBox name_box{button.x + button.width * 0.17, button.y + button.height * 0.08, button.width * 0.53, button.height * 0.80}; @@ -188,90 +273,93 @@ std::string read_move_name(const ImageViewRGB32& screen, const ImageFloatBox& bu } } } - std::string name; - for (unsigned char ch : story_reads_text() ? OCR::tesseract_ocr_read(story_language(), text) : std::string()){ - if (std::isalpha(ch)){ - name.push_back((char)std::tolower(ch)); - } - } - return name; -} - -// The longest known move whose name appears in `name`: "bubblebeam" over "bubble". -const KnownMove* known_move(const std::string& name){ - const KnownMove* known = nullptr; - for (const KnownMove& move : KNOWN_MOVES){ - if (name.find(move.name) != std::string::npos && - (!known || std::string(move.name).size() > std::string(known->name).size())){ - known = &move; - } + const OCR::StringMatchResult read = move_name_matcher().match_substring_from_image( + nullptr, story_language(), text, MOVE_NAME_MAX_LOG10P, MOVE_NAME_LOG10P_SPREAD); + if (read.results.size() != 1){ + return ""; } - return known; + return read.results.begin()->second.token; } -// The move in slot `i`: its read name, and what it is if known. A slot -// read well once keeps its name when a later read fails. -std::pair identify_move(const ImageViewRGB32& screen, const ImageFloatBox& button, size_t i){ +// `slug` read in slot `i`, or what the slot read last time if this read +// failed. +std::string remember_move(std::string slug, size_t i){ static std::array last_read; - std::string name = read_move_name(screen, button); - const KnownMove* known = known_move(name); - if (!known){ - name = last_read[i]; - known = known_move(name); + if (slug.empty()){ + return last_read[i]; } - if (known){ - last_read[i] = known->name; - } - return {name, known}; + last_read[i] = slug; + return slug; } } // namespace -size_t pick_best_move(VideoStream& stream, const ImageViewRGB32& screen, - const BattleMoveMenuState& moves, const std::string& label){ - // Keep the menu as it looked, to check the reads against. - const std::string folder = SCREENSHOTS_PATH() + "AutoStory/moves/"; - Filesystem::create_directories(Filesystem::Path(folder)); - screen.save(folder + now_to_filestring() + "-" + label + ".png"); - size_t best = 1; +std::string MoveSlot::describe(size_t slot) const{ + const KnownMove* known = known_move(slug); + const KnownMove* guess = known ? nullptr : guess_unread_move(slot, pp); + const std::string what = known + ? std::string(known->slug) + " (" + known->type + ", " + std::to_string(known->power) + ")" + : guess + ? std::string("unread, ") + (guess->power > 0 ? "an attack" : "a status move") + " by slot and PP" + : "unread"; + return what + ", PP left " + (pp < 0 ? std::string("unread") : std::to_string(pp)); +} + +size_t choose_move(const std::vector& slots){ + size_t best = 0; int best_score = -1; - bool any_attack = false; - size_t last_not_status = 1; - for (size_t i = 0; i < moves.move_count; i++){ - const auto [name, known] = identify_move(screen, moves.buttons[i], i); + for (size_t i = 0; i < slots.size(); i++){ // A move with no PP left cannot be chosen; the game says so and // keeps the menu up. - const int pp = read_move_pp(screen, moves.buttons[i], known ? known->pp : 0); - stream.log("[" + label + "] Move " + std::to_string(i + 1) + " PP left: " + (pp < 0 ? std::string("unread") : std::to_string(pp)) + "."); - if (pp == 0){ + if (slots[i].pp == 0){ continue; } - // An unreadable move counts as a plain attack, ahead of known - // status moves. - const int score = known ? known->power * 2 + (std::string(known->type) != "normal" ? 1 : 0) : 40 * 2 - 1; - stream.log("[" + label + "] Move " + std::to_string(i + 1) + " reads \"" + name + "\"" + - (known ? std::string(" = ") + known->name + " (" + known->type + ", " + std::to_string(known->power) + ")" : " (unknown)") + "."); + const KnownMove* known = known_move(slots[i].slug); + if (!known){ + known = guess_unread_move(i, slots[i].pp); + } + // A move that might be either counts below any attack known for + // sure, and an earlier one first: slot 1 is an attack for every + // starter. + const int score = known ? known->power * 2 + (std::string_view(known->type) != "normal" ? 1 : 0) : 1; if (score > best_score){ best_score = score; - best = i + 1; - } - any_attack = any_attack || (known && known->power > 0); - if (!known || known->power > 0){ - last_not_status = i + 1; + best = i; } } - // No attack read: the newest move is the starter's own-type attack - // (Water Gun, Ember, Absorb), unless it is a status move. - if (!any_attack){ - best = last_not_status; + return best + 1; +} + +std::vector read_move_menu(const ImageViewRGB32& screen, const BattleMoveMenuState& moves){ + std::vector slots; + for (size_t i = 0; i < moves.move_count; i++){ + MoveSlot slot; + slot.slug = read_move_name(screen, moves.buttons[i]); + const KnownMove* known = known_move(slot.slug); + slot.pp = read_move_pp(screen, moves.buttons[i], known ? known->pp : 0); + slots.push_back(std::move(slot)); + } + return slots; +} + +size_t pick_best_move(VideoStream& stream, const ImageViewRGB32& screen, + const BattleMoveMenuState& moves, const std::string& label){ + // Keep the menu as it looked, to check the reads against. + const std::string folder = SCREENSHOTS_PATH() + "AutoStory/moves/"; + Filesystem::create_directories(Filesystem::Path(folder)); + screen.save(folder + now_to_filestring() + "-" + label + ".png"); + std::vector slots = read_move_menu(screen, moves); + for (size_t i = 0; i < slots.size(); i++){ + slots[i].slug = remember_move(std::move(slots[i].slug), i); + stream.log("[" + label + "] Move " + std::to_string(i + 1) + ": " + slots[i].describe(i) + "."); } + const size_t best = choose_move(slots); stream.log("[" + label + "] Best move: " + std::to_string(best) + "."); return best; } - } // namespace PokemonBDSP } // namespace NintendoSwitch } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_BattleMoves.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_BattleMoves.h index 2f9b1fa674..9dfc62fbbb 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_BattleMoves.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_BattleMoves.h @@ -4,8 +4,9 @@ * * Adapted from PokemonAutomation/Arduino-Source#1717 by Developer-Butters. * - * Which move to use: the move menu's names and PP read with OCR, scored by - * the power of the early moves the starters and their foes have. + * Which move to use: the move menu's names, read in the game's language, + * and PP, scored by the power of the early moves the starters and their + * foes have. * */ @@ -13,6 +14,7 @@ #define PokemonAutomation_PokemonBDSP_AutoStory_BattleMoves_H #include +#include #include "CommonFramework/ImageTypes/ImageViewRGB32.h" #include "CommonFramework/Tools/VideoStream.h" #include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_BattleMenuReader.h" @@ -22,11 +24,31 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ -// The best move on the move menu `moves` of `screen`, 1-based: the most -// powerful one we know, and on a tie one that is not Normal (an early -// starter's own type). A move with no PP left is passed over; with no -// attack read, the newest move that is not a status move. Keeps a -// screenshot of the menu, labelled `label`. +// One move on the move menu as read: the slug of the move name dictionary +// ("" when the name was not read) and the PP left (-1 when not read). +struct MoveSlot{ + std::string slug; + int pp = -1; + + // What the move in 0-based slot `slot` is taken for, for the log. + std::string describe(size_t slot) const; +}; + +// The best of `slots`, 1-based: the most powerful one we know, and on a +// tie one that is not Normal (an early starter's own type). A move with +// no PP left is passed over. A move whose name was not read is told by +// what the starters have in its slot and the PP it has left, which rules +// out moves with less most PP; one that might still be either comes after +// every attack, earliest first. +size_t choose_move(const std::vector& slots); + +// The names, in the story's language, and PP of the moves on the move +// menu `moves` of `screen`. +std::vector read_move_menu(const ImageViewRGB32& screen, const BattleMoveMenuState& moves); + +// The best move on the move menu `moves` of `screen`, 1-based, as +// choose_move() picks from the names read in the game's language and the +// PP left. Keeps a screenshot of the menu, labelled `label`. size_t pick_best_move(VideoStream& stream, const ImageViewRGB32& screen, const BattleMoveMenuState& moves, const std::string& label); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Center.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Center.cpp index e7a87ce60a..ac2dac27a9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Center.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Center.cpp @@ -23,6 +23,7 @@ #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkScreen.h" #include "PokemonBDSP_AutoStory_WildBattle.h" #include "PokemonBDSP_AutoStory_Center.h" +#include "PokemonBDSP_AutoStory_TalkOver.h" #include "PokemonBDSP_AutoStory_LitDoorway.h" namespace PokemonAutomation{ @@ -462,7 +463,15 @@ void talk_to_nurse( ){ // The nurse's counter is straight ahead of the door. route_status(stream, label + ": talking to the nurse."); - if (walk_to_talk(stream, context, run_from_wild_battle, {0, 1}, 6000ms, label + ": to the nurse").stop != WalkStop::DIALOG){ + WalkResult walk = walk_to_talk(stream, context, run_from_wild_battle, {0, 1}, 6000ms, label + ": to the nurse"); + // A "transition" before the first step is the inside still fading in, + // not a door (lab-B 2026-11-10, 00.04b): settle, then walk once more. + if (walk.stop == WalkStop::TRANSITION && walk.moved_chunks == 0){ + stream.log("[Route] " + label + ": to the nurse: a fade before the first step; settling, then once more."); + talk_over(stream, context, label + ": inside the Center"); + walk = walk_to_talk(stream, context, run_from_wild_battle, {0, 1}, 6000ms, label + ": to the nurse"); + } + if (walk.stop != WalkStop::DIALOG){ OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, label + ": nurse not reached.", stream); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.cpp new file mode 100644 index 0000000000..4c371b495b --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.cpp @@ -0,0 +1,61 @@ +/* BDSP AutoStory - Talk-over + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.h" +#include "PokemonBDSP_AutoStory_WildBattle.h" +#include "PokemonBDSP_AutoStory_TalkOver.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +TalkOverEnd talk_over(VideoStream& stream, ProControllerContext& context, const std::string& label, const TalkOverSpec& spec){ + const WallClock deadline = current_time() + TALK_OVER_LIMIT; + TalkOver judge(spec.rule); + BdspScreenObserver eyes(spec.watch == TalkOverWatch::TRAINER ? BattleCue::TRAINER : BattleCue::WILD_MENU, spec.banner); + while (current_time() < deadline){ + context.wait_for_all_requests(); + const WallClock now = current_time(); + switch (judge.look(eyes.observe(stream.video().snapshot(), now), now)){ + case SceneMove::DONE: + stream.log(std::format("[Talk-over] {}: over; {}.", label, judge.describe())); + return TalkOverEnd::QUIET; + case SceneMove::BATTLE: + if (spec.watch == TalkOverWatch::TRAINER){ + stream.log("[Talk-over] " + label + ": a battle started."); + return TalkOverEnd::BATTLE; + } + stream.log("[Talk-over] " + label + ": in a wild battle; fleeing."); + run_from_wild_battle(stream, context); + continue; + case SceneMove::NEXT: + pbf_press_button(context, spec.next, TALK_OVER_HOLD, TALK_OVER_RELEASE); + continue; + case SceneMove::B: + pbf_press_button(context, BUTTON_B, TALK_OVER_HOLD, TALK_OVER_RELEASE); + continue; + } + } + const long long seconds = std::chrono::duration_cast(TALK_OVER_LIMIT).count(); + OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, + !judge.warped() + ? std::format("{}: no fade or banner within {} s, so we are not where the step goes (map mismatch).", label, seconds) + : !spec.rule.end_on_quiet + ? std::format("{}: no battle within {} s of the talk.", label, seconds) + : std::format("{}: not back on a quiet overworld within {} s.", label, seconds), + stream); +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h new file mode 100644 index 0000000000..b4e5c6debe --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h @@ -0,0 +1,81 @@ +/* BDSP AutoStory - Talk-over + * + * From: https://github.com/PokemonAutomation/ + * + * When a talk or a scene is over, judged from what the screen shows over + * time (#268's design note, slice 4): one rule for scenes, the speeches + * after a battle and a trainer's lines before one. It replaces the loops + * each of those had (settle(), settle_after_battle(), talk_or_fight()'s, + * confirm_battle_overworld()'s), which differed in how long the quiet had + * to last and whether the screen had to be still. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_TalkOver_H +#define PokemonAutomation_PokemonBDSP_AutoStory_TalkOver_H + +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "Pokemon/AutoStory/Pokemon_SceneJudges.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// The judgement is shared (Pokemon_SceneJudges.h): it reads the screen +// events BdspScreenObserver reports. +// What to do after a look. +using Pokemon::SceneMove; +// What ends a talk-over, besides the quiet. +using Pokemon::TalkOverRule; +// When a talk or a scene is over, from looks alone. +using Pokemon::TalkOver; + +// One press is held this long, +constexpr Milliseconds TALK_OVER_HOLD = Milliseconds(80); +// then released this long before the next look. +constexpr Milliseconds TALK_OVER_RELEASE = Milliseconds(1200); +// How long a talk-over may take before the step fails. +constexpr Milliseconds TALK_OVER_LIMIT = Milliseconds(120000); + + +// What counts as a battle starting during a talk-over. +enum class TalkOverWatch{ + // A wild battle's menu; it is fled and the talk-over goes on. A black + // screen is a fade (a scene that changes map). + SCENE, + // A trainer's battle: its menu (Roark's read as STANDARD, r210d) or the + // black screen it opens with. The talk-over ends there. + TRAINER, +}; + +// How talk_over() presses and looks. +struct TalkOverSpec{ + // Pressed while a box shows: B, or A for lines that give an item. + Button next = BUTTON_B; + TalkOverRule rule = {}; + TalkOverWatch watch = TalkOverWatch::SCENE; + // The expected map's banner name for TalkOverRule::warp ("" for a fade only). + std::string banner = ""; +}; + +// How talk_over() ended. +enum class TalkOverEnd{ + QUIET, + BATTLE, // Only with TalkOverWatch::TRAINER. +}; + +// Presses through any text and scene on the console until TalkOver says it +// is over. Fails with a screenshot after TALK_OVER_LIMIT. +TalkOverEnd talk_over(VideoStream& stream, ProControllerContext& context, const std::string& label, const TalkOverSpec& spec = {}); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp index 90d8afaf94..84dda41bbf 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.cpp @@ -18,11 +18,9 @@ #include "CommonTools/Async/InferenceRoutines.h" #include "CommonTools/OCR/OCR_RawTesseractOCR.h" #include "CommonTools/OCR/OCR_Routines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" #include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" -#include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Indoors.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" @@ -32,6 +30,7 @@ #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkScreen.h" #include "PokemonBDSP_AutoStory_Bag.h" #include "PokemonBDSP_AutoStory_Battle.h" +#include "PokemonBDSP_AutoStory_TalkOver.h" #include "PokemonBDSP_AutoStory_WildBattle.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walks.h" #include "PokemonBDSP_AutoStory_Talks.h" @@ -57,50 +56,22 @@ bool dialogue_opens(VideoStream& stream, ProControllerContext& context, Millisec } bool talk_or_fight(VideoStream& stream, ProControllerContext& context, const std::string& label, TalkExpect expect, BattleFormat format){ - ShortDialogDetector dialog; - OverworldDetector overworld; - BattleMenuDetector battle_menu(BattleType::TRAINER); - // Roark's battle menu read as STANDARD, not TRAINER, and nothing fought - // it (r210d): either counts here, as only a trainer's battle can start. - BattleMenuDetector battle_menu_standard(BattleType::STANDARD); - BlackScreenDetector black; - auto quiet_since = std::chrono::steady_clock::now(); - for (size_t check = 0; check < 120; check++){ - context.wait_for_all_requests(); - const auto frame = stream.video().snapshot(); - if (!frame){ - fail_step(stream, label + ": No video frame."); - } - if (battle_menu.detect(*frame.frame) || battle_menu_standard.detect(*frame.frame) || black.detect(*frame.frame)){ - route_status(stream, "Fighting " + label + "."); - fight_story_battle(stream, context, label, format); - // Lines after the battle (Roark's badge, r211d) keep the menu - // from opening: finish them before the Potion. - if (dialogue_opens(stream, context, 3000ms)){ - finish_dialogue(stream, context, BUTTON_B, label + " after the battle"); - } - if (!in_pokemon_center(stream)){ - use_potion_first_pokemon(stream, context, 0.5); - } - return true; - } - const bool talking = dialog.detect(*frame.frame); - if (!talking && overworld.detect(*frame.frame)){ - if (expect != TalkExpect::BATTLE && std::chrono::steady_clock::now() - quiet_since >= 4s){ - route_status(stream, label + " only talked."); - return false; - } - pbf_wait(context, 300ms); - continue; - } - quiet_since = std::chrono::steady_clock::now(); - if (talking){ - pbf_press_button(context, BUTTON_B, 80ms, 1100ms); - }else{ - pbf_wait(context, 300ms); - } + const TalkOverEnd end = talk_over(stream, context, label, { + .rule = {.end_on_quiet = expect != TalkExpect::BATTLE}, + .watch = TalkOverWatch::TRAINER, + }); + if (end == TalkOverEnd::QUIET){ + route_status(stream, label + " only talked."); + return false; + } + route_status(stream, "Fighting " + label + "."); + // The battle ends with its speeches over (confirm_battle_overworld()): + // Roark's badge lines keep the Potion's menu from opening until then. + fight_story_battle(stream, context, label, format); + if (!in_pokemon_center(stream)){ + use_potion_first_pokemon(stream, context, 0.8); } - fail_step(stream, label + ": neither a battle nor the overworld after the dialogue."); + return true; } // A rough check that we stand in a Pokemon Center: its floor fills the lower @@ -193,7 +164,7 @@ void fight_route_trainer(VideoStream& stream, ProControllerContext& context, con context.wait_for_all_requests(); // The next trainer may be a few tiles on: check HP now. With no // Potion in the Bag this only looks. - use_potion_first_pokemon(stream, context, 0.5); + use_potion_first_pokemon(stream, context, 0.8); } bool sign_text_matches(const std::string& text, const std::string& key){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.h index ceceef7d0e..b8fae5f225 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Talks.h @@ -37,9 +37,9 @@ bool dialogue_opens(VideoStream& stream, ProControllerContext& context, Millisec // followed by a Potion if HP is under half. Anyone else's ends back in the // overworld. Returns whether there was a battle. Between a trainer's last // line and the battle the overworld shows with no dialogue for a moment, -// so "only talked" needs 4 s of it, and never comes when `expect` is -// BATTLE. `format` DOUBLES for tag and twin battles. A lost battle ends in -// the last Pokemon Center; see in_pokemon_center(). +// so "only talked" is talk_over()'s quiet, and never comes when `expect` +// is BATTLE. `format` DOUBLES for tag and twin battles. A lost battle ends +// in the last Pokemon Center; see in_pokemon_center(). enum class TalkExpect{ TALK_OR_BATTLE, BATTLE, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.cpp index 8be35a67dd..5994605164 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.cpp @@ -208,38 +208,81 @@ bool mine_select_run(VideoStream& stream, ProControllerContext& context, BattleT return false; } -// Run on the battle menu, until the battle's exit shows or `timeout` -// runs out. Whether the exit was seen. -bool run_until_escaped( - VideoStream& stream, ProControllerContext& context, BattleType battle_type, - std::chrono::seconds timeout, EndBattleWatcher& battle_end -){ - const auto deadline = std::chrono::steady_clock::now() + timeout; - while (std::chrono::steady_clock::now() < deadline){ - pbf_press_button(context, BUTTON_B, 40ms, 200ms); - context.wait_for_all_requests(); - BattleMenuWatcher menu_ready(battle_type, COLOR_YELLOW); - const int ready = wait_until(stream, context, 3s, {{battle_end}, {menu_ready}}); - if (ready == 0){ - return true; - } - if (ready != 1 || !mine_select_run(stream, context, battle_type)){ - continue; +// The escape policy's game steps on the console. The exit watcher lives +// across the attempts: EndBattleWatcher needs black followed by a visible +// screen, which one attempt's waits may split. +class ConsoleWildBattleEscape : public WildBattleEscapeActions{ +public: + ConsoleWildBattleEscape(VideoStream& stream, ProControllerContext& context, BattleType battle_type) + : m_stream(stream) + , m_context(context) + , m_battle_type(battle_type) + {} + + virtual WildRunOutcome run() override; + virtual void fight() override{ + fight_wild_battle(m_stream, m_context, "Mine escape"); + } + virtual void note(const std::string& text) override{ + m_stream.log("[Mine escape] " + text); + } + + // After the policy gave up: whether the exit still shows within `wait`. + bool exit_within(Milliseconds wait){ + return wait_until(m_stream, m_context, wait, {{m_battle_end}}) == 0; + } + +private: + // B, then the exit (0) or the battle menu (1) within three seconds; -1 for neither. + int exit_or_menu(); + + VideoStream& m_stream; + ProControllerContext& m_context; + BattleType m_battle_type; + EndBattleWatcher m_battle_end; +}; + +int ConsoleWildBattleEscape::exit_or_menu(){ + pbf_press_button(m_context, BUTTON_B, 40ms, 200ms); + m_context.wait_for_all_requests(); + BattleMenuWatcher menu_ready(m_battle_type, COLOR_YELLOW); + return wait_until(m_stream, m_context, 3s, {{m_battle_end}, {menu_ready}}); +} + +WildRunOutcome ConsoleWildBattleEscape::run(){ + const int ready = exit_or_menu(); + if (ready == 0){ + return WildRunOutcome::ESCAPED; + } + if (ready != 1 || !mine_select_run(m_stream, m_context, m_battle_type)){ + return WildRunOutcome::UNCERTAIN; + } + m_stream.log("[Mine escape] Run input sent; watching for black-screen exit."); + const int result = run_until(m_stream, + m_context, + [](ProControllerContext& controller){ + pbf_mash_button(controller, BUTTON_ZL, 1000ms); + pbf_mash_button(controller, BUTTON_A, 1000ms); + pbf_mash_button(controller, BUTTON_B, 3000ms); + controller.wait_for_all_requests(); + }, + {m_battle_end}); + if (result == 0){ + return WildRunOutcome::ESCAPED; + } + // No exit after Run: the menu back means the game refused it ("Can't + // escape!": Onix's Bind in Oreburgh Mine, console B 2026-11-07). Its + // text and the foe's turn take a few seconds. + for (size_t look = 0; look < 2; look++){ + const int seen = exit_or_menu(); + if (seen == 0){ + return WildRunOutcome::ESCAPED; } - stream.log("[Mine escape] Run input sent; watching for black-screen exit."); - const int result = run_until(stream, - context, - [](ProControllerContext& controller){ - pbf_press_button(controller, BUTTON_A, 60ms, 0ms); - pbf_wait(controller, 4s); - controller.wait_for_all_requests(); - }, - {battle_end}); - if (result == 0){ - return true; + if (seen == 1){ + return WildRunOutcome::TRAPPED; } } - return false; + return WildRunOutcome::UNCERTAIN; } // B until the overworld shows; fails with `failure` after two minutes. @@ -389,13 +432,17 @@ void catch_1_pokemon( void escape_wild_battle(VideoStream& stream, ProControllerContext& context, BattleType battle_type, - std::chrono::seconds timeout){ - EndBattleWatcher battle_end; - bool exit_transition = run_until_escaped(stream, context, battle_type, timeout, battle_end); - if (!exit_transition && wait_until(stream, context, 10s, {{battle_end}}) == 0){ - exit_transition = true; + const WildBattleEscapePolicy& policy){ + ConsoleWildBattleEscape actions(stream, context, battle_type); + WildEscapeResult result = escape_wild_battle(actions, policy); + if (result == WildEscapeResult::FOUGHT){ + // fight_wild_battle() ended on the overworld. + return; + } + if (result == WildEscapeResult::UNCONFIRMED && actions.exit_within(10s)){ + result = WildEscapeResult::ESCAPED; } - if (exit_transition){ + if (result == WildEscapeResult::ESCAPED){ // EndBattleWatcher requires black followed by a visible screen. stream.log("[Mine escape] Black-screen exit transition confirmed.", COLOR_GREEN); pbf_wait(context, 800ms); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.h index 6ef1b1b8fa..98a93ffb9b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_WildBattle.h @@ -13,10 +13,10 @@ #ifndef PokemonAutomation_PokemonBDSP_AutoStory_WildBattle_H #define PokemonAutomation_PokemonBDSP_AutoStory_WildBattle_H -#include #include "CommonFramework/Tools/VideoStream.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" #include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -34,13 +34,16 @@ void battle_1_pokemon(VideoStream& stream, ProControllerContext& context); // in the Bag, up to ten throws; ends on the overworld. void catch_1_pokemon(VideoStream& stream, ProControllerContext& context); -// Runs from the wild battle on screen: Run on the battle menu until the -// exit's black screen shows. Fails with a screenshot after `timeout`. +// Leaves the wild battle on screen as `policy` says: Run on the battle menu +// until the exit's black screen shows, or, once the game has refused the +// escape `policy.run_refusals` times (a trapping move), fights it to its end +// with the best move. Fails with a screenshot once the policy gives up and +// the main menu does not prove the overworld either. void escape_wild_battle( VideoStream& stream, ProControllerContext& context, BattleType battle_type = BattleType::STANDARD, - std::chrono::seconds timeout = std::chrono::seconds(30) + const WildBattleEscapePolicy& policy = WildBattleEscapePolicy() ); // escape_wild_battle() for a standard wild battle, as the walker takes it diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp index c3fe3fea36..446ec4a4fd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.cpp @@ -47,8 +47,18 @@ CoordEvent read_event(const JsonObject& object, const std::string& where){ .value = read_int(object, "value", where), .source = read_string(object, "source", where), }; - const int x = read_int(object, "x", where); - const int y = read_int(object, "y", where); + int x = 0; + int y = 0; + if (const JsonArray* coord = object.get_array("coord")){ + if (coord->size() < 2 || !(*coord)[0].is_integer() || !(*coord)[1].is_integer()){ + throw ParseException(where + "coord must have at least 2 integer elements."); + } + x = (int)(*coord)[0].to_integer_default(); + y = (int)(*coord)[1].to_integer_default(); + }else{ + x = read_int(object, "x", where); + y = read_int(object, "y", where); + } const int width = read_int(object, "width", where); const int length = read_int(object, "length", where); if (width < 1 || length < 1){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RobustRoute.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RobustRoute.h index a54bdc1610..c279c21123 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RobustRoute.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RobustRoute.h @@ -38,10 +38,8 @@ 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; + // An open leg of n tiles may end open_hold_error(n) tiles + // short or long. // 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; @@ -49,6 +47,19 @@ struct RobustPlanCosts : TilePlanCosts{ // 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 + // Open legs longer than exact_open_tiles are held for their time + // (TileLeg::held), not tapped: no leg is planned whose possible ends + // past its shortest cross tall grass, a wanderer's zone or a ledge, so + // a long or short hold meets nothing a tap would not have. Off, such + // legs are planned as uncertain but walked in taps. + bool hold_open_legs = false; + // Extra per tall-grass tile an open leg enters. A wild battle on a leg + // to a wall costs nothing to recover from: RouteWalker walks to the + // wall again. On an open leg it loses the tile count, and the walk + // plans again from the tiles round it, often back through the same + // grass (00.04b to_catch_grass, 00.04d north_to_jubilife and 01.06 + // up_jubilifes_road were scored STRAND for that). + int per_open_grass_tile = 0; 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 @@ -61,7 +72,7 @@ struct RobustPlanCosts : TilePlanCosts{ }; // Cheapest legs that take the player from any of the tiles in `from` to tiles -// that are all `goal`, even if every open leg ends up to `open_error` tiles +// that are all `goal`, even if every open leg ends up open_hold_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 @@ -92,7 +103,6 @@ long long robust_route_cost( const RobustPlanCosts& costs ); - } // namespace PokemonBDSP } // namespace NintendoSwitch } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp index a89679cf16..7ea8b80c71 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.cpp @@ -56,7 +56,8 @@ WallHit slide_to_wall(const StoryWorld& world, const TilePos& from, Direction di std::string to_string(const TileLeg& leg){ - return std::format("{} {}{}", Pokemon::direction_name(leg.direction), leg.tiles, leg.ends_at_wall ? " (to wall)" : " (open)"); + return std::format("{} {}{}", Pokemon::direction_name(leg.direction), leg.tiles, + leg.ends_at_wall ? " (to wall)" : leg.held ? " (held)" : " (open)"); } @@ -133,7 +134,7 @@ std::optional> plan_tile_route( } std::vector ret; for (const Pokemon::Leg& leg : *legs){ - ret.push_back(TileLeg{leg.direction, distance(leg.end, leg.start), leg.to_wall}); + ret.push_back(TileLeg{leg.direction, distance(leg.end, leg.start), leg.to_wall, false}); } return ret; } @@ -257,6 +258,38 @@ std::optional step_tiles(const StoryWorld& world, TilePos from, Directi return stepped; } +// step_tiles() for each count from 1 to `most`, in one walk: [n - 1] is +// step_tiles(world, from, direction, n). +std::vector> step_prefixes(const StoryWorld& world, TilePos from, Direction direction, int most){ + std::vector> out; + Stepped stepped; + int travelled = 0; + bool in_wander = wandering_hazard(world, from); + while ((int)out.size() < most){ + const std::optional next = step(world, from, direction); + if (!next){ + stepped.end = from; + const std::optional last = at_wall(world, from, direction) ? std::optional(stepped) : std::nullopt; + out.resize((size_t)most, last); + break; + } + travelled += (int)distance(*next, from); + stepped.grass += tall_grass(world, *next) ? 1 : 0; + 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; + while ((int)out.size() < std::min(travelled, most)){ + out.push_back(stepped); + } + } + return out; +} + using Spread = std::vector; bool spread_less(const TilePos& a, const TilePos& b){ @@ -277,6 +310,9 @@ struct Expansion{ long long cost = 0; Spread next; TileLeg leg; + // A held leg that may end somewhere unsafe: not to be used, though a + // longer one may be. + bool unsafe = false; }; // To the wall: every position walks until stopped. Nothing unless each is @@ -306,32 +342,53 @@ std::optional to_wall_leg(const StoryWorld& world, const Spread& spre } 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}; + expansion.leg = TileLeg{direction, longest, true, false}; return expansion; } +// Whether a held leg's possible ends, `ends` in order from the shortest, +// meet nothing past the shortest that a tap would not: no tall grass, no +// wanderer's zone, no ledge hop. +bool held_ends_safe(const StoryWorld& world, const std::vector& ends){ + for (size_t i = 1; i < ends.size(); i++){ + if (distance(ends[i - 1], ends[i]) > 1 || tall_grass(world, ends[i]) || wandering_hazard(world, ends[i])){ + return false; + } + } + return true; +} + // Open: about `tiles` tiles, give or take the error. Nothing if any -// possible end leaves the maps or enters a door. +// possible end leaves the maps or enters a door, or a held leg's may end +// somewhere unsafe (held_ends_safe()). 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; + const int error = tiles <= costs.exact_open_tiles ? 0 : (int)open_hold_error((size_t)tiles); + const bool held = costs.hold_open_legs && error > 0; for (const TilePos& pos : spread){ + std::vector ends; + const std::vector> prefixes = step_prefixes(world, pos, direction, tiles + error); for (int n = std::max(1, tiles - error); n <= tiles + error; n++){ - const std::optional stepped = step_tiles(world, pos, direction, n); + const std::optional& stepped = prefixes[(size_t)n - 1]; 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); + ends.push_back(stepped->end); } + if (held && !held_ends_safe(world, ends)){ + expansion.unsafe = true; + } + expansion.next.insert(expansion.next.end(), ends.begin(), ends.end()); } + const int per_open_tile = held ? 0 : costs.per_open_tile; 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}; + (long long)(costs.per_tile + per_open_tile) * tiles + + (long long)(costs.per_grass_tile + costs.per_open_grass_tile) * grass + (long long)costs.per_wander_tile * wander; + expansion.leg = TileLeg{.direction = direction, .tiles = (size_t)tiles, .ends_at_wall = false, .held = held}; return expansion; } @@ -385,12 +442,15 @@ class RobustSearch{ if (std::optional wall = to_wall_leg(m_world, spread, direction, m_costs)){ relax(spread, cost, std::move(*wall)); } + // A held leg unsafe at one length may be safe at a longer one. 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)); + if (!open->unsafe){ + relax(spread, cost, std::move(*open)); + } } } } @@ -404,7 +464,7 @@ class RobustSearch{ } if (spread != m_start){ const TileLeg& prev = m_nodes.at(spread).leg.leg; - if (expansion.leg.direction == prev.direction && !prev.ends_at_wall){ + if (expansion.leg.direction == prev.direction && !prev.ends_at_wall && !prev.held && !expansion.leg.held){ expansion.cost -= m_costs.per_leg; } } @@ -429,7 +489,7 @@ class RobustSearch{ for (const PlannedLeg& planned : legs){ if (!consolidated.empty() && consolidated.back().leg.direction == planned.leg.direction && - !consolidated.back().leg.ends_at_wall + !consolidated.back().leg.ends_at_wall && !consolidated.back().leg.held && !planned.leg.held ){ consolidated.back().leg.tiles += planned.leg.tiles; consolidated.back().leg.ends_at_wall = planned.leg.ends_at_wall; @@ -450,6 +510,10 @@ class RobustSearch{ } // namespace +size_t open_hold_error(size_t){ + return 1; +} + std::optional> plan_robust_route( const StoryWorld& world, const TilePos& from, const TilePos& to, @@ -493,7 +557,7 @@ long long robust_route_cost( if (expansion){ cost = expansion->cost; } - if (previous != nullptr && previous->direction == leg.direction && !previous->ends_at_wall){ + if (previous != nullptr && previous->direction == leg.direction && !previous->ends_at_wall && !previous->held && !leg.held){ cost -= costs.per_leg; } total += cost; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h index 5a09e8623c..0673f054ff 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h @@ -35,11 +35,25 @@ struct WallHit{ WallHit slide_to_wall(const StoryWorld& world, const Pokemon::TilePos& from, Pokemon::Direction direction); +// How many tiles short or long a timed hold of `tiles` tiles may end: one. +// On lab-B (2026-11-09, Route 202's lawn, the stick held west, then taps +// back to the wall counting the taps), holds of 200 to 1200 ms moved 2, +// 3, 3, 5, 7, 7, 7, 8 and 9 tiles, each the same on every try (600 ms: 5 +// of 5, with or without B): the error is the rounding of the time to a +// tile, not a drift that grows. Holds of 15 to 30 tiles are not measured +// yet. BDSP's one model of a timed hold's error, for the planner and the +// route scorer (route_score_paces()). +size_t open_hold_error(size_t tiles); + // 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 + // An open leg held for its tiles' time instead of tapped a tile at a + // time: much faster, but it may end open_hold_error() tiles + // short or long (RobustPlanCosts::hold_open_legs). + bool held = false; }; // Formats tile movement leg into human-readable string representation. std::string to_string(const TileLeg& leg); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp index b26f8caf51..f385dfcacc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.cpp @@ -66,7 +66,7 @@ class WallPolicy{ } return Pokemon::WallRecoveryStep{ .positions = std::move(ends), - .hold = {.direction = direction, .tiles = longest, .ends_at_wall = true}, + .hold = {.direction = direction, .tiles = longest, .ends_at_wall = true, .held = false}, }; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_bench.golden.txt b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_bench.golden.txt new file mode 100644 index 0000000000..8709980adc --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_bench.golden.txt @@ -0,0 +1,69 @@ +BDSP AutoStory: the route bench. Each ROUTE step of the story table, its +plan scored by Pokemon::score_route() as RouteWalker walks it (wall legs +held, at a run after 00.03; open legs tapped), then the user's routes for +three of them (TARGET). Written by the test "Route bench: no route scores +worse than Data/route_bench.golden.txt"; rerun it with PA_UPDATE_ROUTE_BENCH=1 +to rewrite this file. A route is worse when its verdict leaves PASS, its +expected or worst time grows or one of its human ratios grows past 1.00; a +route that did not pass is better once it passes. No story route may STRAND. +columns: case | expected ms (interruptions by chance) | worst ms (slowest start and +the costliest single interruption) | nominal ms (slowest start, none) | stops (wall +re-localizations) | recoveries (places an interruption may happen) | replans (of those, +the ones the plan cannot absorb) | slower than human (expected / human ms) | riskier +than human ((recoveries + 1) / (human's + 1)) | more backtracking than human ((replans + +tiles walked back + 1) / (human's + 1); a planned stop at a wall is not backtracking) | +the human's ms (the user's route, a recorded run, or the stand-in: the shortest safe +walk run with no stops) | verdict (why). A ratio above 1.5 is flagged "!". + +00.01 below_the_flute | 4090 | 4090 | 4090 | 1 | 0 | 0 | 5.84! | 1.00 | 1.00 | 700 ms (stand-in) | PASS +00.01 above_the_door | 7230 | 7230 | 7230 | 1 | 0 | 0 | 4.66! | 1.00 | 1.00 | 1550 ms (stand-in) | PASS +00.01 short_of_barrys_door | 11950 | 11950 | 11950 | 1 | 0 | 0 | 4.35! | 1.00 | 1.00 | 2750 ms (stand-in) | PASS +00.01 above_barrys_door | 7230 | 7230 | 7230 | 1 | 0 | 0 | 4.66! | 1.00 | 1.00 | 1550 ms (stand-in) | PASS +00.03 into_rowans_scene | 3030 | 3030 | 3030 | 1 | 0 | 0 | 2.33! | 1.00 | 1.00 | 1300 ms (stand-in) | PASS +00.03 into_dawns_scene | 61510 | 46690 | 34340 | 4 | 22 | 0 | 5.37! | 1.15 | 56.00! | 11450 ms (stand-in) | PASS +00.04 onto_the_path | 4050 | 4050 | 4050 | 2 | 0 | 0 | 5.79! | 1.00 | 1.00 | 700 ms (stand-in) | PASS +00.04 to_ledge_column | 3850 | 3850 | 3850 | 1 | 0 | 0 | 3.21! | 1.00 | 1.00 | 1200 ms (stand-in) | PASS +00.04 along_route_201_road | 36400 | 36400 | 36400 | 0 | 0 | 0 | 2.98! | 1.00 | 0.60 | 12200 ms (user's route) | PASS +00.04 into_twinleaf | 10200 | 10200 | 10200 | 1 | 0 | 0 | 1.00 | 1.00 | 1.00 | 10200 ms (user's route) | PASS +00.04 to_moms_doorstep | 4100 | 4100 | 4100 | 0 | 0 | 0 | 5.47! | 1.00 | 1.00 | 750 ms (stand-in) | PASS +00.04 beside_mom | 900 | 900 | 900 | 0 | 0 | 0 | 2.25! | 1.00 | 1.00 | 400 ms (stand-in) | PASS +00.04 into_moms_call | 2550 | 2550 | 2550 | 1 | 0 | 0 | 1.00 | 1.00 | 1.00 | 2550 ms (user's route) | PASS +00.04 short_of_the_catch_tutorial | 84001 | 81950 | 49900 | 6 | 19 | 7 | 4.73! | 1.00 | 57.00! | 17750 ms (stand-in) | PASS +00.04b to_catch_grass | 11689 | 38550 | 6300 | 2 | 34 | 1 | 17.98! | 17.50! | 2.00! | 650 ms (stand-in) | PASS +00.04b into_sandgem | 9520 | 19400 | 7050 | 3 | 12 | 0 | 2.93! | 4.33! | 1.00 | 3250 ms (stand-in) | PASS +00.04d north_to_jubilife | 73575 | 42700 | 30350 | 8 | 35 | 0 | 7.21! | 1.24 | 80.00! | 10200 ms (stand-in) | PASS +00.05 to_the_school | 9700 | 9700 | 9700 | 0 | 0 | 0 | 6.69! | 1.00 | 1.00 | 1450 ms (stand-in) | PASS +00.05b below_the_presidents_trigger | 4900 | 4900 | 4900 | 0 | 0 | 0 | 5.76! | 1.00 | 1.00 | 850 ms (stand-in) | PASS +00.05b below_the_tv_clown | 21463 | 23600 | 20750 | 1 | 1 | 0 | 4.57! | 2.00! | 5.00! | 4700 ms (stand-in) | PASS +00.05b below_the_company_clown | 21900 | 21900 | 21900 | 0 | 0 | 0 | 6.74! | 1.00 | 3.00! | 3250 ms (stand-in) | PASS +00.05c to_main_boulevard | 2500 | 2500 | 2500 | 0 | 0 | 0 | 3.57! | 1.00 | 1.00 | 700 ms (stand-in) | PASS +00.05c along_main_boulevard | 24100 | 24100 | 24100 | 0 | 0 | 0 | 7.42! | 1.00 | 1.00 | 3250 ms (stand-in) | PASS +00.05c beside_the_president | 10500 | 10500 | 10500 | 0 | 0 | 0 | 4.77! | 1.00 | 1.00 | 2200 ms (stand-in) | PASS +00.05c to_the_route_203_street | 21000 | 21000 | 21000 | 0 | 0 | 0 | 6.00! | 1.00 | 1.00 | 3500 ms (stand-in) | PASS +01.01 west_of_barrys_trigger | 7300 | 7300 | 7300 | 0 | 0 | 0 | 6.35! | 1.00 | 1.00 | 1150 ms (stand-in) | PASS +01.02 by_the_gate | 24815 | 26050 | 13700 | 2 | 9 | 0 | 3.60! | 1.00 | 1.00 | 6900 ms (stand-in) | PASS +01.02 west_of_the_hikers_trigger | 3950 | 3950 | 3950 | 2 | 0 | 0 | 8.78! | 1.00 | 2.00! | 450 ms (stand-in) | PASS +01.02 past_curtis | 10500 | 10500 | 10500 | 0 | 0 | 0 | 6.77! | 1.00 | 1.00 | 1550 ms (stand-in) | PASS +01.02 by_the_east_mouth | 4900 | 4900 | 4900 | 0 | 0 | 0 | 5.76! | 1.00 | 1.00 | 850 ms (stand-in) | PASS +01.02 west_of_the_welcome | 8550 | 8550 | 8550 | 2 | 0 | 0 | 9.00! | 1.00 | 4.00! | 950 ms (stand-in) | PASS +01.02b below_the_centers_door | 6663 | 8800 | 5950 | 2 | 1 | 0 | 2.38! | 2.00! | 2.00! | 2800 ms (stand-in) | PASS +01.03 above_the_mine | 16350 | 16350 | 16350 | 3 | 0 | 0 | 2.75! | 1.00 | 5.00! | 5950 ms (stand-in) | PASS +01.05 east_of_barrys_trigger | 26050 | 26050 | 26050 | 3 | 0 | 0 | 7.44! | 1.00 | 14.00! | 3500 ms (stand-in) | PASS +01.05 through_the_gate | 12050 | 12050 | 12050 | 5 | 0 | 0 | 4.92! | 1.00 | 27.00! | 2450 ms (stand-in) | PASS +01.06 up_jubilifes_road | 87286 | 119950 | 58350 | 3 | 10 | 4 | 7.66! | 2.20! | 20.00! | 11400 ms (stand-in) | PASS +01.06 below_rowans_trigger | 1950 | 1950 | 1950 | 1 | 0 | 0 | 2.29! | 1.00 | 1.00 | 850 ms (stand-in) | PASS +01.08 below_the_ravaged_path | 27098 | 25150 | 12800 | 3 | 12 | 0 | 4.52! | 1.30 | 4.00! | 6000 ms (stand-in) | PASS +01.09 west_of_the_rock | 7050 | 7050 | 7050 | 1 | 0 | 0 | 4.70! | 1.00 | 1.00 | 1500 ms (stand-in) | PASS +01.09 above_the_way_out | 4550 | 4550 | 4550 | 2 | 0 | 0 | 4.14! | 1.00 | 2.00! | 1100 ms (stand-in) | PASS +01.10 line_1 | 900 | 900 | 900 | 0 | 0 | 0 | 2.25! | 1.00 | 1.00 | 400 ms (stand-in) | PASS +01.10 line_2 | 3250 | 3250 | 3250 | 1 | 0 | 0 | 2.83! | 1.00 | 1.00 | 1150 ms (stand-in) | PASS +01.10 line_3 | 4100 | 4100 | 4100 | 0 | 0 | 0 | 4.10! | 1.00 | 1.00 | 1000 ms (stand-in) | PASS +01.10 line_4 | 4050 | 4050 | 4050 | 1 | 0 | 0 | 3.86! | 1.00 | 1.00 | 1050 ms (stand-in) | PASS +01.10 line_5 | 15110 | 20050 | 7700 | 1 | 6 | 0 | 7.75! | 1.17 | 1.00 | 1950 ms (stand-in) | PASS +01.10 line_6 | 3150 | 3150 | 3150 | 1 | 0 | 0 | 3.00! | 1.00 | 1.00 | 1050 ms (stand-in) | PASS +TARGET 00.04 along_route_201_road | 12200 | 12200 | 12200 | 2 | 0 | 0 | 1.00 | 1.00 | 1.00 | 12200 ms (user's route) | PASS +TARGET 00.04 into_twinleaf | 10200 | 10200 | 10200 | 1 | 0 | 0 | 1.00 | 1.00 | 1.00 | 10200 ms (user's route) | PASS +TARGET 00.04 into_moms_call | 2550 | 2550 | 2550 | 1 | 0 | 0 | 1.00 | 1.00 | 1.00 | 2550 ms (user's route) | PASS +00.04 into_twinleaf after run 4's block, planned from the counted tile | 11250 | 11250 | 11250 | 1 | 0 | 0 | 5.00! | 1.00 | 2.00! | 2250 ms (stand-in) | FAIL (may end on (47, 85), off the goal) +00.04 into_twinleaf after run 4's block | 10750 | 10750 | 10750 | 3 | 0 | 0 | 4.78! | 1.00 | 2.00! | 2250 ms (stand-in) | PASS +00.04d north_to_jubilife, planned with the route's own costs (taps in the grass) | 84645 | 66250 | 33200 | 6 | 35 | 5 | 8.30! | 1.24 | 85.00! | 10200 ms (stand-in) | PASS diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt new file mode 100644 index 0000000000..fbc8c921ee --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Data/route_plans.golden.txt @@ -0,0 +1,450 @@ +BDSP AutoStory: the legs each ROUTE step of the story table plans. +Planned as the console's RouteWalker plans them: plan_recovered_route() on +story_plan_world(), from the tiles the row's steps before it leave the +player on, with the step's costs, then the default costs if those find none. +Written by the StoryTable test "every ROUTE step plans as +Data/route_plans.golden.txt says". After a planner or table change, run +that test with PA_UPDATE_ROUTE_PLANS=1 to rewrite this file +(PA_ROUTE_PLANS_GOLDEN= reads or writes another copy), and review +its diff. +turns: direction changes between legs. open: legs that stop in the open +(tapped, not held to a wall). localization: the wall holds at the start +that only bring several start tiles to one (plan_recovered_route()'s +anchor); 0 from one start tile. + +== 00.01 below_the_flute (costs: route) + from: PlayerHouse2F (4, 6) facing north (tile) + target: PlayerHouse2F (7, 5) facing north (tile) + start candidates: PlayerHouse2F (4, 6) + 1. north 1 (to wall) -> PlayerHouse2F (4, 5) + 2. east 3 (open) -> PlayerHouse2F (7, 5) + totals: 2 legs, 1 turns, 1 open, 0 localization + +== 00.01 above_the_door (costs: route) + from: PlayerHouse1F (10, 3) (10, 4) (set) + target: PlayerHouse1F (6, 9) facing south (tile) + start candidates: PlayerHouse1F (10, 3), PlayerHouse1F (10, 4) + 1. south 7 (to wall) -> PlayerHouse1F (10, 10) + 2. north 1 (open) -> PlayerHouse1F (10, 9) + 3. west 4 (open) -> PlayerHouse1F (6, 9) + totals: 3 legs, 2 turns, 2 open, 1 localization + +== 00.01 short_of_barrys_door (costs: route) + from: TwinleafTown (20, 22) facing south (tile) + target: TwinleafTown (10, 12) facing west (tile) + start candidates: Twinleaf Town (20, 22) + 1. west 7 (open) -> Twinleaf Town (13, 22) + 2. north 10 (to wall) -> Twinleaf Town (13, 12) + 3. west 3 (open) -> Twinleaf Town (10, 12) + totals: 3 legs, 2 turns, 2 open, 0 localization + +== 00.01 below_barrys_stairs (costs: route) + from: unknown + target: RivalHouse1F (2, 3) facing east (tile) + not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends) + +== 00.01 above_barrys_door (costs: route) + from: RivalHouse1F (2, 3) (tile) + target: RivalHouse1F (6, 9) facing south (tile) + start candidates: RivalHouse1F (2, 3) + 1. south 7 (to wall) -> RivalHouse1F (2, 10) + 2. north 1 (open) -> RivalHouse1F (2, 9) + 3. east 4 (open) -> RivalHouse1F (6, 9) + totals: 3 legs, 2 turns, 2 open, 0 localization + +== 00.01 below_the_lake_entrance (costs: route) + from: unknown + target: VerityLakefront (17, 14) facing north (tile) + not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends) + +== 00.03 into_rowans_scene (costs: into_scene) + from: VerityLakefront (17, 14) (17, 15) (set) + target: VerityLakefront (17, 21) (tile) + start candidates: Verity Lakefront (17, 14), Verity Lakefront (17, 15) + 1. south 7 (to wall) -> Verity Lakefront (17, 21) + totals: 1 legs, 0 turns, 0 open, 1 localization + +== 00.03 into_dawns_scene (costs: into_scene) + from: TwinleafTown (20, 22) facing south (tile) + target: Route201 (63, 5) facing east (tile) + start candidates: Twinleaf Town (20, 22) + 1. west 3 (open) -> Twinleaf Town (17, 22) + 2. north 34 (to wall) -> Route 201 (17, 13) + 3. east 40 (to wall) -> Route 201 (57, 13) + 4. west 7 (open) -> Route 201 (50, 13) + 5. north 10 (to wall) -> Route 201 (50, 3) + 6. east 13 (to wall) -> Route 201 (63, 3) + 7. south 2 (open) -> Route 201 (63, 5) + totals: 7 legs, 6 turns, 3 open, 0 localization + +== 00.04 onto_the_path (costs: town) + from: SandgemTown (26, 11) (27, 11) (28, 11) (26, 12) (27, 12) (28, 12) facing north (set) + target: SandgemTown (29, 12) facing west (tile) + start candidates: Sandgem Town (26, 11), Sandgem Town (27, 11), Sandgem Town (28, 11), Sandgem Town (26, 12), Sandgem Town (27, 12), Sandgem Town (28, 12) + 1. east 3 (to wall) -> Sandgem Town (29, 11), Sandgem Town (29, 12) + 2. north 1 (to wall) -> Sandgem Town (29, 11) + 3. south 1 (open) -> Sandgem Town (29, 12) + totals: 3 legs, 2 turns, 1 open, 2 localization + +== 00.04 to_ledge_column (costs: line) + from: Route201 (57, 4) (58, 4) (59, 4) (60, 4) (61, 4) (62, 4) (63, 4) facing north (set) + target: Route201 (55, 5) facing west (tile) + start candidates: Route 201 (57, 4), Route 201 (58, 4), Route 201 (59, 4), Route 201 (60, 4), Route 201 (61, 4), Route 201 (62, 4), Route 201 (63, 4) + 1. west 7 (to wall) -> Route 201 (56, 4) + 2. south 1 (open) -> Route 201 (56, 5) + 3. west 1 (open) -> Route 201 (55, 5) + totals: 3 legs, 2 turns, 2 open, 1 localization + +== 00.04 along_route_201_road (costs: line) + from: Route201 (55, 14) facing south (tile) + target: Route201 (15, 14) facing west (tile) + start candidates: Route 201 (55, 14) + 1. west 16 (open) -> Route 201 (39, 14) + 2. north 3 (open) -> Route 201 (39, 11) + 3. west 24 (open) -> Route 201 (15, 11) + 4. south 2 (open) -> Route 201 (15, 14) + totals: 4 legs, 3 turns, 4 open, 0 localization + +== 00.04 into_twinleaf (costs: line) + from: Route201 (15, 14) facing west (tile) + target: TwinleafTown (15, 22) facing south (tile) + start candidates: Route 201 (15, 14) + 1. south 37 (to wall) -> Twinleaf Town (15, 26) + 2. north 4 (open) -> Twinleaf Town (15, 22) + totals: 2 legs, 1 turns, 1 open, 0 localization + +== 00.04 to_moms_doorstep (costs: line) + from: TwinleafTown (15, 22) facing south (tile) + target: TwinleafTown (20, 22) facing north (tile) + start candidates: Twinleaf Town (15, 22) + 1. east 5 (open) -> Twinleaf Town (20, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.04 beside_mom (costs: route) + from: PlayerHouse1F (6, 9) facing north (tile) + target: PlayerHouse1F (6, 8) facing east (tile) + start candidates: PlayerHouse1F (6, 9) + 1. north 1 (open) -> PlayerHouse1F (6, 8) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.04 into_moms_call (costs: trigger) + from: PlayerHouse1F (11, 8) facing south (tile) + target: PlayerHouse1F (6, 9) facing west (tile) + start candidates: PlayerHouse1F (11, 8) + 1. west 1 (open) -> PlayerHouse1F (10, 8) + 2. south 1 (open) -> PlayerHouse1F (10, 9) + 3. west 4 (to wall) -> PlayerHouse1F (6, 9) + totals: 3 legs, 2 turns, 2 open, 0 localization + +== 00.04 short_of_the_catch_tutorial (costs: route) + from: TwinleafTown (6, 22) (6, 23) facing west (set) + target: Route202 (22, 27) facing west (tile) + start candidates: Twinleaf Town (6, 22), Twinleaf Town (6, 23) + 1. north 19 (to wall) -> Twinleaf Town (6, 4) + 2. east 8 (open) -> Twinleaf Town (14, 4) + 3. north 16 (to wall) -> Route 201 (14, 13) + 4. east 43 (to wall) -> Route 201 (57, 13) + 5. west 7 (open) -> Route 201 (50, 13) + 6. north 7 (open) -> Route 201 (50, 6) + 7. east 43 (to wall) -> Sandgem Town (29, 13) + 8. west 5 (open) -> Sandgem Town (24, 13) + 9. north 21 (to wall) -> Route 202 (25, 24) + 10. west 3 (to wall) -> Route 202 (22, 24) + 11. south 3 (open) -> Route 202 (22, 27) + totals: 11 legs, 10 turns, 5 open, 1 localization + +== 00.04b to_catch_grass (costs: route) + from: Route202 (15, 25) (16, 25) (17, 25) (18, 25) (19, 25) (20, 25) (21, 25) (15, 26) (16, 26) (17, 26) (18, 26) (19, 26) (20, 26) (21, 26) (15, 27) (16, 27) (17, 27) (18, 27) (19, 27) (20, 27) (21, 27) (21, 28) (21, 29) (set) + target: Route202 (18, 25) (19, 25) (20, 25) (18, 26) (19, 26) (20, 26) (18, 27) (19, 27) (20, 27) (set) + start candidates: Route 202 (15, 25), Route 202 (16, 25), Route 202 (17, 25), Route 202 (18, 25), Route 202 (19, 25), Route 202 (20, 25), Route 202 (21, 25), Route 202 (15, 26), Route 202 (16, 26), Route 202 (17, 26), Route 202 (18, 26), Route 202 (19, 26), Route 202 (20, 26), Route 202 (21, 26), Route 202 (15, 27), Route 202 (16, 27), Route 202 (17, 27), Route 202 (18, 27), Route 202 (19, 27), Route 202 (20, 27), Route 202 (21, 27), Route 202 (21, 28), Route 202 (21, 29) + 1. north 4 (to wall) -> Route 202 (15, 25), Route 202 (16, 25), Route 202 (17, 25), Route 202 (18, 25), Route 202 (19, 25), Route 202 (20, 25), Route 202 (21, 25) + 2. east 8 (to wall) -> Route 202 (23, 25) + 3. west 3 (open) -> Route 202 (20, 25) + totals: 3 legs, 2 turns, 1 open, 2 localization + +== 00.04b into_sandgem (costs: robust) + from: Route202 (18, 25) (19, 25) (20, 25) (18, 26) (19, 26) (20, 26) (18, 27) (19, 27) (20, 27) (set) + target: SandgemTown (29, 5) (tile) + start candidates: Route 202 (18, 25), Route 202 (19, 25), Route 202 (20, 25), Route 202 (18, 26), Route 202 (19, 26), Route 202 (20, 26), Route 202 (18, 27), Route 202 (19, 27), Route 202 (20, 27) + 1. south 2 (to wall) -> Route 202 (18, 27), Route 202 (19, 27), Route 202 (20, 27) + 2. east 12 (to wall) -> Route 202 (30, 27) + 3. south 10 (to wall) -> Sandgem Town (29, 5) + totals: 3 legs, 2 turns, 0 open, 2 localization + +== 00.04d north_to_jubilife (costs: route) + from: Route202 (30, 24) (tile) + target: Route202 (11, 0) (12, 0) (13, 0) (14, 0) (15, 0) (16, 0) (17, 0) (18, 0) (11, 1) (12, 1) (13, 1) (14, 1) (15, 1) (16, 1) (17, 1) (18, 1) (11, 2) (12, 2) (13, 2) (14, 2) (15, 2) (16, 2) (17, 2) (18, 2) (11, 3) (12, 3) (13, 3) (14, 3) (15, 3) (16, 3) (17, 3) (18, 3) (set) + start candidates: Route 202 (30, 24) + 1. south 2 (open) -> Route 202 (30, 26) + 2. west 27 (to wall) -> Route 202 (3, 26) + 3. north 12 (to wall) -> Route 202 (3, 14) + 4. east 14 (to wall) -> Route 202 (17, 14) + 5. south 8 (to wall) -> Route 202 (17, 22) + 6. east 13 (to wall) -> Route 202 (30, 22) + 7. north 18 (to wall) -> Route 202 (30, 4) + 8. south 1 (open) -> Route 202 (30, 5) + 9. west 5 (open) -> Route 202 (25, 5) + 10. north 1 (to wall) -> Route 202 (25, 4) + 11. west 7 (to wall) -> Route 202 (18, 4) + 12. north 1 (open) -> Route 202 (18, 3) + totals: 12 legs, 11 turns, 4 open, 0 localization + +== 00.05 to_the_center (costs: town) + from: unknown + target: JubilifeCity (52, 41) facing north (tile) + not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends) + +== 00.05 to_the_school (costs: town) + from: JubilifeCity (52, 41) facing north (tile) + target: JubilifeCity (40, 41) facing north (tile) + start candidates: Jubilife City (52, 41) + 1. west 12 (open) -> Jubilife City (40, 41) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.05b below_the_presidents_trigger (costs: town) + from: JubilifeCity (40, 41) facing south (tile) + target: JubilifeCity (46, 41) facing north (tile) + start candidates: Jubilife City (40, 41) + 1. east 6 (open) -> Jubilife City (46, 41) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.05b below_the_mart_clown (costs: town) + from: unknown + target: JubilifeCity (55, 34) facing north (tile) + not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends) + +== 00.05b below_the_tv_clown (costs: town) + from: JubilifeCity (55, 34) facing north (tile) + target: JubilifeCity (36, 17) facing north (tile) + start candidates: Jubilife City (55, 34) + 1. west 23 (to wall) -> Jubilife City (32, 34) + 2. north 10 (open) -> Jubilife City (32, 24) + 3. east 4 (open) -> Jubilife City (36, 24) + 4. north 7 (open) -> Jubilife City (36, 17) + totals: 4 legs, 3 turns, 3 open, 0 localization + +== 00.05b below_the_company_clown (costs: town) + from: JubilifeCity (36, 17) facing north (tile) + target: JubilifeCity (15, 19) facing north (tile) + start candidates: Jubilife City (36, 17) + 1. south 4 (open) -> Jubilife City (36, 21) + 2. west 21 (open) -> Jubilife City (15, 21) + 3. north 2 (open) -> Jubilife City (15, 19) + totals: 3 legs, 2 turns, 3 open, 0 localization + +== 00.05c to_main_boulevard (costs: line) + from: JubilifeCity (15, 19) facing north (tile) + target: JubilifeCity (15, 22) facing south (tile) + start candidates: Jubilife City (15, 19) + 1. south 3 (open) -> Jubilife City (15, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.05c along_main_boulevard (costs: line) + from: JubilifeCity (15, 22) facing south (tile) + target: JubilifeCity (45, 22) facing south (tile) + start candidates: Jubilife City (15, 22) + 1. east 30 (open) -> Jubilife City (45, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.05c beside_the_president (costs: line) + from: JubilifeCity (45, 22) facing south (tile) + target: JubilifeCity (45, 35) facing east (tile) + start candidates: Jubilife City (45, 22) + 1. south 13 (open) -> Jubilife City (45, 35) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 00.05c to_the_route_203_street (costs: line) + from: JubilifeCity (45, 35) facing east (tile) + target: JubilifeCity (58, 22) facing east (tile) + start candidates: Jubilife City (45, 35) + 1. north 13 (open) -> Jubilife City (45, 22) + 2. east 13 (open) -> Jubilife City (58, 22) + totals: 2 legs, 1 turns, 2 open, 0 localization + +== 01.01 west_of_barrys_trigger (costs: town) + from: JubilifeCity (58, 22) facing east (tile) + target: Route203 (4, 18) facing east (tile) + start candidates: Jubilife City (58, 22) + 1. east 9 (open) -> Route 203 (4, 18) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.02 by_the_gate (costs: route) + from: Route203 (5, 20) facing south (tile) + target: Route203 (55, 9) facing east (tile) + start candidates: Route 203 (5, 20) + 1. north 2 (open) -> Route 203 (5, 18) + 2. east 50 (to wall) -> Route 203 (55, 18) + 3. north 12 (to wall) -> Route 203 (55, 6) + 4. south 3 (open) -> Route 203 (55, 9) + totals: 4 legs, 3 turns, 2 open, 0 localization + +== 01.02 west_of_the_hikers_trigger (costs: route) + from: OreburghGate (4, 22) (5, 22) facing east (set) + target: OreburghGate (6, 22) facing east (tile) + start candidates: OreburghGate (4, 22), OreburghGate (5, 22) + 1. south 1 (to wall) -> OreburghGate (4, 23), OreburghGate (5, 23) + 2. east 2 (to wall) -> OreburghGate (6, 23) + 3. north 1 (open) -> OreburghGate (6, 22) + totals: 3 legs, 2 turns, 1 open, 2 localization + +== 01.02 past_curtis (costs: route) + from: OreburghGate (7, 22) facing east (tile) + target: OreburghGate (20, 22) facing east (tile) + start candidates: OreburghGate (7, 22) + 1. east 13 (open) -> OreburghGate (20, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.02 by_the_east_mouth (costs: route) + from: OreburghGate (20, 22) facing east (tile) + target: OreburghGate (26, 22) facing east (tile) + start candidates: OreburghGate (20, 22) + 1. east 6 (open) -> OreburghGate (26, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.02 west_of_the_welcome (costs: route) + from: OreburghCity (2, 13) (3, 13) facing east (set) + target: OreburghCity (9, 13) facing east (tile) + start candidates: Oreburgh City (2, 13), Oreburgh City (3, 13) + 1. north 3 (to wall) -> Oreburgh City (2, 10), Oreburgh City (3, 10) + 2. east 4 (to wall) -> Oreburgh City (6, 10) + 3. south 3 (open) -> Oreburgh City (6, 13) + 4. east 3 (open) -> Oreburgh City (9, 13) + totals: 4 legs, 3 turns, 2 open, 2 localization + +== 01.02b below_the_centers_door (costs: town) + from: OreburghCity (26, 22) facing north (tile) + target: OreburghCity (47, 21) facing north (tile) + start candidates: Oreburgh City (26, 22) + 1. east 22 (to wall) -> Oreburgh City (48, 22) + 2. north 1 (to wall) -> Oreburgh City (48, 21) + 3. west 1 (open) -> Oreburgh City (47, 21) + totals: 3 legs, 2 turns, 1 open, 0 localization + +== 01.03 above_the_mine (costs: town) + from: OreburghCity (47, 21) (46, 21) facing south (set) + target: OreburghCity (46, 57) facing south (tile) + start candidates: Oreburgh City (47, 21), Oreburgh City (46, 21) + 1. east 2 (to wall) -> Oreburgh City (48, 21) + 2. west 4 (open) -> Oreburgh City (44, 21) + 3. south 20 (to wall) -> Oreburgh City (44, 41) + 4. west 1 (open) -> Oreburgh City (43, 41) + 5. south 16 (to wall) -> Oreburgh City (43, 57) + 6. east 3 (open) -> Oreburgh City (46, 57) + totals: 6 legs, 5 turns, 3 open, 1 localization + +== 01.05 east_of_barrys_trigger (costs: town) + from: OreburghCity (26, 21) (26, 22) facing south (set) + target: OreburghCity (7, 13) facing west (tile) + start candidates: Oreburgh City (26, 21), Oreburgh City (26, 22) + 1. south 5 (to wall) -> Oreburgh City (26, 26) + 2. west 2 (to wall) -> Oreburgh City (24, 26) + 3. north 5 (to wall) -> Oreburgh City (24, 21) + 4. west 9 (open) -> Oreburgh City (15, 21) + 5. north 8 (open) -> Oreburgh City (15, 13) + 6. west 8 (open) -> Oreburgh City (7, 13) + totals: 6 legs, 5 turns, 3 open, 1 localization + +== 01.05 through_the_gate (costs: route) + from: OreburghGate (27, 22) (26, 22) facing west (set) + target: OreburghGate (5, 22) facing west (tile) + start candidates: OreburghGate (27, 22), OreburghGate (26, 22) + 1. north 2 (to wall) -> OreburghGate (27, 20), OreburghGate (26, 21) + 2. east 1 (to wall) -> OreburghGate (27, 20), OreburghGate (27, 21) + 3. south 3 (to wall) -> OreburghGate (27, 23) + 4. west 19 (to wall) -> OreburghGate (8, 23) + 5. north 1 (to wall) -> OreburghGate (8, 22) + 6. west 3 (open) -> OreburghGate (5, 22) + totals: 6 legs, 5 turns, 1 open, 3 localization + +== 01.06 up_jubilifes_road (costs: town) + from: Route203 (55, 9) facing west (tile) + target: JubilifeCity (41, 8) facing north (tile) + start candidates: Route 203 (55, 9) + 1. south 10 (to wall) -> Route 203 (55, 19) + 2. west 17 (to wall) -> Route 203 (38, 19) + 3. north 1 (open) -> Route 203 (38, 18) + 4. west 60 (open) -> Jubilife City (41, 22) + 5. north 14 (to wall) -> Jubilife City (41, 8) + totals: 5 legs, 4 turns, 2 open, 0 localization + +== 01.06 below_rowans_trigger (costs: town) + from: JubilifeCity (41, 8) facing north (tile) + target: JubilifeCity (47, 8) facing north (tile) + start candidates: Jubilife City (41, 8) + 1. east 6 (to wall) -> Jubilife City (47, 8) + totals: 1 legs, 0 turns, 0 open, 0 localization + +== 01.08 below_the_ravaged_path (costs: town) + from: JubilifeCity (44, 5) facing west (tile) + target: Route204South (11, 2) facing north (tile) + start candidates: Jubilife City (44, 5) + 1. east 2 (open) -> Jubilife City (46, 5) + 2. north 19 (to wall) -> Route 204 (14, 18) + 3. west 2 (open) -> Route 204 (12, 18) + 4. north 16 (to wall) -> Route 204 (12, 2) + 5. west 1 (to wall) -> Route 204 (11, 2) + totals: 5 legs, 4 turns, 2 open, 0 localization + +== 01.09 west_of_the_rock (costs: route) + from: RavagedPath (19, 50) facing north (tile) + target: RavagedPath (21, 43) facing east (tile) + start candidates: RavagedPath (19, 50) + 1. north 10 (to wall) -> RavagedPath (19, 40) + 2. south 3 (open) -> RavagedPath (19, 43) + 3. east 2 (open) -> RavagedPath (21, 43) + totals: 3 legs, 2 turns, 2 open, 0 localization + +== 01.09 above_the_way_out (costs: route) + from: RavagedPath (21, 43) facing east (tile) + target: RavagedPath (28, 44) facing south (tile) + start candidates: RavagedPath (21, 43) + 1. east 8 (to wall) -> RavagedPath (29, 43) + 2. south 1 (to wall) -> RavagedPath (29, 44) + 3. west 1 (open) -> RavagedPath (28, 44) + totals: 3 legs, 2 turns, 1 open, 0 localization + +== 01.10 line_1 (costs: line) + from: Route204North (20, 26) facing south (tile) + target: Route204North (20, 27) (tile) + start candidates: Route 204 (20, 26) + 1. south 1 (open) -> Route 204 (20, 27) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.10 line_2 (costs: line) + from: Route204North (20, 27) (tile) + target: Route204North (11, 27) (tile) + start candidates: Route 204 (20, 27) + 1. west 10 (to wall) -> Route 204 (10, 27) + 2. east 1 (open) -> Route 204 (11, 27) + totals: 2 legs, 1 turns, 1 open, 0 localization + +== 01.10 line_3 (costs: line) + from: Route204North (11, 27) (tile) + target: Route204North (11, 22) (tile) + start candidates: Route 204 (11, 27) + 1. north 5 (open) -> Route 204 (11, 22) + totals: 1 legs, 0 turns, 1 open, 0 localization + +== 01.10 line_4 (costs: line) + from: Route204North (11, 22) (tile) + target: Route204North (19, 22) (tile) + start candidates: Route 204 (11, 22) + 1. east 10 (to wall) -> Route 204 (21, 22) + 2. west 2 (open) -> Route 204 (19, 22) + totals: 2 legs, 1 turns, 1 open, 0 localization + +== 01.10 line_5 (costs: line) + from: Route204North (19, 22) (tile) + target: Route204North (19, 12) (tile) + start candidates: Route 204 (19, 22) + 1. north 15 (to wall) -> Route 204 (19, 7) + 2. south 5 (open) -> Route 204 (19, 12) + totals: 2 legs, 1 turns, 1 open, 0 localization + +== 01.10 line_6 (costs: line) + from: Route204North (19, 12) (tile) + target: Route204North (11, 12) (tile) + start candidates: Route 204 (19, 12) + 1. west 9 (to wall) -> Route 204 (10, 12) + 2. east 1 (open) -> Route 204 (11, 12) + totals: 2 legs, 1 turns, 1 open, 0 localization diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.cpp new file mode 100644 index 0000000000..387864b251 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.cpp @@ -0,0 +1,55 @@ +/* BDSP AutoStory - Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkScreen.h" +#include "PokemonBDSP_AutoStory_ScreenEvents.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::ScreenEvent; +using Pokemon::ScreenEvents; + + +BdspScreenObserver::BdspScreenObserver(BattleCue cue, std::string banner) + : m_cue(cue) + , m_banner(std::move(banner)) + , m_wild_menu(BattleType::STANDARD) + , m_trainer_menu(BattleType::TRAINER) +{} + +ScreenEvents BdspScreenObserver::observe(const VideoSnapshot& frame, WallClock now){ + ScreenEvents out; + if (!frame){ + m_previous = VideoSnapshot(); + return out; + } + const ImageViewRGB32& screen = *frame.frame; + out.set(ScreenEvent::BATTLE_STARTED, m_wild_menu.detect(screen) || (m_cue == BattleCue::TRAINER && + (m_trainer_menu.detect(screen) || m_black.detect(screen)))); + out.set(ScreenEvent::DIALOG_BOX, m_dialog.detect(screen)); + out.set(ScreenEvent::PLAYER_CAN_MOVE, m_overworld.detect(screen)); + out.set(ScreenEvent::SCREEN_STILL, m_previous && walk_screen_change(*m_previous.frame, screen) < WALK_TAP_BLOCKED_CHANGE); + out.merge(Pokemon::fade_events(fade_of_screen(screen))); + out.set(ScreenEvent::LOCATION_BANNER, !m_banner.empty() && location_banner_matches(m_reads.read(screen, now), m_banner)); + m_previous = frame; + return out; +} + +void BdspScreenObserver::make_overlays(VideoOverlaySet& items) const{ + m_dialog.make_overlays(items); + m_overworld.make_overlays(items); + m_wild_menu.make_overlays(items); +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.h new file mode 100644 index 0000000000..b9fb719e77 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.h @@ -0,0 +1,65 @@ +/* BDSP AutoStory - Screen Events + * + * From: https://github.com/PokemonAutomation/ + * + * BDSP's detectors as the shared screen events (Pokemon_ScreenEvents.h): + * the dialogue box, the overworld, a still screen, a fade, the expected + * map's location banner and a battle's start. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_ScreenEvents_H +#define PokemonAutomation_PokemonBDSP_AutoStory_ScreenEvents_H + +#include +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LocationBannerWatcher.h" +#include "PokemonBDSP_AutoStory_OverworldDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// What BATTLE_STARTED is. +enum class BattleCue{ + // A wild battle's menu. A black screen is a fade. + WILD_MENU, + // Also a trainer's battle: its menu (Roark's read as STANDARD, r210d) + // or the black screen it opens with. + TRAINER, +}; + +// The shared events from BDSP's detectors. Not the choice box, the +// interact prompt or a battle's end: no AutoStory step reads them yet. +class BdspScreenObserver : public Pokemon::ScreenEventObserver{ +public: + // `banner`: the expected map's banner name; LOCATION_BANNER is only it + // ("" for none). + BdspScreenObserver(BattleCue cue, std::string banner); + + virtual Pokemon::ScreenEvents observe(const VideoSnapshot& frame, WallClock now) override; + virtual void make_overlays(VideoOverlaySet& items) const override; + +private: + BattleCue m_cue; + std::string m_banner; + ShortDialogDetector m_dialog; + OverworldDetector m_overworld; + BattleMenuDetector m_wild_menu; + BattleMenuDetector m_trainer_menu; + BlackScreenDetector m_black; + LocationBannerReads m_reads; + VideoSnapshot m_previous; +}; + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp index 61d1d2ba92..eea967670d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "Data/PokemonBDSP_AutoStory_Maps.h" @@ -22,15 +23,16 @@ #include "Data/PokemonBDSP_AutoStory_StoryTrainers.h" #include "Data/PokemonBDSP_AutoStory_TrainerSight.h" #include "Data/PokemonBDSP_AutoStory_WalkRules.h" +#include "Data/PokemonBDSP_AutoStory_WallRecovery.h" +#include "Utils/PokemonBDSP_AutoStory_PlannedRoute.h" +#include "Utils/PokemonBDSP_AutoStory_RouteIO.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" #include "PokemonBDSP_AutoStory_StoryExecutor.h" -#include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_StoryTable.h" #include "Utils/PokemonBDSP_AutoStory_StoryLanguage.h" -#include "Utils/PokemonBDSP_AutoStory_PlannedRoute.h" -#include "Utils/PokemonBDSP_AutoStory_RouteIO.h" #include "Utils/PokemonBDSP_AutoStory_RouteTiming.h" #include "PokemonBDSP_AutoStory_PlannedRoute_Tests.h" #include "Utils/PokemonBDSP_AutoStory_WalkResult.h" @@ -107,11 +109,11 @@ class ScriptedRouteIO : public RouteIO{ {} virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override{ - m_script.legs.push_back({.direction = walk.direction, .tiles = 0, .ends_at_wall = true}); + m_script.legs.push_back({.direction = walk.direction, .tiles = 0, .ends_at_wall = true, .held = false}); return expect("wall: " + walk.label).walk; } virtual WalkResult walk_taps(Direction direction, size_t tiles, const std::string& label) override{ - m_script.legs.push_back({.direction = direction, .tiles = tiles, .ends_at_wall = false}); + m_script.legs.push_back({.direction = direction, .tiles = tiles, .ends_at_wall = false, .held = false}); return expect(std::format("{} taps: {}", tiles, label)).walk; } virtual void press(const RouteInput& input) override{ @@ -370,6 +372,165 @@ UnitTestResult test_open_leg_known_trainer(Logger&){ } +// 01.08's walk below the Ravaged Path (lab-B 2026-11-08 16:50): the leg +// north up Route 204 South ended at (13, 2), and the leg "west 2 (to +// wall)" to (11, 2) stopped at once, 0 chunks moved: the wandering +// youngster (the map's youngster_3, wandering (12, 2) to (14, 2)) stood on +// (12, 2). The world joins Jubilife and Route 204 South, as the step's. +const StoryWorld& ravaged_path_world(){ + static const StoryWorld* const world = story_plan_world("JubilifeCity", "Route204South"); + return *world; +} +TilePos on_route204_south(TilePos local){ + return story_to_world(ravaged_path_world(), "Route204South", local); +} + +// Routes no longer run along a wander zone, so that leg is no longer +// planned on Route 204 South: the walks below replay it on a plain room, +// from (3, 1) "west 2 (to wall)" to (1, 1), the person on (2, 1), with a +// row below to plan round them. +StoryWorld youngster_room(){ + return make_world({"#####", "#...#", "#...#", "#####"}); +} + +// The console's first walk west: blocked after 800 ms, no chunk moved. +ScriptStep west_never_moved(){ + return walk_step("wall: T: west 2 (to wall)", WalkStop::BLOCKED, 1050ms, 0); +} + +// A youngster who steps off the leg's next tile while we wait is waited +// out, on a leg of two tiles too: the walk west then reaches the wall at +// (11, 2). The wait used to need a stop at least three tiles short of the +// wall, so the person one tile ahead was talked to instead. +UnitTestResult test_short_leg_waits_for_the_way(Logger&){ + Script script{.steps = { + west_never_moved(), + press_step("wait 2500 ms x1"), + walk_step("wall: T: west 2 (to wall)", WalkStop::BLOCKED, 3000ms, 2), + answer_step("dialog within 500 ms", false), + }}; + ScriptedWalk walk; + try{ + walk = walk_script(youngster_room(), {3, 1}, {1, 1}, {}, script); + }catch (const ScriptMismatch& e){ + return e.message; + } + if (!walk.failure.empty() || !walk.fights.empty()){ + return std::format("expected to wait and walk on; fought {}, failure \"{}\".", walk.fights.size(), walk.failure); + } + if (walk.at != std::vector{{1, 1}}){ + return "did not arrive at (1, 1)."; + } + const std::string left = script_left(script); + return left.empty() ? UnitTestResult(true) : UnitTestResult(left); +} + +// Whether the replan after the youngster's talk starts from (3, 1) alone, +// with (2, 1) marked, and plans a route. +std::string check_never_moved_replan(const Script& script){ + const std::string replan = check_replan_from(script, {"(3, 1)"}); + if (!replan.empty()){ + return replan; + } + const auto replan_note = std::find_if(script.notes.begin(), script.notes.end(), [](const std::string& note){ + return note.find("planning again") != std::string::npos; + }); + if (replan_note->find("(2, 1)") != std::string::npos){ + return "the replan still starts from the youngster's tile: " + *replan_note; + } + const auto marked = std::find_if(script.notes.begin(), script.notes.end(), [](const std::string& note){ + return note.find("marked it") != std::string::npos; + }); + if (marked == script.notes.end() || marked->find("(2, 1)") == std::string::npos){ + return "the youngster's tile (2, 1) was not marked."; + } + const size_t plans = std::count_if(script.notes.begin(), script.notes.end(), [](const std::string& note){ + return note.find("legs planned") != std::string::npos; + }); + if (plans != 2){ + return std::format("{} plans made, expected the first and the replan.", plans); + } + return ""; +} + +// The youngster stays on (12, 2) through both waits and talks without a +// battle. The console then planned from {(12, 2), (13, 2)}, one tile per +// tile the walk may have moved, and found no plan: an uncertain start +// needs a wall both tiles reach (wall_recovery_candidates()), and no wall +// is anchored from a tile someone wanders on, which both are. A walk that +// never moved stopped where it began: the replan starts from the start +// alone, with the youngster's tile marked (on youngster_room()). +UnitTestResult test_never_moved_plans_from_the_start(Logger& logger){ + const StoryWorld& world = ravaged_path_world(); + const std::vector console_from{on_route204_south({12, 2}), on_route204_south({13, 2})}; + if (!wall_recovery_candidates(world, console_from).empty()){ + return "the console's two tiles have a wall to anchor on: the cause is not the wander box."; + } + logger.log("No wall anchors from Route 204 South (12, 2) and (13, 2): both are in youngster_3's wander box."); + Script script{.steps = { + west_never_moved(), + press_step("wait 2500 ms x1"), + west_never_moved(), + press_step("wait 2500 ms x1"), + west_never_moved(), + press_step("A 80 ms x1"), + answer_step("dialog within 2000 ms", true), + }}; + ScriptedWalk walk; + std::string stopped_at; + try{ + walk = walk_script(youngster_room(), {3, 1}, {1, 1}, {}, script); + }catch (const ScriptMismatch& e){ + // The walk after the replan is not scripted. + stopped_at = e.message; + } + if (!walk.failure.empty()){ + return "failed: " + walk.failure; + } + if (script.next != script.steps.size()){ + return "stopped at: " + stopped_at; + } + for (const std::string& note : script.notes){ + logger.log(note); + } + const std::string replan = check_never_moved_replan(script); + return replan.empty() ? UnitTestResult(true) : UnitTestResult(replan); +} + +// A leg to the wall two tiles away that runs out of time after one tile +// (one chunk moved): someone stands in it, as Route 204's youngster did on +// 01.08's "west 2 (to wall)" (lab-B 2026-11-08). The check at the wall +// allowed a tile short on legs of two or three tiles, so the stop against +// him passed as the wall and the route went on a tile off. Now it is a +// stop short of the wall: talk to whoever is there, then plan again. +UnitTestResult test_short_leg_a_tile_short_is_not_arrived(Logger&){ + const StoryWorld room = make_world({"####", "#..#", "#..#", "#..#", "####"}); + Script script{.steps = { + walk_step("wall: T: north 2 (to wall)", WalkStop::LIMIT, 1850ms, 1), + press_step("A 80 ms x1"), + answer_step("dialog within 2000 ms", false), + }}; + ScriptedWalk walk; + std::string stopped_at; + try{ + walk = walk_script(room, {1, 3}, {1, 1}, {}, script); + }catch (const ScriptMismatch& e){ + // The walk after the replan is not scripted. + stopped_at = e.message; + } + if (!walk.failure.empty()){ + return "failed: " + walk.failure; + } + if (script.next != script.steps.size()){ + return "went on as at the wall: " + stopped_at; + } + const bool replanned = std::any_of(script.notes.begin(), script.notes.end(), [](const std::string& note){ + return note.find("stopped early after about 1 tiles") != std::string::npos && note.find("planning again") != std::string::npos; + }); + return replanned ? UnitTestResult(true) : UnitTestResult("no replan after the stop a tile short."); +} + + // The console as a small simulator: the player stands on one tile of // `world`, walls and `obstacles` stop them, and every walk and tap moves // them. Fails the case after `max_calls` calls (a walker that loops). @@ -391,7 +552,8 @@ class SimulatedRouteIO : public RouteIO{ virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override{ count_call(); - const Milliseconds per_tile = route_ms_per_tile(walk.direction, MoveSpeed::WALK); + const MoveSpeed speed = walk.options.pace == DpadPace::RUN ? MoveSpeed::RUN : MoveSpeed::WALK; + const Milliseconds per_tile = route_ms_per_tile(walk.direction, speed); if (m_overshoot && walk.limit > ROUTE_START_DELAY){ // A hold timed for n tiles (ROUTE_START_DELAY, then half a // tile under n) goes on past them until a wall stops it. @@ -547,27 +709,31 @@ size_t jubilife_shortest(const StoryWorld& world, TilePos from, TilePos goal){ // at (52, 41) nowhere near the Center. Timed holds overshoot by up to // ceil(0.35 n) tiles (three runs of 10 went about 13); taps are exact. // With every timed hold overshooting the walk still ends on the tile. +// Run (the program after the shoes, 00.05 heal_jubilife) and walk alike. UnitTestResult test_jubilife_center_held_overshoot(Logger&){ const StoryWorld world = jubilife_world(); const TilePos from{48, 62}; const TilePos goal{52, 41}; - std::vector notes; - SimulatedRouteIO io(world, from, {}, notes); - io.overshoot_timed_holds(true); - RouteTrainers trainers{.sights = {}, .fight = [](const std::string&){}}; - try{ - walk_route(io, world, {from}, trainers, { - .goal = [goal](const TilePos& pos){ return pos == goal; }, - .label = "T", - .avoid = {}, - .costs = town_plan_costs(), - .speed = MoveSpeed::WALK, - }); - }catch (const RouteFailed& e){ - return "failed: " + e.message; - } - if (io.at() != goal){ - return "ended at " + Pokemon::to_string(io.at()) + ", not at (52, 41)."; + for (const MoveSpeed speed : {MoveSpeed::RUN, MoveSpeed::WALK}){ + const std::string_view pace = speed == MoveSpeed::RUN ? "running" : "walking"; + std::vector notes; + SimulatedRouteIO io(world, from, {}, notes); + io.overshoot_timed_holds(true); + RouteTrainers trainers{.sights = {}, .fight = [](const std::string&){}}; + try{ + walk_route(io, world, {from}, trainers, { + .goal = [goal](const TilePos& pos){ return pos == goal; }, + .label = "T", + .avoid = {}, + .costs = town_plan_costs(), + .speed = speed, + }); + }catch (const RouteFailed& e){ + return std::format("{}: failed: {}", pace, e.message); + } + if (io.at() != goal){ + return std::format("{}: ended at {}, not at (52, 41).", pace, Pokemon::to_string(io.at())); + } } return true; } @@ -767,11 +933,23 @@ const PlannedRouteCase PLANNED_ROUTE_CASES[] = { .expectation = {}, }, { - .input = {"blocked from several possible tiles routes around", test_blocked_from_several_tiles}, + .input = {"a person a tile ahead on a short leg is waited out", test_short_leg_waits_for_the_way}, .expectation = {}, }, { - .input = {"Jubilife to the Center with timed holds overshooting", test_jubilife_center_held_overshoot}, + .input = {"a short leg to a wall a tile short is a stop, not the wall", test_short_leg_a_tile_short_is_not_arrived}, + .expectation = {}, + }, + { + .input = {"a wall leg that never moved plans from its start", test_never_moved_plans_from_the_start}, + .expectation = {}, + }, + { + .input = {"Jubilife Center with every timed hold overshooting", test_jubilife_center_held_overshoot}, + .expectation = {}, + }, + { + .input = {"blocked from several possible tiles routes around", test_blocked_from_several_tiles}, .expectation = {}, }, { diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp index 6f288e1b38..8239d07065 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RecoveryWalk_Tests.cpp @@ -8,7 +8,18 @@ * physical cause. Run the real story step and route walker on GridSim. */ #include -#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h" #include "Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkResult.h" #include "Simulation/PokemonBDSP_AutoStory_GridSim.h" @@ -21,26 +32,58 @@ namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonBDSP{ +using namespace detail; namespace{ using namespace std::chrono_literals; using Pokemon::Direction; using Pokemon::TilePos; +using Pokemon::GridPose; +using Pokemon::story_arg; + +// A wild battle in the recovery walk itself, on its first input of the +// kind: one the console cannot tell from a battle before that input began +// (WalkOrigin::MAY_PRECEDE_LEG). +enum class RecoveryBattle{ NONE, FIRST_TAP, FIRST_HOLD }; class InterruptingRouteIO : public GridSimRouteIO{ public: InterruptingRouteIO(GridSim& sim, std::vector& notes, - std::vector taps, size_t interrupted_holds) - : GridSimRouteIO(sim, notes, std::move(taps)), m_left(interrupted_holds) + std::vector taps, size_t interrupted_holds, RecoveryBattle recovery_battle = RecoveryBattle::NONE) + : GridSimRouteIO(sim, notes, std::move(taps)), m_notes(notes), m_left(interrupted_holds), m_recovery_battle(recovery_battle) {} virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override{ if (m_left > 0){ m_left--; return {.stop = WalkStop::LIMIT, .walked = 400ms, .wild_battles = 1}; } + if (take_recovery_battle(RecoveryBattle::FIRST_HOLD, walk.label)){ + return {.stop = WalkStop::LIMIT, .walked = 400ms, .wild_battles = 1, .origin = WalkOrigin::MAY_PRECEDE_LEG}; + } return GridSimRouteIO::walk_to_wall(walk); } + virtual WalkResult walk_taps(Direction direction, size_t tiles, const std::string& label) override{ + if (take_recovery_battle(RecoveryBattle::FIRST_TAP, label)){ + WalkResult result = GridSimRouteIO::walk_taps(direction, tiles - 1, label); + result.wild_battles++; + result.moved_chunks++; + result.origin = WalkOrigin::MAY_PRECEDE_LEG; + return result; + } + return GridSimRouteIO::walk_taps(direction, tiles, label); + } private: + bool take_recovery_battle(RecoveryBattle kind, const std::string& label){ + if (m_recovery_battle != kind || label.find("recovery") == std::string::npos){ + return false; + } + m_recovery_battle = RecoveryBattle::NONE; + m_notes.push_back("[Sim] a wild battle on the first input of " + label); + return true; + } + + std::vector& m_notes; size_t m_left; + RecoveryBattle m_recovery_battle; }; // Only walking is needed for this real LEGS step. Unexpected story actions @@ -52,19 +95,22 @@ class RecoveryStepIO : public StoryStepIO{ virtual void fight(const std::string&) override{ throw GridSimFailure{"unexpected trainer"}; } virtual void walk_until_stopped(Direction, size_t, const std::string&) override{ throw GridSimFailure{"unexpected blind hold"}; } virtual bool run_until_map(Direction, Milliseconds, const std::string&, const std::string&) override{ throw GridSimFailure{"unexpected banner walk"}; } - virtual bool run_into_door(Direction, bool, Milliseconds = Milliseconds(12000)) override{ throw GridSimFailure{"unexpected door"}; } + virtual WarpSeen run_into_door(Direction, bool, Milliseconds = Milliseconds(12000), Milliseconds = Milliseconds(0), const std::string& = "") override{ throw GridSimFailure{"unexpected door"}; } virtual std::optional tap_to_banner(Direction, const std::string&, size_t) override{ throw GridSimFailure{"unexpected banner"}; } - virtual void settle(Button, const std::string&, bool) override{ throw GridSimFailure{"unexpected scene"}; } + virtual void settle(Button, const std::string&, bool, const std::string&) override{ throw GridSimFailure{"unexpected scene"}; } private: RouteIO& m_route; }; +// The coal room's counted walk from the corridor rock (15, 9) to below +// Roark (18, 29), as 01.03 walked it before its end was clipped to his +// rock and the wall: nine counted legs, the last one 9 tiles west along +// an open row, which is what these recovery cases need. const Pokemon::StoryStep& mine_step(){ static const Pokemon::StoryStep step = []{ Pokemon::StoryStep step; step.kind = Pokemon::StoryStepKind::LEGS; step.name = "below_roark"; - step.action = "open"; step.args["legs"] = std::vector{ {.direction = Direction::EAST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 2}, @@ -89,6 +135,7 @@ struct RecoveryInput{ SimEncounterPhase phase = SimEncounterPhase::BEFORE_MOVEMENT; WalkOrigin origin = WalkOrigin::CURRENT_LEG; size_t interrupted_holds = 0; + RecoveryBattle recovery_battle = RecoveryBattle::NONE; }; struct RecoveryExpectation{ std::string failure = {}; @@ -117,7 +164,7 @@ class Test_RecoveryWalk : public UnitTest{ .requested_tiles = m_case.input.tiles, .tap = tap, .phase = m_case.input.phase, .origin = m_case.input.origin}); } std::vector notes; - InterruptingRouteIO route(sim, notes, std::move(taps), m_case.input.interrupted_holds); + InterruptingRouteIO route(sim, notes, std::move(taps), m_case.input.interrupted_holds, m_case.input.recovery_battle); RecoveryStepIO io(route); StoryWalkSteps walks(io); walks.begin_attempt("01.03"); @@ -145,6 +192,706 @@ class Test_RecoveryWalk : public UnitTest{ private: RecoveryCase m_case; }; + +// A wild battle on below_roark's open leg east 14, on the input's tap: the +// leg's screen events must place the player a tile or so from where the +// taps left them, not anywhere along the 14 tiles. The taps go on after +// the battle, as the console's do: the player ends at the leg's end, a +// tile short when the battle came before its tap moved. Red until the +// story's taps read their events: the leg kept all 15 of its tiles. +struct PlacedBattleInput{ + std::string name; + size_t tap; + SimEncounterPhase phase; +}; +struct PlacedBattleExpectation{ + size_t tiles_in; // how far along east 14 the taps left the player +}; +struct PlacedBattleCase{ + PlacedBattleInput input; + PlacedBattleExpectation expectation; +}; + +// "4 to 6 tiles in." in a placement line, if any. +std::optional> placed_span(const std::vector& notes){ + for (const std::string& note : notes){ + const size_t line = note.find("battle on the leg:"); + const size_t in = note.find(" tiles in."); + if (line == std::string::npos || in == std::string::npos){ + continue; + } + const size_t to = note.rfind(" to ", in); + const size_t from = note.rfind(' ', to - 1); + return std::pair{std::stoul(note.substr(from + 1, to - from - 1)), std::stoul(note.substr(to + 4, in - to - 4))}; + } + return std::nullopt; +} + +class Test_PlacedLegBattle : public UnitTest{ +public: + explicit Test_PlacedLegBattle(PlacedBattleCase data) + : UnitTest("PokemonBDSP::AutoStory - Recovery walk: a battle on an open leg's taps, placed by its screen events: " + data.input.name) + , m_case(std::move(data)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const StoryWorld* world = story_plan_world("OreburghMine", "OreburghMine"); + GridSim sim({.world = world}, world->to_world("OreburghMine", {15, 9}), Direction::SOUTH, true); + std::vector notes; + InterruptingRouteIO route(sim, notes, {{.label = "below_roark", .direction = Direction::EAST, + .requested_tiles = 14, .tap = m_case.input.tap, .phase = m_case.input.phase}}, 0, RecoveryBattle::NONE); + RecoveryStepIO io(route); + StoryWalkSteps walks(io); + walks.begin_attempt("01.03"); + Pokemon::RunState state{.pose = Pokemon::tile_pose("OreburghMine", {{15, 9}}, Direction::SOUTH), .flags = {}}; + std::string failure; + try{ + failure = walks.legs(state, mine_step()).failure; + }catch (const GridSimFailure& error){ + failure = error.message; + } + for (const std::string& note : notes){ + logger.log(note); + } + const auto end = story_to_local(*world, "OreburghMine", nearest_tile(sim.player().pos)); + if (!failure.empty() || !end || *end != TilePos{18, 29}){ + return "Expected below Roark (18, 29), got " + to_string(sim.player().pos) + ": " + failure; + } + const auto span = placed_span(notes); + const size_t tiles_in = m_case.expectation.tiles_in; + if (!span){ + return "The battle was not placed: the leg kept every one of its tiles."; + } + if (span->first > tiles_in || tiles_in > span->second || span->second - span->first > 2){ + return std::format("Placed {} to {} tiles in; the taps left the player {} in.", span->first, span->second, tiles_in); + } + return true; + } +private: + PlacedBattleCase m_case; +}; + +// The route walker's open legs as lab-B 2026-11-08 11:55 saw one: a leg of +// more than a tile that ends on open ground, not at a wall, goes a tile +// past where it was planned to stop (there, south 5 went 6). The walker is +// not told. A single tap stays tile-exact, and so do the story's own +// counted taps. +class OvershootingRouteIO : public GridSimRouteIO{ +public: + OvershootingRouteIO(GridSim& sim, std::vector& notes, std::vector taps) + : GridSimRouteIO(sim, notes, std::move(taps)), m_sim(sim), m_notes(notes) + {} + virtual WalkResult walk_taps(Direction direction, size_t tiles, const std::string& label) override{ + const WalkResult result = GridSimRouteIO::walk_taps(direction, tiles, label); + if (tiles > 1 && label.ends_with("(open)") && result.stop == WalkStop::LIMIT && sim_can_step(m_sim, direction)){ + m_sim.tap(direction, route_ms_per_tile(direction, MoveSpeed::WALK), false); + m_notes.push_back(std::format("[Sim] {}: overshot a tile {} to {}.", label, direction_name(direction), to_string(m_sim.player().pos))); + } + return result; + } +private: + GridSim& m_sim; + std::vector& m_notes; +}; + +// RecoveryStepIO that also walks to walls, as the story simulation does. +class WallStepIO : public RecoveryStepIO{ +public: + WallStepIO(RouteIO& route, GridSim& sim) : RecoveryStepIO(route), m_sim(sim){} + virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string&) override{ + m_sim.tap(direction, ROUTE_TURN_TAP, false); + m_sim.hold(direction, ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles), SimPace::WALK); + } +private: + GridSim& m_sim; +}; + +const Pokemon::StoryStep& story_step(std::string_view row, std::string_view name){ + for (const Pokemon::StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const Pokemon::StoryStep& step : checkpoint.steps){ + if (checkpoint.id == row && step.name == name){ + return step; + } + } + } + throw GridSimFailure{std::format("no step {} in {}", name, row)}; +} + +// lab-B 2026-11-08 11:55: a wild battle on 01.03's counted taps across +// Roark's room re-planned to the end of the interrupted leg, the open tile +// (15, 16); the re-plan's open run south overshot a row, and the taps after +// ran a row off, under Roark's rocks. With a wild battle on the input's +// tap, the table's to_roarks_corner from (15, 9) must end on his corner +// (20, 28) facing west, and beside_roarks_rock on (20, 29). +struct CornerInput{ + std::string name; + std::vector battle; +}; +struct CornerExpectation{ + std::string failure = {}; +}; +struct CornerCase{ + CornerInput input; + CornerExpectation expectation; +}; +class Test_RoarksCorner : public UnitTest{ +public: + explicit Test_RoarksCorner(CornerCase data) + : UnitTest("PokemonBDSP::AutoStory - Recovery walk: 01.03 to Roark's corner, " + data.input.name), m_case(std::move(data)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const StoryWorld& world = *story_plan_world("OreburghMine", "OreburghMine"); + GridSim sim({.world = &world}, world.to_world("OreburghMine", {15, 9}), Direction::SOUTH, true); + std::vector notes; + OvershootingRouteIO route(sim, notes, m_case.input.battle); + WallStepIO io(route, sim); + StoryWalkSteps walks(io); + walks.begin_attempt("01.03"); + Pokemon::RunState state{.pose = Pokemon::tile_pose("OreburghMine", {{15, 9}}, Direction::SOUTH), .flags = {}}; + std::string failure; + try{ + for (std::string_view name : {"to_roarks_corner", "beside_roarks_rock"}){ + const Pokemon::StoryStep& step = story_step("01.03", name); + failure = walks.legs(state, step).failure; + const auto end = story_to_local(world, "OreburghMine", nearest_tile(sim.player().pos)); + logger.log(std::format("{} ended at {}.", name, to_string(sim.player().pos))); + const Pokemon::TileDeclared& declared = std::get(*step.pose_after); + const std::vector& tiles = declared.tiles; + const bool on_tile = end && std::find(tiles.begin(), tiles.end(), *end) != tiles.end(); + if (failure.empty() && (!on_tile || declared.facing != sim.player().facing)){ + failure = std::format("{} ended at {} facing {}, not on {}.", name, to_string(sim.player().pos), + direction_name(sim.player().facing), Pokemon::to_string(Pokemon::pose_of(*step.pose_after))); + } + if (!failure.empty()){ + break; + } + state.pose = Pokemon::pose_of(*step.pose_after); + } + }catch (const GridSimFailure& error){ + failure = error.message; + } + for (const std::string& note : notes){ + if (note.find("recovery") != std::string::npos || note.find("overshot") != std::string::npos){ + logger.log(note); + } + } + return failure == m_case.expectation.failure ? UnitTestResult(true) + : UnitTestResult("Expected '" + m_case.expectation.failure + "', got '" + failure + "'"); + } +private: + CornerCase m_case; +}; + +const CornerCase CORNER_CASES[] = { + {.input = {.name = "no battle", .battle = {}}, .expectation = {}}, + {.input = {.name = "battle on south 5 tap 3", + .battle = {{.label = "to_roarks_corner", .direction = Direction::SOUTH, .requested_tiles = 5, .tap = 3}}}, .expectation = {}}, + {.input = {.name = "battle on south 5 tap 5", + .battle = {{.label = "to_roarks_corner", .direction = Direction::SOUTH, .requested_tiles = 5, .tap = 5}}}, .expectation = {}}, + {.input = {.name = "battle on east 14 tap 7", + .battle = {{.label = "to_roarks_corner", .direction = Direction::EAST, .requested_tiles = 14, .tap = 7}}}, .expectation = {}}, + {.input = {.name = "battle on south 10 tap 4", + .battle = {{.label = "to_roarks_corner", .direction = Direction::SOUTH, .requested_tiles = 10, .tap = 4}}}, .expectation = {}}, + // On a leg's first tap the battle may have begun before it (MC seed 90037). + {.input = {.name = "battle on east 14 tap 1", + .battle = {{.label = "to_roarks_corner", .direction = Direction::EAST, .requested_tiles = 14, .tap = 1}}}, .expectation = {}}, + {.input = {.name = "battle on south 10 tap 1", + .battle = {{.label = "to_roarks_corner", .direction = Direction::SOUTH, .requested_tiles = 10, .tap = 1}}}, .expectation = {}}, +}; + +// The Oreburgh Mine's warps, from the decomp's warp events (Platinum's +// res/field/maps/*/events.json; BDSP keeps DP's layout): the city's five +// warp tiles lead to the hall's three 2-1-2, the hall's back a column +// each, and the coal room's warp to the hall's column 12. +struct WarpLink{ + std::string from_map; + TilePos from; + std::string to_map; + TilePos to; +}; +const WarpLink MINE_WARPS[] = { + {"OreburghCity", {44, 59}, "OreburghMineB1F", {11, 1}}, + {"OreburghCity", {45, 59}, "OreburghMineB1F", {11, 1}}, + {"OreburghCity", {46, 59}, "OreburghMineB1F", {12, 1}}, + {"OreburghCity", {47, 59}, "OreburghMineB1F", {13, 1}}, + {"OreburghCity", {48, 59}, "OreburghMineB1F", {13, 1}}, + {"OreburghMineB1F", {11, 1}, "OreburghCity", {45, 59}}, + {"OreburghMineB1F", {12, 1}, "OreburghCity", {46, 59}}, + {"OreburghMineB1F", {13, 1}, "OreburghCity", {47, 59}}, + {"OreburghMine", {15, 1}, "OreburghMineB1F", {12, 21}}, +}; + +// Oreburgh's Hiker, who wanders (46..48, 25..27) from (47, 26) on the +// Diamond decomp's map: across column 46, the walk north to the Center. +SimWanderer oreburgh_hiker(uint64_t seed, Milliseconds start){ + const StoryWorld& city = *story_plan_world("OreburghCity", "OreburghCity"); + const TilePos first = story_to_world(city, "OreburghCity", {46, 25}); + const TilePos last = story_to_world(city, "OreburghCity", {48, 27}); + return {.name = "hiker_0", .box = {first.x, first.y, last.x, last.y}, .pos = story_to_world(city, "OreburghCity", {47, 26}), + .seed = seed, .step_interval = 2000ms, .time_offset = start}; +} + +// Puts the player on `map`'s `start` and walks north to a warp, then puts +// them where it lands, with `wanderers` about. Returns where, on which map. +std::pair warp_north(GridSim& sim, const std::string& map, const TilePos& start, std::vector wanderers = {}){ + const StoryWorld& from = *story_plan_world(map, map); + sim.place({.world = &from}, story_to_world(from, map, start), Direction::NORTH); + if (sim.hold(Direction::NORTH, 20000ms, SimPace::WALK).stop != SimStop::WARP){ + throw GridSimFailure{std::format("no warp north of {} on {}", Pokemon::to_string(start), map)}; + } + const std::optional warp = story_to_local(from, map, *sim.player().warped); + for (const WarpLink& link : MINE_WARPS){ + if (link.from_map == map && warp == link.from){ + const StoryWorld& to = *story_plan_world(link.to_map, link.to_map); + sim.place({.world = &to, .trainers = story_trainers(to), .wanderers = std::move(wanderers)}, + story_to_world(to, link.to_map, link.to), Direction::NORTH); + return std::pair{link.to_map, link.to}; + } + } + throw GridSimFailure{std::format("no warp known at {} on {}", warp ? Pokemon::to_string(*warp) : "?", map)}; +} + +// A LEGS step on Oreburgh City, after which the player stands on one of +// `end` facing `facing` (nowhere said if `end` is empty). +Pokemon::StoryStep city_legs(std::string_view name, std::vector legs, std::string_view variant, + std::vector end = {}, Direction facing = Direction::NORTH +){ + Pokemon::StoryStep out; + out.kind = Pokemon::StoryStepKind::LEGS; + out.name = name; + out.action = variant; + out.args["legs"] = std::move(legs); + out.args["fight_wild"] = false; + if (!end.empty()){ + out.pose_after = Pokemon::TileDeclared{.map = "OreburghCity", .tiles = std::move(end), .facing = facing}; + } + return out; +} +// A planned route on Oreburgh City to `target`, facing `facing`. +Pokemon::StoryStep city_route(std::string_view name, TilePos target, Direction facing){ + Pokemon::StoryStep out; + out.kind = Pokemon::StoryStepKind::ROUTE; + out.name = name; + out.action = "town"; + const GridPose gp{.map = "OreburghCity", .tiles = {target}, .facing = facing}; + out.args["target"] = gp; + out.args["fight_wild"] = false; + out.pose_after = Pokemon::TileDeclared{.map = gp.map, .tiles = gp.tiles, .facing = gp.facing}; + return out; +} + +using CitySteps = std::pair>; + +// 01.03 out of the mine as the table had it before lab-B 2026-11-08: from +// the city's (45, 59) north against the mine's sign (45, 56), a route to +// below the Center's door (47, 21), a tap south, the walls east and north +// of (48, 22), and a tap west. +CitySteps old_steps_out_of_the_mine(){ + Pokemon::StoryStep route = city_route("below_the_centers_door_again", {47, 21}, Direction::NORTH); + route.pose_after.reset(); + return {Pokemon::tile_pose("OreburghCity", {TilePos{45, 59}, TilePos{45, 58}}, Direction::NORTH), { + city_legs("up_to_the_mines_sign", {{.direction = Direction::NORTH, .tiles = 3}}, "to_wall", {{45, 57}}), + route, + city_legs("south_of_the_centers_door", {{.direction = Direction::SOUTH, .tiles = 1}}, ""), + city_legs("against_the_walls_east_of_the_door", {{.direction = Direction::EAST, .tiles = 3}, {.direction = Direction::NORTH, .tiles = 1}}, + "to_wall", {{48, 21}}), + city_legs("below_the_centers_door_lined_up", {{.direction = Direction::WEST, .tiles = 1}}, "", {{47, 21}}), + }}; +} +// 01.03 out of the mine as the table had it at lab-B 2026-11-08 13:50: pin +// the column against the walls east of the mine, route to the street west +// of the door, (44, 22), and line up against the walls east and north of +// (48, 22). Its route goes round the Hiker's rows west of column 46. +CitySteps previous_steps_out_of_the_mine(){ + return {Pokemon::tile_pose("OreburghCity", {TilePos{46, 59}, TilePos{45, 59}, TilePos{47, 59}, TilePos{46, 58}, TilePos{45, 58}, TilePos{47, 58}}, + Direction::NORTH), { + city_legs("off_the_mines_warp_tiles", {{.direction = Direction::NORTH, .tiles = 1}}, ""), + city_legs("east_of_the_mine", {{.direction = Direction::EAST, .tiles = 4}}, "to_wall", {{48, 58}, {49, 57}}, Direction::EAST), + city_legs("north_of_row_58", {{.direction = Direction::NORTH, .tiles = 1}}, ""), + city_legs("against_the_walls_east_of_the_mine", {{.direction = Direction::EAST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 1}}, + "to_wall", {{49, 57}}, Direction::SOUTH), + city_route("west_of_the_centers_door", {44, 22}, Direction::WEST), + city_legs("against_the_walls_east_of_the_door", {{.direction = Direction::EAST, .tiles = 4}, {.direction = Direction::NORTH, .tiles = 1}}, + "to_wall", {{48, 21}}), + city_legs("below_the_centers_door_lined_up", {{.direction = Direction::WEST, .tiles = 1}}, "", {{47, 21}}), + }}; +} +// The table's 01.03 steps out of the mine, from where it has us on the +// city to below the Center's door. +CitySteps table_steps_out_of_the_mine(){ + std::vector steps; + for (const Pokemon::StoryCheckpoint& checkpoint : story_checkpoints()){ + bool on = false; + for (const Pokemon::StoryStep& step : checkpoint.steps){ + on = checkpoint.id == "01.03" && step.name != "heal_oreburgh" && (on || step.name == "out_of_the_mine"); + if (on && step.name != "out_of_the_mine"){ + steps.push_back(step); + } + } + } + return {Pokemon::pose_of(*story_step("01.03", "out_of_the_mine").pose_after), steps}; +} + +// OvershootingRouteIO that keeps where each walk and tap left the player. +class TracingRouteIO : public OvershootingRouteIO{ +public: + TracingRouteIO(GridSim& sim, std::vector& notes) + : OvershootingRouteIO(sim, notes, {}), m_sim(sim) + {} + virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override{ + const WalkResult result = OvershootingRouteIO::walk_to_wall(walk); + m_trail.push_back(m_sim.player().pos); + return result; + } + virtual WalkResult walk_taps(Direction direction, size_t tiles, const std::string& label) override{ + const WalkResult result = OvershootingRouteIO::walk_taps(direction, tiles, label); + m_trail.push_back(m_sim.player().pos); + return result; + } + void mark(){ + m_trail.push_back(m_sim.player().pos); + } + const std::vector& trail() const{ + return m_trail; + } +private: + GridSim& m_sim; + std::vector m_trail; +}; + +// How `steps` went: why they did not end on (47, 21) with the Center's +// door north ("" if they did), and whether the walk stood west of column +// 46 on the way. +struct CenterWalk{ + std::string miss; + bool west_of_column_46 = false; +}; +bool went_west_of_column_46(const StoryWorld& city, const std::vector& trail){ + return std::any_of(trail.begin(), trail.end(), [&city](const SimPos& pos){ + const std::optional tile = story_to_local(city, "OreburghCity", nearest_tile(pos)); + return tile && tile->x < 46; + }); +} +std::string walk_city_steps(StoryWalkSteps& walks, TracingRouteIO& route, const CitySteps& steps, Logger& logger){ + Pokemon::RunState state{.pose = steps.first, .flags = {}}; + std::string ends; + for (const Pokemon::StoryStep& step : steps.second){ + const Pokemon::Outcome outcome = step.kind == Pokemon::StoryStepKind::ROUTE ? walks.route(state, step) : walks.legs(state, step); + route.mark(); + ends += std::format(" {} {}", step.name, to_string(route.trail().back())); + if (!outcome.succeeded()){ + return step.name + ": " + Pokemon::to_string(outcome); + } + state.pose = step.pose_after ? Pokemon::pose_of(*step.pose_after) : outcome.pose ? *outcome.pose : state.pose; + } + logger.log(" " + ends); + return ""; +} +// Walks `steps` on `sim` from where the player stands, the table having +// them on `steps.first`, with open legs overshooting. +CenterWalk center_walk(GridSim& sim, const CitySteps& steps, Logger& logger){ + std::vector notes; + TracingRouteIO route(sim, notes); + WallStepIO io(route, sim); + StoryWalkSteps walks(io); + walks.begin_attempt("01.03"); + CenterWalk out; + try{ + out.miss = walk_city_steps(walks, route, steps, logger); + }catch (const GridSimFailure& error){ + out.miss = error.message; + }catch (const Exception& error){ + out.miss = std::string(error.name()) + ": " + error.message(); + } + for (const std::string& note : notes){ + if (note.find("waiting") != std::string::npos || note.find("tiles to the wall") != std::string::npos){ + logger.log(" " + note); + } + } + const StoryWorld& city = sim.world(); + out.west_of_column_46 = went_west_of_column_46(city, route.trail()); + if (!out.miss.empty()){ + return out; + } + if (story_to_local(city, "OreburghCity", nearest_tile(sim.player().pos)) != TilePos{47, 21} || !on_grid(sim.player().pos)){ + out.miss = std::format("ended at {}, not on (47, 21).", to_string(sim.player().pos)); + }else if (sim.hold(Direction::NORTH, 3000ms, SimPace::RUN).stop != SimStop::WARP){ + out.miss = "no door north of (47, 21)."; + } + return out; +} + +// lab-B 2026-11-08 (09:46, 10:39, 12:03): out of the mine, the walk north +// to the mine's sign never stopped on it, and the route after went up the +// wrong column; at 12:04 it ran through the Center's door. The coal room's +// warp lands us on the hall's column 12, which comes out on the city's +// (46, 59), east of the sign. At 13:50 the steps that pinned the column +// east of the mine went astray too: the hold east from (48, 57) moved 0 +// where the map has (49, 57) open. The table now runs straight north up +// column 46 to the wall at (46, 20), waiting for Oreburgh's Hiker when he +// wanders into the column, and taps east below the door. From the hall's +// column 12, with or without a tile past the fade, and with the Hiker at +// any seed and start time, its steps must end below the door, (47, 21), +// and walk in, never west of column 46. From the hall's other columns the +// count north is far off the map's and the walk must fail. +enum class MineExitSteps{ OLD, PREVIOUS, TABLE }; +struct MineExitInput{ + std::string name; + int hall_column = 12; + bool past_the_fade = false; + MineExitSteps steps = MineExitSteps::TABLE; + // Every seed and start time of the Hiker's, not just the first. + bool every_hiker = false; +}; +struct MineExitExpectation{ + bool below_the_door = true; + std::optional west_of_column_46 = false; +}; +struct MineExitCase{ + MineExitInput input; + MineExitExpectation expectation; +}; +class Test_MineExit : public UnitTest{ +public: + explicit Test_MineExit(MineExitCase data) + : UnitTest("PokemonBDSP::AutoStory - Recovery walk: 01.03 out of the mine on the decomp's warps, " + data.input.name) + , m_case(std::move(data)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const std::vector seeds = m_case.input.every_hiker ? std::vector{0, 1, 2, 7, 42, 100, 999, 1337} : std::vector{0}; + const std::vector starts = m_case.input.every_hiker + ? std::vector{0ms, 500ms, 1200ms, 2000ms, 3500ms, 5000ms} : std::vector{0ms}; + for (uint64_t seed : seeds){ + for (Milliseconds start : starts){ + const std::string failure = run_once(oreburgh_hiker(seed, start), logger); + if (!failure.empty()){ + return std::format("the Hiker's seed {}, {} ms in: {}", seed, start.count(), failure); + } + } + } + return true; + } +private: + CitySteps steps() const{ + switch (m_case.input.steps){ + case MineExitSteps::OLD: + return old_steps_out_of_the_mine(); + case MineExitSteps::PREVIOUS: + return previous_steps_out_of_the_mine(); + case MineExitSteps::TABLE: + break; + } + return table_steps_out_of_the_mine(); + } + std::string run_once(const SimWanderer& hiker, Logger& logger) const{ + CenterWalk walk; + try{ + const StoryWorld& room = *story_plan_world("OreburghMine", "OreburghMine"); + GridSim sim({.world = &room}, story_to_world(room, "OreburghMine", {15, 2}), Direction::NORTH, true); + const TilePos hall = warp_north(sim, "OreburghMine", {15, 2}).second; + const TilePos out = warp_north(sim, "OreburghMineB1F", {m_case.input.hall_column, hall.y}, {hiker}).second; + if (m_case.input.past_the_fade){ + sim.tap(Direction::NORTH, route_ms_per_tile(Direction::NORTH, MoveSpeed::WALK), false); + } + walk = center_walk(sim, steps(), logger); + logger.log(std::format("Coal room to the hall's {}, up column {} to the city's {}: {}{}", Pokemon::to_string(hall), + m_case.input.hall_column, Pokemon::to_string(out), walk.miss.empty() ? "below the door" : walk.miss, + walk.west_of_column_46 ? ", west of column 46 on the way" : "")); + }catch (const GridSimFailure& error){ + walk.miss = error.message; + } + if (walk.miss.empty() != m_case.expectation.below_the_door){ + return walk.miss.empty() ? "Reached below the door: the test no longer shows the console's failure." : walk.miss; + } + if (m_case.expectation.west_of_column_46 && walk.west_of_column_46 != *m_case.expectation.west_of_column_46){ + return walk.west_of_column_46 ? "The walk went west of column 46." : "The walk stayed on column 46 and east."; + } + return ""; + } + + MineExitCase m_case; +}; + +const MineExitCase MINE_EXIT_CASES[] = { + {.input = {.name = "old steps from the hall's column 12", .hall_column = 12, .steps = MineExitSteps::OLD}, + .expectation = {.below_the_door = false, .west_of_column_46 = std::nullopt}}, + {.input = {.name = "old steps from the hall's column 13", .hall_column = 13, .steps = MineExitSteps::OLD}, + .expectation = {.below_the_door = false, .west_of_column_46 = std::nullopt}}, + // The steps of 13:50 reach the door on the map, round the Hiker's rows + // to the west. + {.input = {.name = "13:50's steps from the hall's column 12", .hall_column = 12, .steps = MineExitSteps::PREVIOUS}, + .expectation = {.below_the_door = true, .west_of_column_46 = true}}, + {.input = {.name = "from the hall's column 12", .hall_column = 12}, .expectation = {}}, + {.input = {.name = "from the hall's column 12, a tile past the fade", .hall_column = 12, .past_the_fade = true}, .expectation = {}}, + {.input = {.name = "from the hall's column 12, the Hiker at every seed and start time", .hall_column = 12, .every_hiker = true}, + .expectation = {}}, + {.input = {.name = "from the hall's column 12, a tile past the fade, the Hiker at every seed and start time", .hall_column = 12, + .past_the_fade = true, .every_hiker = true}, .expectation = {}}, + // Off column 46 the run north is not the map's 37 or 38 tiles: up + // column 45 it stops at the mine's sign, up column 47 it goes through + // the Center's door. + {.input = {.name = "from the hall's column 11", .hall_column = 11}, + .expectation = {.below_the_door = false, .west_of_column_46 = std::nullopt}}, + {.input = {.name = "from the hall's column 13", .hall_column = 13}, + .expectation = {.below_the_door = false, .west_of_column_46 = std::nullopt}}, +}; + +// A wild battle after `tiles` tiles of the first walk north longer than +// that, tapped or run until a banner (none if 0); the walk goes on after +// it, as walk_tiles_dpad() and walk_until_dpad() go on after running. +class ColumnBattle{ +public: + ColumnBattle(std::vector& notes, size_t tiles) : m_notes(notes), m_tiles(tiles){} + size_t tiles() const{ return m_tiles; } + // Whether the battle comes after `tile` tiles of a walk of `tiles` `direction`. + bool after(Direction direction, size_t tiles, size_t tile){ + if (m_taken || m_tiles == 0 || direction != Direction::NORTH || tiles <= m_tiles || tile != m_tiles){ + return false; + } + m_taken = true; + m_notes.push_back(std::format("[Sim] a wild battle after {} tiles north.", tile)); + return true; + } +private: + std::vector& m_notes; + size_t m_tiles; + bool m_taken = false; +}; + +class ColumnBattleRouteIO : public GridSimRouteIO{ +public: + ColumnBattleRouteIO(GridSim& sim, std::vector& notes, ColumnBattle& battle) + : GridSimRouteIO(sim, notes), m_battle(battle) + {} + virtual WalkResult walk_taps(Direction direction, size_t tiles, const std::string& label) override{ + if (!m_battle.after(direction, tiles, m_battle.tiles())){ + return GridSimRouteIO::walk_taps(direction, tiles, label); + } + WalkResult result = GridSimRouteIO::walk_taps(direction, m_battle.tiles(), label); + const WalkResult rest = GridSimRouteIO::walk_taps(direction, tiles - m_battle.tiles(), label); + result.stop = rest.stop; + result.walked += rest.walked; + result.moved_chunks += rest.moved_chunks; + result.wild_battles++; + return result; + } +private: + ColumnBattle& m_battle; +}; + +// RecoveryStepIO that also runs until a map's banner: it reads +// SIM_BANNER_TILES into the map, as the story simulation's does, or where +// something stops the run on it. +class BannerStepIO : public RecoveryStepIO{ +public: + static constexpr size_t SIM_BANNER_TILES = 3; + BannerStepIO(RouteIO& route, GridSim& sim, ColumnBattle& battle) : RecoveryStepIO(route), m_sim(sim), m_battle(battle){} + virtual bool run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&) override{ + size_t on = 0; + size_t tiles = 0; + for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ + m_battle.after(direction, SIZE_MAX, tiles); + const SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + tiles++; + const bool stopped = move.distance == 0 || move.stop != SimStop::DONE; + on = story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)) ? on + 1 : 0; + if (on > 0 && (on >= SIM_BANNER_TILES || stopped)){ + return true; + } + if (stopped){ + return false; + } + } + return false; + } +private: + GridSim& m_sim; + ColumnBattle& m_battle; +}; + +// 01.10's last stretch, north up column 11 from (11, 12) through the grass +// on (11, 5..11) into Floaroma (lab-B 2026-11-08 18:17:53): a wild battle +// on "north 7 (open)" to (11, 5) left (11, 5..12), and no plan came, for +// column 11 has no wall to the north and no other wall brings those tiles +// together. The table's steps after line 6, with a wild battle the input's +// tiles up, must end in Floaroma where the row's last walk says. +struct LineSevenInput{ + std::string name; + size_t battle_after_tiles = 0; +}; +struct LineSevenExpectation{ +}; +struct LineSevenCase{ + LineSevenInput input; + LineSevenExpectation expectation; +}; + +UnitTestResult test_line_7_battle_reaches_floaroma(Logger& logger, const LineSevenInput& input){ + const StoryWorld& world = *story_plan_world("Route204North", "FloaromaTown"); + GridSim sim({.world = &world}, story_to_world(world, "Route204North", {11, 12}), Direction::WEST, true); + std::vector notes; + ColumnBattle battle(notes, input.battle_after_tiles); + ColumnBattleRouteIO route(sim, notes, battle); + BannerStepIO io(route, sim, battle); + StoryWalkSteps walks(io); + walks.begin_attempt("01.10"); + Pokemon::RunState state{.pose = Pokemon::tile_pose("Route204North", {{11, 12}}, Direction::WEST), .flags = {}}; + std::string failure; + std::optional last; + try{ + bool after_line_6 = false; + for (const Pokemon::StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const Pokemon::StoryStep& step : checkpoint.id == "01.10" ? checkpoint.steps : std::vector{}){ + const bool walks_here = after_line_6 && (step.kind == Pokemon::StoryStepKind::ROUTE || step.kind == Pokemon::StoryStepKind::LEGS); + after_line_6 |= step.name == "line_6"; + if (!walks_here || !failure.empty()){ + continue; + } + const Pokemon::Outcome outcome = step.kind == Pokemon::StoryStepKind::ROUTE ? walks.route(state, step) : walks.legs(state, step); + failure = outcome.failure; + last = step.pose_after ? Pokemon::pose_of(*step.pose_after) + : step.args.contains("target") ? Pokemon::pose_of(story_arg(step.args, "target")) : last; + state.pose = outcome.pose ? *outcome.pose : *last; + logger.log(std::format("01.10 {} ended at {}.", step.name, to_string(sim.player().pos))); + } + } + }catch (const GridSimFailure& error){ + failure = error.message; + } + for (const std::string& note : notes){ + logger.log(note); + } + if (!failure.empty() || !last){ + return "01.10 after line 6: " + (failure.empty() ? std::string("no walk") : failure); + } + const std::vector tiles = Pokemon::tiles_of(*last); + const auto end = story_to_local(world, last->map, nearest_tile(sim.player().pos)); + if (!end || std::find(tiles.begin(), tiles.end(), *end) == tiles.end()){ + return std::format("01.10 ended at {}, not on {}.", to_string(sim.player().pos), Pokemon::to_string(*last)); + } + if (last->map != "FloaromaTown"){ + return "01.10 ends on " + last->map + ", not in Floaroma."; + } + return true; +} + +class Test_LineSevenBattle : public UnitTest{ +public: + explicit Test_LineSevenBattle(LineSevenCase data) + : UnitTest("PokemonBDSP::AutoStory - Recovery walk: 01.10 into Floaroma, " + data.input.name), m_case(std::move(data)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + return test_line_7_battle_reaches_floaroma(logger, m_case.input); + } +private: + LineSevenCase m_case; +}; + +const LineSevenCase LINE_SEVEN_CASES[] = { + {.input = {.name = "no battle", .battle_after_tiles = 0}, .expectation = {}}, + {.input = {.name = "a wild battle 3 tiles up (lab-B, 2026-11-08)", .battle_after_tiles = 3}, .expectation = {}}, + {.input = {.name = "a wild battle 6 tiles up", .battle_after_tiles = 6}, .expectation = {}}, +}; + } // namespace void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ @@ -156,12 +903,35 @@ void add_tests_AutoStory_RecoveryWalk(UnitTestDatabase& database){ {.input = {.name = "last west leg recovers position and facing", .taps = {9}, .direction = Direction::WEST, .tiles = 9}, .expectation = {.failure = ""}}, {.input = {.name = "repeat the interrupted recovery hold", .taps = {5}, .interrupted_holds = 1}, .expectation = {.failure = ""}}, {.input = {.name = "recovery hold budget exhausted", .taps = {5}, .interrupted_holds = 10}, .expectation = {.failure = "recovery budget"}}, - {.input = {.name = "first input may belong to previous leg", .taps = {1}}, .expectation = {.failure = "encounter_origin_unknown"}}, - {.input = {.name = "late encounter origin unknown", .taps = {5}, .origin = WalkOrigin::MAY_PRECEDE_LEG}, .expectation = {.failure = "encounter_origin_unknown"}}, + // A second battle, in the recovery walk, on its first tap or hold + // (MC seeds 717266 and 331438): the walk plans again to the step's end. + {.input = {.name = "battle on the recovery's first tap", .taps = {5}, .recovery_battle = RecoveryBattle::FIRST_TAP}, .expectation = {.failure = ""}}, + {.input = {.name = "battle on the recovery's first hold", .taps = {5}, .recovery_battle = RecoveryBattle::FIRST_HOLD}, .expectation = {.failure = ""}}, + // A battle that may have begun before the leg: localized from the + // leg's tiles all the same, and re-planned to the step's end. + {.input = {.name = "first input may belong to previous leg", .taps = {1}}, .expectation = {.failure = ""}}, + {.input = {.name = "late encounter origin unknown", .taps = {5}, .origin = WalkOrigin::MAY_PRECEDE_LEG}, .expectation = {.failure = ""}}, }; for (const RecoveryCase& scenario : CASES){ database.add(scenario); } + const PlacedBattleCase PLACED_CASES[] = { + {.input = {.name = "tap 3", .tap = 3, .phase = SimEncounterPhase::AFTER_MOVEMENT}, .expectation = {.tiles_in = 14}}, + {.input = {.name = "tap 7, before it moved", .tap = 7, .phase = SimEncounterPhase::BEFORE_MOVEMENT}, .expectation = {.tiles_in = 13}}, + {.input = {.name = "the last tap", .tap = 14, .phase = SimEncounterPhase::AFTER_MOVEMENT}, .expectation = {.tiles_in = 14}}, + }; + for (const PlacedBattleCase& scenario : PLACED_CASES){ + database.add(scenario); + } + for (const CornerCase& scenario : CORNER_CASES){ + database.add(scenario); + } + for (const MineExitCase& scenario : MINE_EXIT_CASES){ + database.add(scenario); + } + for (const LineSevenCase& scenario : LINE_SEVEN_CASES){ + database.add(scenario); + } } } // namespace PokemonBDSP } // namespace NintendoSwitch diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.cpp new file mode 100644 index 0000000000..2c8966a1fb --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.cpp @@ -0,0 +1,64 @@ +/* BDSP AutoStory Resources + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonBDSP_AutoStory_Resources.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +const std::string_view PATHS[] = { + // Actions/PokemonBDSP_AutoStory_Settings.cpp: each row's label and + // target value, as SETTINGS there names them. + "PokemonBDSP/Autostory/Options/textspeed_label.png", + "PokemonBDSP/Autostory/Options/textspeed_value.png", + "PokemonBDSP/Autostory/Options/changewindow_label.png", + "PokemonBDSP/Autostory/Options/changewindow_value.png", + "PokemonBDSP/Autostory/Options/battleeffects_label.png", + "PokemonBDSP/Autostory/Options/battleeffects_value.png", + "PokemonBDSP/Autostory/Options/battlestyle_label.png", + "PokemonBDSP/Autostory/Options/battlestyle_value.png", + "PokemonBDSP/Autostory/Options/sendtoboxes_label.png", + "PokemonBDSP/Autostory/Options/sendtoboxes_value.png", + "PokemonBDSP/Autostory/Options/givenicknames_label.png", + "PokemonBDSP/Autostory/Options/givenicknames_value.png", + "PokemonBDSP/Autostory/Options/gyroscope_label.png", + "PokemonBDSP/Autostory/Options/gyroscope_value.png", + "PokemonBDSP/Autostory/Options/autosave_label.png", + "PokemonBDSP/Autostory/Options/autosave_value.png", + "PokemonBDSP/Autostory/Options/shownicknames_label.png", + "PokemonBDSP/Autostory/Options/shownicknames_value.png", + "PokemonBDSP/Autostory/Options/backgroundmusic_label.png", + "PokemonBDSP/Autostory/Options/backgroundmusic_value.png", + "PokemonBDSP/Autostory/Options/soundeffects_label.png", + "PokemonBDSP/Autostory/Options/soundeffects_value.png", + + // Actions/PokemonBDSP_AutoStory_Events_Lake.cpp + "PokemonBDSP/StarterBriefcase.png", + // Inference/PokemonBDSP_SelectionArrow.cpp and + // PokemonBDSP_NameListDetector.cpp + "PokemonBDSP/SelectionArrow.png", + // Actions/PokemonBDSP_AutoStory_BattleMoves.cpp: the move names in + // every language. + "PokemonSV/PokemonMovesOCR.json", +}; + +} // namespace + + +const std::vector& autostory_resource_paths(){ + static const std::vector LIST(std::begin(PATHS), std::end(PATHS)); + return LIST; +} + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.h new file mode 100644 index 0000000000..ebcd4bf09c --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.h @@ -0,0 +1,35 @@ +/* BDSP AutoStory Resources + * + * From: https://github.com/PokemonAutomation/ + * + * The files under the Resources folder that AutoStory, and the readers + * and detectors it calls, load while a program runs. A deployment whose + * Packages lack one of them stops mid-story with a FileException, so the + * test checks every one of them exists. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_Resources_H +#define PokemonAutomation_PokemonBDSP_AutoStory_Resources_H + +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Paths relative to RESOURCE_PATH(). When a reader or detector that +// AutoStory uses starts loading a new file, add it here. +const std::vector& autostory_resource_paths(); + +// Adds the test that every path above is under RESOURCE_PATH(). +void add_tests_AutoStoryResources(UnitTestDatabase& database); + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources_Tests.cpp new file mode 100644 index 0000000000..77b0f34e42 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources_Tests.cpp @@ -0,0 +1,78 @@ +/* BDSP AutoStory Resources Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Checks that every file in autostory_resource_paths() is in the + * Resources folder the program runs with. + * + */ + +#include +#include +#include +#include "Common/Cpp/Filesystem/Filesystem.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/GlobalAutoPaths.h" +#include "PokemonBDSP_AutoStory_Resources.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +namespace{ + +struct ResourcesInput{ + std::string name; + const std::vector& (*paths)(); +}; +struct ResourcesExpectation{ + // The paths that may be missing; none, for a list a program loads. + size_t missing; +}; +struct ResourcesCase{ + ResourcesInput input; + ResourcesExpectation expectation; +}; + +class Test_AutoStoryResources : public UnitTest{ +public: + explicit Test_AutoStoryResources(ResourcesCase test_case) + : UnitTest(std::string("PokemonBDSP::AutoStoryResources - ") + test_case.input.name) + , m_case(test_case) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + std::string missing; + size_t count = 0; + for (std::string_view path : m_case.input.paths()){ + if (!Filesystem::exists(Filesystem::Path(RESOURCE_PATH() + std::string(path)))){ + missing += "\n " + std::string(path); + count++; + } + } + if (count == m_case.expectation.missing){ + return true; + } + return std::to_string(count) + " missing under " + RESOURCE_PATH() + ":" + missing; + } + +private: + ResourcesCase m_case; +}; + +const ResourcesCase RESOURCES_CASES[] = { + {.input = {"every file AutoStory loads is in Resources", autostory_resource_paths}, .expectation = {.missing = 0}}, +}; + +} // namespace + + +void add_tests_AutoStoryResources(UnitTestDatabase& database){ + for (const ResourcesCase& item : RESOURCES_CASES){ + database.add(item); + } +} + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.cpp new file mode 100644 index 0000000000..0c9fa562f8 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.cpp @@ -0,0 +1,647 @@ +/* BDSP AutoStory - Route Bench Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Scores the plan of every ROUTE step of the story table with the shared + * route scorer (Pokemon_RouteScorer.h), and the routes the user asked for + * on three of them, and checks that no route scores worse than + * Data/route_bench.golden.txt. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Filesystem/FileIO.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/Navigation/Pokemon_RouteScorer.h" +#include "Data/PokemonBDSP_AutoStory_RobustRoute.h" +#include "Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "Data/PokemonBDSP_AutoStory_WallRecovery.h" +#include "Utils/PokemonBDSP_AutoStory_RouteChoice.h" +#include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP_AutoStory_TableRoutes.h" +#include "PokemonBDSP_AutoStory_RouteBench_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +namespace{ + +using Pokemon::Direction; +using Pokemon::RouteScore; +using Pokemon::ScoredLeg; +using Pokemon::ScoredLegKind; +using Pokemon::TilePos; + +// One route to score: the plan the program walks today, or one hand-written. +struct BenchCase{ + std::string name; + const StoryWorld* world; + std::vector from; + std::vector goal; + std::vector triggers; // a scene starts here and stops the player + std::vector legs; + bool run = false; + std::optional costs; + bool planned = true; // false: no plan exists + // A human's route for this case (the user's, or a recorded run's), the + // bar the plan is measured against; none: the stand-in. + std::optional> human = std::nullopt; + std::string human_source = ""; +}; + +Pokemon::ScoreMap bench_map(const BenchCase& bench){ + return route_score_map(*bench.world, bench.triggers); +} + +Pokemon::RoutePaces bench_paces(){ + return route_score_paces(); +} + +MoveSpeed bench_speed(bool run){ + return run ? MoveSpeed::RUN : MoveSpeed::WALK; +} + +// The legs as RouteWalker walks them (route_scored_legs()). +std::vector walked_legs(const std::vector& legs, bool run){ + return route_scored_legs(legs, bench_speed(run)); +} + +RouteScore score_case(const BenchCase& bench){ + if (!bench.planned){ + return {.verdict = Pokemon::RouteVerdict::FAIL, .why = "no plan"}; + } + const std::vector& targets = bench.goal; + const std::function goal = [&targets](const TilePos& pos){ + return std::find(targets.begin(), targets.end(), pos) != targets.end(); + }; + const Pokemon::RouteReplanner replan = [&](const std::vector& from) -> std::optional>{ + const std::optional> legs = + plan_recovered_route(*bench.world, from, goal, replan_costs(bench.costs.value_or(RobustPlanCosts()))); + if (!legs){ + return std::nullopt; + } + return walked_legs(*legs, bench.run); + }; + return Pokemon::score_route(bench_map(bench), bench.from, goal, bench.legs, bench_paces(), route_interrupt_model(), replan); +} + + +// The table's ROUTE steps from a known place, as the program plans them. +std::vector table_cases(){ + std::vector cases; + std::map seen; + for (const TableRoute& route : table_routes()){ + if (route.world == nullptr){ + continue; + } + std::string name = route.row + " " + route.step->name; + const size_t repeat = seen[name]++; + if (repeat > 0){ + name += std::format(" #{}", repeat + 1); + } + const RouteStepPlan plan = plan_table_route(route); + const bool run = route.row > std::string(RUNNING_SHOES_ROW); + const Pokemon::Pose target = Pokemon::pose_of(Pokemon::story_arg(route.step->args, "target")); + const std::vector goal = world_tiles(*route.world, target); + cases.push_back({ + .name = name, .world = route.world, .from = plan.start, + .goal = goal, .triggers = route.step->action == ROUTE_ONTO_TRIGGER ? goal : std::vector{}, + .legs = plan.legs ? walked_legs(*plan.legs, run) : std::vector{}, + .run = run, .costs = story_route_costs(route.step->action), .planned = plan.legs.has_value(), + }); + } + return cases; +} + +size_t case_index(const std::vector& cases, const std::string& name){ + for (size_t i = 0; i < cases.size(); i++){ + if (cases[i].name == name){ + return i; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No table route " + name + "."); +} + +TilePos wall_from(const StoryWorld& world, const TilePos& from, Direction direction){ + return slide_to_wall(world, from, direction).stop; +} + +ScoredLeg taps(Direction direction, size_t tiles){ + return {.direction = direction, .tiles = tiles, .kind = ScoredLegKind::TAPS, .run = true}; +} +ScoredLeg run_to_wall(Direction direction, size_t tiles){ + return {.direction = direction, .tiles = tiles, .kind = ScoredLegKind::TO_WALL, .run = true}; +} +ScoredLeg run_open(Direction direction, size_t tiles){ + return {.direction = direction, .tiles = tiles, .kind = ScoredLegKind::OPEN_HOLD, .run = true}; +} + +// 00.04 "along_route_201_road": the console tapped "west 16 (open)" along +// Route 201's road at 800 ms a tile (lab-B 2026-11-09, step 9 of 00.04). +// The user's route: run west into the funnel of columns 36 to 39, whose +// walls stop a run north on row 9; run north, then west to the wall at +// column 13, a tap east onto column 15 and taps south over the ledge. +BenchCase road_target(const BenchCase& current){ + const StoryWorld& world = *current.world; + const TilePos start = current.from.front(); + const TilePos funnel = story_to_world(world, "Route201", {38, 14}); + const TilePos row9 = wall_from(world, funnel, Direction::NORTH); + const TilePos west = wall_from(world, row9, Direction::WEST); + const TilePos goal = current.goal.front(); + BenchCase target = current; + target.name = "TARGET " + current.name; + target.legs = { + run_open(Direction::WEST, (size_t)(start.x - funnel.x)), + run_to_wall(Direction::NORTH, (size_t)(funnel.y - row9.y)), + run_to_wall(Direction::WEST, (size_t)(row9.x - west.x)), + taps(Direction::EAST, (size_t)(goal.x - west.x)), + taps(Direction::SOUTH, 4), + }; + return target; +} + +// 00.04 "into_twinleaf": the console tapped "south 33 (open)" for 26 s +// (lab-B 2026-11-09, step 10 of 00.04), where the column ends at a wall. +// The user's route: run south to that wall, then tap back north. +BenchCase twinleaf_target(const BenchCase& current){ + const StoryWorld& world = *current.world; + const TilePos start = current.from.front(); + const TilePos wall = wall_from(world, start, Direction::SOUTH); + const TilePos goal = current.goal.front(); + BenchCase target = current; + target.name = "TARGET " + current.name; + target.legs = {run_to_wall(Direction::SOUTH, (size_t)(wall.y - start.y))}; + if (wall.y > goal.y){ + target.legs.push_back(taps(Direction::NORTH, (size_t)(wall.y - goal.y))); + } + return target; +} + +// 00.04 "into_moms_call", to her call on (6, 9) (lab-B 2026-11-09 17:29, +// step 17 of 00.04). The user's route: down to row 9, whose wall row 10 +// does not stop us, so a tap; then run west along row 9 until her call +// stops us on (6, 9). +BenchCase moms_call_target(const BenchCase& current){ + BenchCase target = current; + target.name = "TARGET " + current.name; + target.legs = {taps(Direction::WEST, 1), taps(Direction::SOUTH, 1), run_to_wall(Direction::WEST, 4)}; + return target; +} + +// 00.04 "into_twinleaf", lab-B run 4 (2026-11-09 18:50): "south 33 (open)" +// was blocked after 22 taps, counted at Twinleaf (15, 11), by someone on +// (15, 12). The plan from that one tile, "west 1 (to wall)", walked six +// tiles west, and the walk ended beside the house, east of its door. A +// blocked count can be a tile off (blocked_stop_tiles()): both cases are +// scored from every tile it gives, the blocker on the map. "counted tile" +// is the plan walk_route() made then, from the count alone; the other is +// the plan it makes now. +const StoryWorld& run4_world(const StoryWorld& world){ + static const StoryWorld blocked = [&world]{ + StoryWorld out = world; + out.block(story_to_world(world, "TwinleafTown", {15, 12})); + return out; + }(); + return blocked; +} +void add_run4_cases(std::vector& cases){ + const BenchCase& route = cases[case_index(cases, "00.04 into_twinleaf")]; + const StoryWorld& world = run4_world(*route.world); + const TilePos counted = story_to_world(world, "TwinleafTown", {15, 11}); + const std::vector targets = route.goal; + const auto goal = [targets](const TilePos& pos){ + return std::find(targets.begin(), targets.end(), pos) != targets.end(); + }; + BenchCase recovery = route; + recovery.world = &world; + recovery.from = blocked_stop_tiles(world, {counted}, Direction::SOUTH); + recovery.human = std::nullopt; + const std::optional> old_plan = plan_recovered_route(world, {counted}, goal, *recovery.costs); + BenchCase old_case = recovery; + old_case.name = "00.04 into_twinleaf after run 4's block, planned from the counted tile"; + old_case.legs = old_plan ? walked_legs(*old_plan, recovery.run) : std::vector{}; + old_case.planned = old_plan.has_value(); + cases.push_back(std::move(old_case)); + const std::optional> new_plan = plan_fastest_route({ + .world = world, .from = recovery.from, .goal = goal, .costs = *recovery.costs, .speed = bench_speed(recovery.run), + }); + recovery.name = "00.04 into_twinleaf after run 4's block"; + recovery.legs = new_plan ? walked_legs(*new_plan, recovery.run) : std::vector{}; + recovery.planned = new_plan.has_value(); + cases.push_back(std::move(recovery)); +} + +// A wild battle on a leg to a wall needs no new plan: RouteWalker walks +// to the wall again. On an open leg it loses the count of tiles. 00.04d +// north_to_jubilife's plan with the route's own costs crosses Route 202's +// grass on "west 12 (taps)", and each battle there needs a replan; +// plan_fastest_route() picks the plan with open legs dear in grass +// (replan_costs()), which crosses it on legs to a wall. This scores the +// plan the route's own costs give. +void add_own_costs_case(std::vector& cases){ + BenchCase own = cases[case_index(cases, "00.04d north_to_jubilife")]; + const std::vector targets = own.goal; + const auto goal = [targets](const TilePos& pos){ + return std::find(targets.begin(), targets.end(), pos) != targets.end(); + }; + const std::optional> legs = plan_recovered_route(*own.world, own.from, goal, *own.costs); + own.name += ", planned with the route's own costs (taps in the grass)"; + own.legs = legs ? walked_legs(*legs, own.run) : std::vector{}; + own.planned = legs.has_value(); + cases.push_back(std::move(own)); +} + +// A human run recorded on the console, as legs: replaces a case's stand-in. +struct RecordedHumanRun{ + std::string case_name; + std::vector legs; + std::string source; // the run's log +}; +// The hook for recorded human runs (a log of a human playing, turned into +// legs). None recorded yet. +std::vector recorded_human_runs(){ + return {}; +} + +// Adds `target` after the case it improves, and makes it that case's human +// route: the user described each of them. +void add_target(std::vector& cases, const std::string& name, const std::function& make){ + BenchCase& current = cases[case_index(cases, name)]; + BenchCase target = make(current); + current.human = target.legs; + current.human_source = "user's route"; + target.human = target.legs; + target.human_source = "user's route"; + cases.push_back(std::move(target)); +} + +std::vector bench_cases(){ + std::vector cases = table_cases(); + add_target(cases, "00.04 along_route_201_road", road_target); + add_target(cases, "00.04 into_twinleaf", twinleaf_target); + add_target(cases, "00.04 into_moms_call", moms_call_target); + add_run4_cases(cases); + add_own_costs_case(cases); + for (const RecordedHumanRun& run : recorded_human_runs()){ + BenchCase& bench = cases[case_index(cases, run.case_name)]; + bench.human = run.legs; + bench.human_source = "recorded: " + run.source; + } + return cases; +} + + +constexpr std::string_view BENCH_HEADER = + "BDSP AutoStory: the route bench. Each ROUTE step of the story table, its\r\n" + "plan scored by Pokemon::score_route() as RouteWalker walks it (wall legs\r\n" + "held, at a run after 00.03; open legs tapped), then the user's routes for\r\n" + "three of them (TARGET). Written by the test \"Route bench: no route scores\r\n" + "worse than Data/route_bench.golden.txt\"; rerun it with PA_UPDATE_ROUTE_BENCH=1\r\n" + "to rewrite this file. A route is worse when its verdict leaves PASS, its\r\n" + "expected or worst time grows or one of its human ratios grows past 1.00; a\r\n" + "route that did not pass is better once it passes. No story route may STRAND.\r\n" + "columns: case | expected ms (interruptions by chance) | worst ms (slowest start and\r\n" + "the costliest single interruption) | nominal ms (slowest start, none) | stops (wall\r\n" + "re-localizations) | recoveries (places an interruption may happen) | replans (of those,\r\n" + "the ones the plan cannot absorb) | slower than human (expected / human ms) | riskier\r\n" + "than human ((recoveries + 1) / (human's + 1)) | more backtracking than human ((replans +\r\n" + "tiles walked back + 1) / (human's + 1); a planned stop at a wall is not backtracking) |\r\n" + "the human's ms (the user's route, a recorded run, or the stand-in: the shortest safe\r\n" + "walk run with no stops) | verdict (why). A ratio above 1.5 is flagged \"!\".\r\n" + "\r\n"; + +// The bar a case's plan is measured against: a human's walk of it. +struct HumanBaseline{ + long long ms = 0; + size_t risk_tiles = 0; // places an interruption may happen + size_t backtracking = 0; // replans and tiles walked back (backtracking()) + std::string source; +}; + +// What the bench counts as backtracking: the replans a plan cannot absorb +// (recoveries that need a new plan) and the tiles it walks back. +size_t backtracking(const RouteScore& score, const std::vector& legs){ + return score.replans + Pokemon::tiles_walked_back(legs); +} + +// A step of the stand-in's search: tiles walked, grass and wanderer tiles +// avoided where a way round exists. +struct StandInNode{ + long long cost; + long long ms; + size_t risk; + TilePos pos; + bool operator>(const StandInNode& other) const{ + return cost > other.cost; + } +}; + +using StandInQueue = std::priority_queue, std::greater>; + +bool in_goal(const BenchCase& bench, const TilePos& pos){ + return std::find(bench.goal.begin(), bench.goal.end(), pos) != bench.goal.end(); +} + +// Queues the steps from `node` the stand-in may take: not through a warp +// or a trigger off the goal, and round grass and wanderers where it can. +void push_steps(StandInQueue& open, const BenchCase& bench, const Pokemon::ScoreMap& map, + const Pokemon::RoutePaces& paces, const StandInNode& node +){ + for (Direction direction : Pokemon::ALL_DIRECTIONS){ + const std::optional next = map.step(node.pos, direction); + if (!next){ + continue; + } + const Pokemon::TileRisk risk = map.risk(*next); + if ((risk == Pokemon::TileRisk::WARP || risk == Pokemon::TileRisk::TRIGGER) && !in_goal(bench, *next)){ + continue; + } + const long long tiles = std::abs(next->x - node.pos.x) + std::abs(next->y - node.pos.y); + const bool risky = risk == Pokemon::TileRisk::ENCOUNTER || risk == Pokemon::TileRisk::WANDERER; + open.push({node.cost + tiles + (risky ? 1000 : 0), node.ms + tiles * paces.ms_per_tile(direction, true), + node.risk + (risky ? 1 : 0), *next}); + } +} + +// The shortest safe walk from `start` to the goal, run the whole way. +std::optional stand_in_from(const BenchCase& bench, const TilePos& start){ + const Pokemon::ScoreMap map = bench_map(bench); + const Pokemon::RoutePaces paces = bench_paces(); + StandInQueue open; + std::set> done; + open.push({0, paces.start_ms, 0, start}); + while (!open.empty() && done.size() < 100000){ + const StandInNode node = open.top(); + open.pop(); + if (!done.insert({node.pos.x, node.pos.y}).second){ + continue; + } + if (in_goal(bench, node.pos)){ + return HumanBaseline{node.ms, node.risk, 0, "stand-in"}; // no replans, no tile back + } + push_steps(open, bench, map, paces, node); + } + return std::nullopt; +} + +// For a case with no human route: the shortest safe walk from its slowest +// start, run the whole way, with no stops (as a player who sees the map +// walks). Nothing if no walk reaches the goal. +std::optional stand_in(const BenchCase& bench){ + std::optional slowest; + for (const TilePos& start : bench.from){ + const std::optional walk = stand_in_from(bench, start); + if (walk && (!slowest || slowest->ms < walk->ms)){ + slowest = walk; + } + } + return slowest; +} + +std::optional human_baseline(const BenchCase& bench){ + if (!bench.human){ + return stand_in(bench); + } + BenchCase human = bench; + human.legs = *bench.human; + const RouteScore score = score_case(human); + return HumanBaseline{score.nominal_ms, score.recoveries, backtracking(score, human.legs), bench.human_source}; +} + +// "1.23", with "!" past 1.5: a plan that far behind the human is flagged. +std::string ratio_text(double ratio){ + return std::format("{:.2f}{}", ratio, ratio > 1.5 ? "!" : ""); +} + +// slower | riskier | more backtracking than the human, and the human's time. +std::string human_columns(const BenchCase& bench, const RouteScore& score, const std::optional& human){ + if (!human || human->ms <= 0){ + return "- | - | - | no human baseline"; + } + const double slower = score.expected_ms / (double)human->ms; + const double riskier = (double)(score.recoveries + 1) / (double)(human->risk_tiles + 1); + const double back = (double)(backtracking(score, bench.legs) + 1) / (double)(human->backtracking + 1); + return std::format("{} | {} | {} | {} ms ({})", ratio_text(slower), ratio_text(riskier), ratio_text(back), + human->ms, human->source); +} + +std::string bench_line(const BenchCase& bench, const RouteScore& score){ + std::string line = std::format("{} | {} | {} | {} | {} | {} | {} | {} | {}", bench.name, (long long)(score.expected_ms + 0.5), + score.worst_ms, score.nominal_ms, score.stops, score.recoveries, score.replans, + human_columns(bench, score, human_baseline(bench)), Pokemon::verdict_name(score.verdict)); + return score.why.empty() ? line : line + " (" + score.why + ")"; +} + +// The bench's lines, each case's legs for the log, and the cases that +// strand where they must not. +struct BenchText{ + std::string lines; + std::string legs; + std::string strands; +}; +BenchText bench_text(){ + BenchText out{std::string(BENCH_HEADER), "", ""}; + for (const BenchCase& bench : bench_cases()){ + const RouteScore score = score_case(bench); + out.lines += bench_line(bench, score) + "\r\n"; + if (score.verdict == Pokemon::RouteVerdict::STRAND){ + out.strands += "\n " + bench.name + ": " + score.why; + } + out.legs += bench.name + ":"; + for (const ScoredLeg& leg : bench.legs){ + out.legs += " " + Pokemon::to_string(leg) + ";"; + } + out.legs += "\n"; + } + return out; +} + +// A bench line's columns. +std::vector bench_fields(const std::string& line){ + std::vector fields; + size_t begin = 0; + while (true){ + const size_t end = line.find(" | ", begin); + fields.push_back(line.substr(begin, end == std::string::npos ? std::string::npos : end - begin)); + if (end == std::string::npos){ + return fields; + } + begin = end + 3; + } +} + +// A bench line's expected time and whether it passed. +struct GoldenRow{ + long long expected_ms; + long long worst_ms; + bool pass; + std::vector ratios; // slower, riskier, backtracking; empty without a human +}; +// The rows of a bench text, by case name. +std::map golden_rows(const std::string& text){ + std::map rows; + size_t begin = 0; + bool body = false; // past the header's blank line + while (begin < text.size()){ + const size_t end = std::min(text.find('\n', begin), text.size()); + std::string line = text.substr(begin, end - begin); + begin = end + 1; + std::erase(line, '\r'); + const size_t first = line.find(" | "); + if (!body || first == std::string::npos){ + body = body || line.empty(); + continue; + } + const std::vector fields = bench_fields(line); + GoldenRow row{std::atoll(fields[1].c_str()), std::atoll(fields[2].c_str()), line.find(" | PASS") != std::string::npos, {}}; + for (size_t i = 7; i < 10 && i < fields.size() && fields[i] != "-"; i++){ + row.ratios.push_back(std::atof(fields[i].c_str())); + } + rows[fields[0]] = std::move(row); + } + return rows; +} + +std::string bench_golden_path(){ + // code-health: allow char_pointer -- std::getenv returns a const char pointer + const char* path = std::getenv("PA_ROUTE_BENCH_GOLDEN"); + if (path != nullptr && path[0] != '\0'){ + return path; + } + const std::string self = __FILE__; + const size_t slash = self.find_last_of("/\\"); + return (slash == std::string::npos ? std::string() : self.substr(0, slash + 1)) + "Data/route_bench.golden.txt"; +} + +// Whether any of `now`'s human ratios grew from `was`'s, past the human's +// own (1.0): a plan may come up to the human's bar. +bool ratio_grew(const GoldenRow& was, const GoldenRow& now){ + for (size_t i = 0; i < std::min(was.ratios.size(), now.ratios.size()); i++){ + if (now.ratios[i] > was.ratios[i] + 0.005 && now.ratios[i] > 1.005){ + return true; + } + } + return false; +} + +// Each route of `now` that scores worse than in `golden`. +std::string worse_routes(const std::string& golden, const std::string& now){ + const std::map before = golden_rows(golden); + std::string out; + for (const auto& [name, row] : golden_rows(now)){ + const auto was = before.find(name); + // A route that did not pass has no times to keep: any pass is better. + if (was == before.end() || (!was->second.pass && row.pass)){ + continue; + } + if ((was->second.pass && !row.pass) || row.expected_ms > was->second.expected_ms || + row.worst_ms > was->second.worst_ms || ratio_grew(was->second, row) + ){ + out += std::format("\n {}: {} ms (worst {}){} -> {} ms (worst {}){}", name, + was->second.expected_ms, was->second.worst_ms, was->second.pass ? "" : " (not PASS)", + row.expected_ms, row.worst_ms, row.pass ? "" : " (not PASS)"); + } + } + return out; +} + +UnitTestResult test_route_bench(Logger& logger){ + const std::string path = bench_golden_path(); + const BenchText text = bench_text(); + const std::string& now = text.lines; + logger.log("Route bench:\n" + now); + logger.log("Route bench legs:\n" + text.legs); + // code-health: allow char_pointer -- std::getenv returns a const char pointer + const char* update = std::getenv("PA_UPDATE_ROUTE_BENCH"); + if (update != nullptr && update[0] != '\0' && update[0] != '0'){ + FileIO file; + if (!file.open(path, FileMode::WRITE | FileMode::BINARY) || file.write(now) != now.size()){ + return "Could not write " + path + "."; + } + logger.log("Wrote " + path + "."); + return true; + } + if (!text.strands.empty()){ + return "Routes strand:" + text.strands; + } + std::string golden; + if (!file_to_string(path, golden)){ + return "Could not read " + path + " (set PA_ROUTE_BENCH_GOLDEN to its path)."; + } + const std::string worse = worse_routes(golden, now); + if (worse.empty()){ + return true; + } + return "Routes score worse than " + path + " (rerun with PA_UPDATE_ROUTE_BENCH=1 if meant):" + worse; +} + + +struct RouteBenchInput{ + std::string name; + UnitTestResult (*test)(Logger&); +}; + +struct RouteBenchExpectation{ + std::string_view description; +}; + +struct RouteBenchCase{ + RouteBenchInput input; + RouteBenchExpectation expectation; +}; + +class Test_AutoStoryRouteBench : public UnitTest{ +public: + explicit Test_AutoStoryRouteBench(RouteBenchCase scenario) + : UnitTest("PokemonBDSP::AutoStory - Route bench: " + scenario.input.name) + , m_case(std::move(scenario)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.test(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + RouteBenchCase m_case; +}; + +const RouteBenchCase ROUTE_BENCH_CASES[] = { + { + .input = {.name = "no route scores worse than Data/route_bench.golden.txt", .test = test_route_bench}, + .expectation = {.description = "no story route strands; every route's verdict, times and ratios at least as good as the golden file's"}, + }, +}; + +} // namespace + + +void add_tests_AutoStory_RouteBench(UnitTestDatabase& database){ + for (const auto& scenario : ROUTE_BENCH_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.h new file mode 100644 index 0000000000..ef237aaaa4 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RouteBench_Tests.h @@ -0,0 +1,25 @@ +/* BDSP AutoStory - Route Bench Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_RouteBench_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_RouteBench_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// The route bench: every story table route's plan scored, against a golden file. +void add_tests_AutoStory_RouteBench(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp index 8b2c777f1b..995f476ce9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_RoutePlanner_Tests.cpp @@ -33,7 +33,8 @@ namespace{ using Pokemon::Direction; using Pokemon::TilePos; -StoryWorld make_world(const std::vector& rows){ +// A map of `rows`, with someone wandering `wander` if given. +StoryWorld make_world(const std::vector& rows, const std::optional& wander = std::nullopt){ Pokemon::MapData map; map.name = "Test"; map.tiles = Pokemon::Grid{(int)rows[0].size(), (int)rows.size(), {}}; @@ -42,6 +43,10 @@ StoryWorld make_world(const std::vector& rows){ map.tiles.cells.push_back(*Pokemon::tile_from_glyph(glyph)); } } + if (wander){ + map.objects.push_back({.name = "wanderer", .x = wander->x0, .y = wander->y0, .facing = std::nullopt, + .wander = wander, .trainer = std::nullopt, .hide_flag = std::nullopt}); + } StoryWorld world; world.add("Test", map, {0, 0}); return world; @@ -140,6 +145,43 @@ UnitTestResult test_plan_robust_route(Logger&){ return true; } +// Someone wanders a row, (2..4, 2): a leg may cross the row through one of +// their tiles, but not run along it through two, the leg's start among +// them. On lab-B (2026-11-08, 01.08) Route 204's youngster stopped a leg +// west along his row twice. With no other way there is no plan. +UnitTestResult test_plan_robust_route_wander_zone(Logger&){ + const Pokemon::TileBox row_zone{.x0 = 2, .y0 = 2, .x1 = 4, .y1 = 2}; + const StoryWorld room = make_world({"#######", "#.....#", "#.....#", "#.....#", "#######"}, row_zone); + const StoryWorld corridor = make_world({"#######", "#.....#", "#######"}, Pokemon::TileBox{.x0 = 2, .y0 = 1, .x1 = 4, .y1 = 1}); + RobustPlanCosts exact; + exact.exact_open_tiles = exact.max_open_tiles; + struct ZoneCase{ + std::string name; + const StoryWorld& world; + TilePos from; + TilePos goal; + std::string legs; + }; + const std::vector cases{ + {.name = "south across the row", .world = room, .from = {3, 1}, .goal = {3, 3}, .legs = "south 2 (to wall) to (3, 3)"}, + {.name = "north across the row", .world = room, .from = {3, 3}, .goal = {3, 1}, .legs = "north 2 (to wall) to (3, 1)"}, + {.name = "east into the row's first tile", .world = room, .from = {1, 2}, .goal = {2, 2}, .legs = "east 1 (open) to (2, 2)"}, + {.name = "east along the row goes round it", .world = room, .from = {1, 2}, .goal = {5, 2}, + .legs = "north 1 (to wall) to (1, 1); east 4 (to wall) to (5, 1); south 1 (open) to (5, 2)"}, + {.name = "west along the row from inside it goes round", .world = room, .from = {3, 2}, .goal = {1, 2}, + .legs = "north 1 (to wall) to (3, 1); west 2 (to wall) to (1, 1); south 1 (open) to (1, 2)"}, + {.name = "no plan when the row is the only way", .world = corridor, .from = {1, 1}, .goal = {5, 1}, .legs = ""}, + }; + for (const ZoneCase& item : cases){ + const auto legs = plan_robust_route(item.world, {item.from}, [&](const TilePos& pos){ return pos == item.goal; }, exact); + const std::string read = legs ? describe(*legs) : ""; + if (read != item.legs){ + return std::format("{}: planned \"{}\", expected \"{}\".", item.name, read, item.legs); + } + } + return true; +} + // November 5 mine report: credited taps need not establish physical pose. // The two phases are explicit diagnostics, not inferred console timing. @@ -350,6 +392,10 @@ const RoutePlannerCase ROUTE_PLANNER_CASES[] = { .input = {"robust plans", test_plan_robust_route}, .expectation = {}, }, + { + .input = {"robust plans cross a wander zone, never along it", test_plan_robust_route_wander_zone}, + .expectation = {}, + }, { .input = {"trainers' sight lines", test_trainer_sight}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.cpp new file mode 100644 index 0000000000..9eb9ef9fde --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.cpp @@ -0,0 +1,93 @@ +/* BDSP AutoStory - Story actions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Actions/PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP_AutoStory_StoryData.h" +#include "PokemonBDSP_AutoStory_StoryActions.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::Outcome; +using Pokemon::RunState; +using Pokemon::StoryAction; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; + + +namespace{ + +// Adds `action` for `kind`'s default and for each of its named actions in +// bdsp_story_actions(), each with that spec's args, so lint_story_checkpoint() +// checks a step's args against the action it names. +void add_with_specs(Pokemon::StoryActionTable& table, StoryStepKind kind, const StoryAction& action){ + const std::span specs = bdsp_story_actions(); + StoryAction fallback = action; + if (const Pokemon::StoryActionSpec* spec = Pokemon::find_story_action(specs, kind, "")){ + fallback.args = spec->args; + } + table.add(kind, "", std::move(fallback)); + for (const Pokemon::StoryActionSpec& spec : specs){ + // A name that is also a story event stays the event's. + if (spec.kind != kind || spec.name.empty() || story_events().contains(spec.name)){ + continue; + } + StoryAction named = action; + named.args = spec.args; + table.add(kind, spec.name, std::move(named)); + } +} + +} // namespace + + +Pokemon::StoryActionTable story_action_table(StoryWalkSteps& walks, const StoryBoundActions& bound){ + Pokemon::StoryActionTable table; + using WalkMethod = Outcome (StoryWalkSteps::*)(RunState&, const StoryStep&); + const auto walk = [&](StoryStepKind kind, WalkMethod method){ + add_with_specs(table, kind, StoryAction{ + .act = [&walks, method](const StoryStep& step, RunState& state){ + return (walks.*method)(state, step); + }, + }); + }; + walk(StoryStepKind::ROUTE, &StoryWalkSteps::route); + walk(StoryStepKind::LEGS, &StoryWalkSteps::legs); + walk(StoryStepKind::STEP, &StoryWalkSteps::step); + walk(StoryStepKind::TALK, &StoryWalkSteps::talk); + walk(StoryStepKind::MASH, &StoryWalkSteps::mash); + + const auto console = [&](StoryStepKind kind, const Pokemon::StoryActionFunction& act){ + add_with_specs(table, kind, StoryAction{.act = act, .needs_console = true}); + }; + console(StoryStepKind::NEW_GAME, bound.new_game); + console(StoryStepKind::OPTIONS, bound.options); + console(StoryStepKind::ANSWER, bound.answer); + console(StoryStepKind::BATTLE, bound.battle); + console(StoryStepKind::TRAIN, bound.train); + console(StoryStepKind::HEAL, bound.heal); + console(StoryStepKind::SAVE, bound.save); + + for (const auto& item : story_events()){ + StoryAction event{.act = bound.event(item.first), .needs_console = true}; + for (const Pokemon::StoryActionSpec& spec : bdsp_story_actions()){ + if (spec.name == item.first && !spec.args.empty()){ + event.args = spec.args; + break; + } + } + table.add_any_kind(item.first, std::move(event)); + } + return table; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h new file mode 100644 index 0000000000..6204f74751 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h @@ -0,0 +1,54 @@ +/* BDSP AutoStory - Story actions + * + * From: https://github.com/PokemonAutomation/ + * + * BDSP's story steps as one action table (Pokemon_StoryActions.h), which + * the console (StoryExecutor) and the simulation (SimExecutor) each bind. + * The walking steps (ROUTE, LEGS, STEP, TALK, MASH) are the same code on + * both: StoryWalkSteps on the binding's StoryStepIO. The steps that need + * the console (the intro, the options, answers, battles, training, the + * Center, saves, and the story's events, story_events()) are the + * binding's own: played on the console, stood in for on the simulation. + * + * A GAME step runs only the event its variant names, and BDSP has no SHOP + * or READY step: lint_story_checkpoint() reports a step with neither. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryActions_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryActions_H + +#include +#include +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// The actions a binding does its own way, one per kind that needs the +// console. +struct StoryBoundActions{ + Pokemon::StoryActionFunction new_game = {}; + Pokemon::StoryActionFunction options = {}; + Pokemon::StoryActionFunction answer = {}; + Pokemon::StoryActionFunction battle = {}; + Pokemon::StoryActionFunction train = {}; + Pokemon::StoryActionFunction heal = {}; + Pokemon::StoryActionFunction save = {}; + // The action for the story event named `name` (story_events()). + std::function event = {}; +}; + +// BDSP's story actions: the walking steps on `walks`, the rest `bound`'s. +// `walks` must outlive the table. +Pokemon::StoryActionTable story_action_table(StoryWalkSteps& walks, const StoryBoundActions& bound); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.cpp index 1fd3adce8e..a6bea013c2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData.cpp @@ -29,6 +29,12 @@ Pokemon::StoryArgSpec optional(std::string key, Pokemon::StoryArgType type, Poke return Pokemon::StoryArgSpec{.key = std::move(key), .type = type, .required = false, .fallback = std::move(fallback), .why = std::move(why)}; } +void add_event_actions(std::vector& actions){ + for (const auto& [name, unused] : story_events()){ + actions.push_back({.kind = Pokemon::StoryStepKind::GAME, .name = name, .args = {}}); + } +} + std::vector make_bdsp_actions(){ std::vector actions( Pokemon::builtin_story_actions().begin(), Pokemon::builtin_story_actions().end() @@ -52,22 +58,30 @@ std::vector make_bdsp_actions(){ "items", Pokemon::StoryArgType::ITEMS, "the items and how many of each" ); - for (std::string_view cost : {"town", "overworld", "indoors", "caves", "robust", "line"}){ - actions.push_back({.kind = Pokemon::StoryStepKind::ROUTE, .name = std::string(cost), .args = {route_target, fight_wild}}); + // No fallback: a ROUTE step without legs then fits the built-in "route". + const Pokemon::StoryArgSpec opt_legs{.key = "legs", .type = Pokemon::StoryArgType::LEGS, .required = false, + .fallback = std::nullopt, .why = "after the route, run its one leg until a dialogue starts"}; + for (auto& action : actions){ + if (action.kind == Pokemon::StoryStepKind::ROUTE){ + action.args.push_back(opt_legs); + } + } + for (std::string_view cost : {"town", "overworld", "indoors", "caves", "robust", "line", "trigger"}){ + actions.push_back({.kind = Pokemon::StoryStepKind::ROUTE, .name = std::string(cost), .args = {route_target, fight_wild, opt_legs}}); } - for (std::string_view act : {"to_wall", "to_dialogue", "to_map", "one_short_ok"}){ + actions.push_back({.kind = Pokemon::StoryStepKind::ROUTE, .name = "into_scene", .args = {route_target, fight_wild, legs_arg}}); + for (std::string_view act : {"to_wall", "to_dialogue", "to_map", "one_short_ok", "counted_wall"}){ actions.push_back({.kind = Pokemon::StoryStepKind::LEGS, .name = std::string(act), .args = {legs_arg, fight_wild}}); } actions.push_back({.kind = Pokemon::StoryStepKind::STEP, .name = "to_banner", .args = {direction_arg}}); + actions.push_back({.kind = Pokemon::StoryStepKind::STEP, .name = "or_legs", .args = {direction_arg, legs_arg}}); actions.push_back({.kind = Pokemon::StoryStepKind::TALK, .name = "talk_to_wanderer", .args = {}}); actions.push_back({.kind = Pokemon::StoryStepKind::MASH, .name = "a", .args = {}}); actions.push_back({.kind = Pokemon::StoryStepKind::BATTLE, .name = "starter", .args = {may_lose}}); actions.push_back({.kind = Pokemon::StoryStepKind::BATTLE, .name = "doubles", .args = {may_lose}}); actions.push_back({.kind = Pokemon::StoryStepKind::SHOP, .name = "sandgem_potions", .args = {items}}); - for (const auto& [name, unused] : story_events()){ - actions.push_back({.kind = Pokemon::StoryStepKind::GAME, .name = name, .args = {}}); - } + add_event_actions(actions); return actions; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.cpp index 254532191a..7dca2b0353 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.cpp @@ -78,7 +78,7 @@ UnitTestResult check_all_checkpoints_load(){ const std::vector expected_ids{ "00.00", "00.01", "00.02", "00.03", "00.04", "00.04b", "00.04c", "00.04d", "00.05", "00.05b", "00.05c", - "01.01", "01.02", "01.03", "01.04", "01.05", "01.06", "01.07", "01.08", "01.09", "01.10", "01.11" + "01.01", "01.02", "01.02b", "01.03", "01.04", "01.05", "01.06", "01.07", "01.08", "01.09", "01.10", "01.11" }; for (size_t i = 0; i < expected_ids.size(); i++){ @@ -107,6 +107,35 @@ UnitTestResult check_all_checkpoints_load(){ return true; } +UnitTestResult check_parity_01_02b(){ + const auto& table = story_checkpoints(); + auto it = std::find_if(table.begin(), table.end(), [](const StoryCheckpoint& cp){ + return cp.id == "01.02b"; + }); + if (it == table.end()){ + return "01.02b checkpoint not found in table"; + } + const StoryCheckpoint& cp = *it; + if (cp.title != "Oreburgh Center heal"){ + return "01.02b title mismatch"; + } + if (cp.on_failure != StoryFailure::RELOAD_AND_RETRY || cp.saves_in != "Oreburgh City"){ + return "01.02b policy mismatch"; + } + if (cp.steps.size() != 5){ + return std::format("01.02b expected 5 steps, got {}", cp.steps.size()); + } + const std::vector expected_step_names{ + "below_barry", "barry", "barrys_lines", "below_the_centers_door", "heal_oreburgh_first" + }; + for (size_t i = 0; i < expected_step_names.size(); i++){ + if (cp.steps[i].name != expected_step_names[i]){ + return std::format("01.02b step {} name mismatch: expected {}, got {}", i, expected_step_names[i], cp.steps[i].name); + } + } + return true; +} + UnitTestResult run_envelope_case(const StoryDataCase& test_case){ JsonValue val = authored_checkpoint_document("bdsp-00.01.plan"); if (test_case.input.mutate != nullptr){ @@ -149,7 +178,11 @@ class Test_StoryData : public UnitTest{ const StoryDataCase STORY_DATA_CASES[] = { { - .input = {.name = "All 22 authored checkpoints load"}, + .input = {.name = "All 23 authored checkpoints load"}, + .expectation = {.rejected = false}, + }, + { + .input = {.name = "Parity: 01.02b checkpoint"}, .expectation = {.rejected = false}, }, { diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp index 919ab90698..9f3e9dad8f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.cpp @@ -25,6 +25,7 @@ #include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "Actions/PokemonBDSP_AutoStory_LitDoorway.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RobustRoute.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TrainerSight.h" #include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h" @@ -65,7 +66,7 @@ using Pokemon::story_arg; std::optional story_route_costs(const std::string& action){ - if (action.empty() || action == "route"){ + if (action.empty() || action == ROUTE_ONTO_TRIGGER || action == ROUTE_INTO_SCENE || action == "route"){ return route_plan_costs(); } if (action == "town"){ @@ -103,72 +104,101 @@ void save_failure_screenshot(VideoStream& stream, size_t attempt){ stream.log("Failure screenshot: " + path); } +} // namespace + + +void ConsoleStepGuard::before_step(const StoryStep& step){ + m_stream.log(std::format("[{}] {} {}: {}", m_checkpoint, Pokemon::story_step_kind_name(step.kind), step.name, step.why), COLOR_BLUE); } +bool ConsoleStepGuard::stops_on_failure(const StoryStep&) const{ + return m_stop_rows.contains(m_checkpoint); +} + +void ConsoleStepGuard::on_failure(const StoryStep&, const OperationFailedException& error){ + // Attempts are the segment's policy; this only counts them for the + // log line the lab's run watcher reads. + const size_t attempt = m_failures[m_checkpoint]++; + m_stream.log(std::format("checkpoint_reattempt_loop: attempt {} failed: {}: {}", attempt, m_checkpoint, error.message()), COLOR_RED); + save_failure_screenshot(m_stream, attempt); +} + +void ConsoleStepGuard::on_interrupt(const StoryStep& step, const Pokemon::InterruptCheck& check){ + const bool cleared = check.outcome.succeeded(); + m_stream.log(std::format( + "[{}] {}: before it, {}: {}", m_checkpoint, step.name, + Pokemon::interrupt_kind_name(check.verdict.kind), cleared ? "cleared" : Pokemon::to_string(check.outcome) + ), cleared ? COLOR_ORANGE : COLOR_RED); +} + +void ConsoleStepGuard::on_screen(const StoryStep& step, const Pokemon::ScreenSettle& screen){ + m_stream.log(std::format("[Screen] before {}: {}", step.name, Pokemon::describe(screen))); +} + +// The table and the guard are members, built after the base: it only +// keeps references to them until a step runs. StoryExecutor::StoryExecutor(StoryEnv& env) - : m_env(env) + : Pokemon::TableExecutor(m_table, m_guard) + , m_env(env) , m_io(env.env.console, env.context) , m_walks(m_io) -{} + , m_guard(env.env.console, m_checkpoint) + , m_table(story_action_table(m_walks, console_actions())) + , m_look(env.env.console, env.context) + , m_interrupts(story_interrupts([this](bool fresh){ return m_look.look(fresh); }, console_interrupt_actions())) +{ + set_interrupts(&m_interrupts); +} -void StoryExecutor::begin_attempt(const Pokemon::StoryCheckpoint& data){ - m_checkpoint = data.id; - m_walks.begin_attempt(data.id); +StoryBoundActions StoryExecutor::console_actions(){ + const auto method = [this](Outcome (StoryExecutor::*action)(RunState&, const StoryStep&)){ + return [this, action](const StoryStep& step, RunState& state){ + return (this->*action)(state, step); + }; + }; + return StoryBoundActions{ + .new_game = method(&StoryExecutor::new_game), + .options = method(&StoryExecutor::options), + .answer = method(&StoryExecutor::answer), + .battle = method(&StoryExecutor::battle), + .train = method(&StoryExecutor::train), + .heal = method(&StoryExecutor::heal), + .save = method(&StoryExecutor::save), + .event = [this](const std::string& name) -> Pokemon::StoryActionFunction{ + return [this, event = story_events().at(name)](const StoryStep& step, RunState& state){ + return event(*this, state, step); + }; + }, + }; } -Outcome StoryExecutor::run(const StoryStep& step, RunState& state){ - stream().log(std::format("[{}] {} {}: {}", m_checkpoint, Pokemon::story_step_kind_name(step.kind), step.name, step.why), COLOR_BLUE); - try{ - return run_guarded(state, step); - }catch (OperationFailedException& e){ - if (m_stop_rows.contains(m_checkpoint)){ - throw; - } - // Attempts are the segment's policy; this only counts them for the - // log line the lab's run watcher reads. - const size_t attempt = m_failures[m_checkpoint]++; - stream().log(std::format("checkpoint_reattempt_loop: attempt {} failed: {}: {}", attempt, m_checkpoint, e.message()), COLOR_RED); - save_failure_screenshot(stream(), attempt); - return Pokemon::outcome_failed("operation_failed", e.message()); - } +// A wild battle is run from, a trainer who saw us fought, a dialog or a +// warp's scene pressed through to the quiet overworld. +StoryInterruptActions StoryExecutor::console_interrupt_actions(){ + const auto settle = [this](std::string label){ + return [this, label](const Pokemon::InterruptVerdict&, RunState&){ + m_io.settle(BUTTON_B, label, false, ""); + return Pokemon::outcome_ok(); + }; + }; + return StoryInterruptActions{ + .wild = [this](const Pokemon::InterruptVerdict&, RunState&){ + run_from_wild_battle(stream(), context()); + return Pokemon::outcome_ok(); + }, + .trainer = [this](const Pokemon::InterruptVerdict&, RunState&){ + m_io.fight(""); + return Pokemon::outcome_ok(); + }, + .dialog = settle("a dialog between steps"), + .warp = settle("a warp between steps"), + }; } -Outcome StoryExecutor::run_guarded(RunState& state, const StoryStep& step){ - const StoryEvents& events = story_events(); - if (auto event = events.find(step.action); event != events.end()){ - return event->second(*this, state, step); - } - switch (step.kind){ - case Pokemon::StoryStepKind::NEW_GAME: - return new_game(state, step); - case Pokemon::StoryStepKind::OPTIONS: - return options(state, step); - case Pokemon::StoryStepKind::ROUTE: - return route(state, step); - case Pokemon::StoryStepKind::LEGS: - return legs(state, step); - case Pokemon::StoryStepKind::STEP: - return this->step(state, step); - case Pokemon::StoryStepKind::TALK: - return talk(state, step); - case Pokemon::StoryStepKind::ANSWER: - return answer(state, step); - case Pokemon::StoryStepKind::MASH: - return mash(state, step); - case Pokemon::StoryStepKind::BATTLE: - return battle(state, step); - case Pokemon::StoryStepKind::TRAIN: - return train(state, step); - case Pokemon::StoryStepKind::HEAL: - return heal(state, step); - case Pokemon::StoryStepKind::SAVE: - return save(state, step); - case Pokemon::StoryStepKind::GAME: - return game(state, step); - default: - return Pokemon::unsupported_step(step); - } +void StoryExecutor::begin_attempt(const Pokemon::StoryCheckpoint& data){ + m_checkpoint = data.id; + m_walks.begin_attempt(data.id, data.steps); } @@ -183,22 +213,6 @@ Outcome StoryExecutor::options(RunState&, const StoryStep&){ return Pokemon::outcome_ok(); } -Outcome StoryExecutor::route(RunState& state, const StoryStep& step){ - return m_walks.route(state, step); -} - -Outcome StoryExecutor::legs(RunState& state, const StoryStep& step){ - return m_walks.legs(state, step); -} - -Outcome StoryExecutor::step(RunState& state, const StoryStep& step){ - return m_walks.step(state, step); -} - -Outcome StoryExecutor::talk(RunState& state, const StoryStep& step){ - return m_walks.talk(state, step); -} - Outcome StoryExecutor::answer(RunState&, const StoryStep& step){ wait_for_dialogue(stream(), context(), label_of(step)); const bool yes = story_arg(step.args, "yes"); @@ -207,10 +221,6 @@ Outcome StoryExecutor::answer(RunState&, const StoryStep& step){ return Pokemon::outcome_ok(); } -Outcome StoryExecutor::mash(RunState& state, const StoryStep& step){ - return m_walks.mash(state, step); -} - Outcome StoryExecutor::battle(RunState&, const StoryStep& step){ // "starter": the Starly battle at the lake (00.02). It opens on its own, // with no talk, and the starter has no Poke Balls to throw; the scene @@ -252,14 +262,18 @@ Outcome StoryExecutor::heal(RunState&, const StoryStep& step){ // doorway lineup is for when the run in finds no door: people on the // way can leave the route unsure of the column (r59, Jubilife). Below // Sandgem's door the lineup read 0.7 tile off and stepped us off it (r48). + // With no fade, the run can have gone on in to the counter (lab-B + // 2026-11-08, Oreburgh). route_turn(stream(), context(), Direction::NORTH); - const bool in = m_io.run_into_door(Direction::NORTH, m_walks.can_run()); - stream().log(std::format("[{}] {}: north into the Center: {}.", m_checkpoint, step.name, in ? "faded" : "no door; lining up by sight")); - if (in){ - pbf_wait(context(), 1500ms); - }else{ + const CenterEntry in = run_into_center(m_io, m_walks.can_run(), [this]{ + context().wait_for_all_requests(); + const VideoSnapshot screen = stream().video().snapshot(); + return screen && pokemon_center_inside(*screen.frame); + }, [&]{ enter_lit_door(stream(), context(), label_of(step)); - } + }, label_of(step)); + stream().log(std::format("[{}] {}: north into the Center: {}.", m_checkpoint, step.name, + in == CenterEntry::FADED ? "faded" : in == CenterEntry::INSIDE ? "no fade, but inside" : "no fade; lined up by sight")); talk_to_nurse(stream(), context(), label_of(step)); // Her last line ("We hope to see you again!") can still be up, and a // line stops the run out at once (r62): B until none shows. @@ -275,9 +289,9 @@ Outcome StoryExecutor::heal(RunState&, const StoryStep& step){ // Out the same way: south until the fade. The walk out's indoor check // read "not a room" a step from the counter and stopped inside (r50, r59). route_turn(stream(), context(), Direction::SOUTH); - const bool out = m_io.run_into_door(Direction::SOUTH, m_walks.can_run()); + const bool out = m_io.run_into_door(Direction::SOUTH, m_walks.can_run()).any(); stream().log(std::format("[{}] {}: south out of the Center: {}.", m_checkpoint, step.name, out ? "faded" : "no fade yet")); - m_io.settle(BUTTON_B, label_of(step), !out); + m_io.settle(BUTTON_B, label_of(step), !out, ""); // r143a's heal said it had walked out while still inside. context().wait_for_all_requests(); VideoSnapshot screen = stream().video().snapshot(); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h index 46a5fd7f91..419d93af74 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h @@ -1,5 +1,7 @@ /* BDSP AutoStory - Story executor * +// code-health: allow header_symbols -- BDSP story executor and checkpoint execution primitives + * * From: https://github.com/PokemonAutomation/ * * BDSP's way of doing the shared story steps @@ -10,12 +12,15 @@ * battles. A step whose variant names one of the story's events * (story_events(), PokemonBDSP_AutoStory_Events.h) runs that event, * whatever its kind: the scripted scenes and the console-measured walks - * of segment 01. + * of segment 01. It is the console's binding of the story's action table + * (story_action_table()); the simulation binds the same table. * - * Every step runs inside a guard that turns a failed console step into a - * failed Outcome, with a screenshot and the "checkpoint_reattempt_loop: - * attempt N failed" line the lab's run watcher reads; the segment then - * reloads the row's save and runs it again. + * Every step runs inside a guard (ConsoleStepGuard) that turns a failed + * console step into a failed Outcome, with a screenshot and the + * "checkpoint_reattempt_loop: attempt N failed" line the lab's run watcher + * reads; the segment then reloads the row's save and runs it again. + * Before each step it clears what came up since the step before + * (story_interrupts(), PokemonBDSP_AutoStory_StoryInterrupts.h). * */ @@ -26,18 +31,22 @@ #include #include #include +#include #include #include #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RobustRoute.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_StoryWorld.h" +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" #include "Pokemon/AutoStory/Pokemon_StorySegments.h" #include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" #include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" #include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" #include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP_AutoStory_StoryActions.h" +#include "PokemonBDSP_AutoStory_StoryInterrupts.h" #include "PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP_AutoStory_StoryWalkSteps.h" @@ -82,15 +91,53 @@ struct StoryEnv{ }; -// The plan costs a ROUTE step's variant names: "" the route costs, -// "town" town_plan_costs(), "robust" the planner's defaults, "line" -// waypoint_plan_costs() (a stretch of a line a human walked). Nothing for -// another name. +// The variant of a ROUTE step whose target is the next scene's trigger: +// the scene starts there and stops the walk, as a wall would (00.04's +// Mom's call on (6, 9)). It plans with the route costs. +inline constexpr std::string_view ROUTE_ONTO_TRIGGER = "trigger"; + +// The variant of a ROUTE step that, once at its target, runs its one leg +// ("legs") until a scene's dialogue starts. It plans with the route costs. +inline constexpr std::string_view ROUTE_INTO_SCENE = "into_scene"; + +// The plan costs a ROUTE step's variant names: "", ROUTE_ONTO_TRIGGER and +// ROUTE_INTO_SCENE the route costs, "town" town_plan_costs(), "robust" the planner's +// defaults, "line" waypoint_plan_costs() (a stretch of a line a human +// walked). Nothing for another name. std::optional story_route_costs(const std::string& variant); -// Does BDSP's kinds of story step on the console. -class StoryExecutor : public Pokemon::StoryStepExecutor{ +// What the console does around each story step: the step's log line, and +// a failed step's "checkpoint_reattempt_loop" line and screenshot. +class ConsoleStepGuard : public Pokemon::StepGuard{ +public: + // `checkpoint` names the row running now; both must outlive the guard. + ConsoleStepGuard(VideoStream& stream, const std::string& checkpoint) + : m_stream(stream) + , m_checkpoint(checkpoint) + {} + // The rows whose failure ends the program (StoryFailure::STOP). + void set_stop_rows(std::set rows){ + m_stop_rows = std::move(rows); + } + + virtual void before_step(const Pokemon::StoryStep& step) override; + virtual bool stops_on_failure(const Pokemon::StoryStep& step) const override; + virtual void on_failure(const Pokemon::StoryStep& step, const OperationFailedException& error) override; + virtual void on_interrupt(const Pokemon::StoryStep& step, const Pokemon::InterruptCheck& check) override; + virtual void on_screen(const Pokemon::StoryStep& step, const Pokemon::ScreenSettle& screen) override; + +private: + VideoStream& m_stream; + const std::string& m_checkpoint; + std::map m_failures; + std::set m_stop_rows; +}; + + +// Does BDSP's kinds of story step on the console: the story's action +// table, its rows that need the console bound to the methods below. +class StoryExecutor : public Pokemon::TableExecutor{ public: explicit StoryExecutor(StoryEnv& env); @@ -106,11 +153,10 @@ class StoryExecutor : public Pokemon::StoryStepExecutor{ // The rows whose failure ends the program (StoryFailure::STOP): a // failed step there throws on instead of failing the step. void set_stop_rows(std::set rows){ - m_stop_rows = std::move(rows); + m_guard.set_stop_rows(std::move(rows)); } // A new attempt of a row: every trainer can see us again. virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override; - virtual Pokemon::Outcome run(const Pokemon::StoryStep& step, Pokemon::RunState& state) override; protected: // The row running now. @@ -121,25 +167,8 @@ class StoryExecutor : public Pokemon::StoryStepExecutor{ Pokemon::Outcome new_game(Pokemon::RunState& state, const Pokemon::StoryStep& step); // verify_tutorial_settings(): fast text, Autosave off. Pokemon::Outcome options(Pokemon::RunState& state, const Pokemon::StoryStep& step); - // Variant: the plan's costs ("" route, "town", "robust", "line"). - Pokemon::Outcome route(Pokemon::RunState& state, const Pokemon::StoryStep& step); - // Each leg in D-pad taps, turning first. Variant "one_short_ok": a leg - // may end a tile short (a door lined up by sight after). Variant - // "to_wall": each leg walks until something stops it, for at most its - // tiles' time, as measured on the console; the pose is then unknown - // unless the step gives one. - Pokemon::Outcome legs(Pokemon::RunState& state, const Pokemon::StoryStep& step); - // One D-pad step `direction`, turning first: onto a scene's trigger or - // into a door. Variant "to_banner": one tap into a cave mouth, then - // wait for pose_after's map's location banner. - Pokemon::Outcome step(Pokemon::RunState& state, const Pokemon::StoryStep& step); - // A at what we face; a dialogue must open. - Pokemon::Outcome talk(Pokemon::RunState& state, const Pokemon::StoryStep& step); // A for YES, B for NO, once the question's box shows. Pokemon::Outcome answer(Pokemon::RunState& state, const Pokemon::StoryStep& step); - // A dialogue opens (or has), then B through it to the overworld; - // variant "a": A through it, for lines that give an item. - Pokemon::Outcome mash(Pokemon::RunState& state, const Pokemon::StoryStep& step); // A trainer's text opens (or has) and ends in a battle, fought with the // best move; one lost fails the step unless `may_lose`. Variant // "doubles" for a tag battle. @@ -154,16 +183,39 @@ class StoryExecutor : public Pokemon::StoryStepExecutor{ Pokemon::Outcome game(Pokemon::RunState& state, const Pokemon::StoryStep& step); private: - Pokemon::Outcome run_guarded(Pokemon::RunState& state, const Pokemon::StoryStep& step); + StoryBoundActions console_actions(); + StoryInterruptActions console_interrupt_actions(); StoryEnv& m_env; ConsoleStoryStepIO m_io; - // The steps that walk and talk (ROUTE, LEGS, STEP, TALK, MASH). + // The steps that walk and talk, the table's rows for them: + // - ROUTE. Variant: the plan's costs ("" route, "town", "robust", "line"). + // - LEGS: each leg in D-pad taps, turning first. Variant "one_short_ok": + // a leg may end a tile short (a door lined up by sight after). Variant + // "to_wall": each leg walks until something stops it, for at most its + // tiles' time, as measured on the console; the pose is then unknown + // unless the step gives one. Variant "counted_wall": its one leg walks + // to the wall, waiting out anyone walking about in the way, and fails + // when the tiles walked are far off the map's from the step's start. + // Variant "measured": each leg in taps; the tiles of the step's start + // whose taps the map lets move as many as moved are where we are. + // - STEP: one D-pad step `direction`, turning first: onto a scene's + // trigger or into a door. Variant "to_banner": one tap into a cave + // mouth, then wait for pose_after's map's location banner. Variant + // "or_legs": into a door, and with no fade, the step's legs onto the + // door's tile and into it again. + // - TALK: A at what we face; a dialogue must open. + // - MASH: a dialogue opens (or has), then B through it to the overworld; + // variant "a": A through it, for lines that give an item. StoryWalkSteps m_walks; std::string m_checkpoint; - std::map m_failures; std::map m_run_counts; - std::set m_stop_rows; + ConsoleStepGuard m_guard; + // The story's actions, its console rows bound to this executor. + Pokemon::StoryActionTable m_table; + // What is cleared between steps, looked for on the screen. + ConsoleScreenLook m_look; + Pokemon::StoryInterrupts m_interrupts; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp new file mode 100644 index 0000000000..3a9edd889a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.cpp @@ -0,0 +1,78 @@ +/* BDSP AutoStory - Story interrupts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonTools/Async/InferenceRoutines.h" +#include "PokemonBDSP_AutoStory_StoryInterrupts.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::InterruptKind; +using Pokemon::InterruptPose; +using Pokemon::StoryStepKind; + + +bool presses_through_text(StoryStepKind kind){ + switch (kind){ + case StoryStepKind::MASH: + case StoryStepKind::ANSWER: + case StoryStepKind::BATTLE: + case StoryStepKind::GAME: + case StoryStepKind::NEW_GAME: + return true; + default: + return false; + } +} + +Pokemon::StoryInterrupts story_interrupts(Pokemon::ScreenLookFunction look, const StoryInterruptActions& actions){ + Pokemon::StoryInterrupts out; + out.look = std::move(look); + out.handlers.add(InterruptKind::WILD_ENCOUNTER, {.handle = actions.wild, .pose = InterruptPose::UNCHANGED}); + out.handlers.add(InterruptKind::TRAINER_SIGHT, {.handle = actions.trainer, .pose = InterruptPose::UNCHANGED}); + out.handlers.add(InterruptKind::DIALOG, {.handle = actions.dialog, .pose = InterruptPose::UNCHANGED}); + out.handlers.add(InterruptKind::WARP, {.handle = actions.warp, .pose = InterruptPose::LOST}); + for (StoryStepKind step : {StoryStepKind::MASH, StoryStepKind::ANSWER, StoryStepKind::BATTLE, StoryStepKind::GAME, StoryStepKind::NEW_GAME}){ + out.handlers.starts_on(step, InterruptKind::DIALOG); + } + out.handlers.starts_on(StoryStepKind::BATTLE, InterruptKind::TRAINER_SIGHT); + // The story's wild battles (the Starly at the lake) are the step's. + out.handlers.starts_on(StoryStepKind::BATTLE, InterruptKind::WILD_ENCOUNTER); + out.handlers.starts_on(StoryStepKind::TRAIN, InterruptKind::WILD_ENCOUNTER); + for (StoryStepKind step : {StoryStepKind::GAME, StoryStepKind::NEW_GAME}){ + for (InterruptKind kind : {InterruptKind::WILD_ENCOUNTER, InterruptKind::TRAINER_SIGHT, InterruptKind::WARP}){ + out.handlers.starts_on(step, kind); + } + } + return out; +} + + +ConsoleScreenLook::ConsoleScreenLook(ConsoleHandle& console, ProControllerContext& context) + : m_stream(console) + , m_context(context) + , m_observer(BattleCue::WILD_MENU, "") + , m_eyes(console, m_observer) + , m_watcher(m_eyes) + , m_start(current_time()) +{} + +Pokemon::ScreenLook ConsoleScreenLook::look(bool fresh){ + if (fresh){ + m_watcher.reset(); + m_start = current_time(); + } + wait_until(m_stream, m_context, BETWEEN_STEPS_LOOK, {m_watcher}); + return {.log = m_watcher.log(), .window = {.start = m_start, .end = current_time()}}; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h new file mode 100644 index 0000000000..000352fcbd --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h @@ -0,0 +1,80 @@ +/* BDSP AutoStory - Story interrupts + * + * From: https://github.com/PokemonAutomation/ + * + * BDSP's interrupts between story steps (Pokemon_StoryInterrupts.h): a + * wild battle is run from, a trainer who saw us is fought, a dialog is + * pressed through, and a warp is waited out, the pose then lost. The + * console (ConsoleScreenLook and the executor's console actions) and the + * simulation bind the same table. + * + * The steps that press through text (MASH, ANSWER, BATTLE, GAME, + * NEW_GAME) start on a dialog: one showing before them is theirs. A + * BATTLE and a GAME step start on a trainer's lines too, TRAIN on a wild + * battle, and a GAME step (a measured script) and NEW_GAME (the title + * screen) on anything. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryInterrupts_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryInterrupts_H + +#include "Common/Cpp/Time.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "Pokemon/AutoStory/Pokemon_ScreenEvents.h" +#include "Pokemon/AutoStory/Pokemon_StoryInterrupts.h" +#include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_ScreenEvents.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// What clears each kind of interrupt, as a binding does it. +struct StoryInterruptActions{ + Pokemon::InterruptAction wild = {}; + Pokemon::InterruptAction trainer = {}; + Pokemon::InterruptAction dialog = {}; + Pokemon::InterruptAction warp = {}; +}; + +// BDSP's interrupts: `look` judged with the shared knobs, `actions` for +// each kind, and the steps that start on one. +Pokemon::StoryInterrupts story_interrupts(Pokemon::ScreenLookFunction look, const StoryInterruptActions& actions); + +// Whether a step of `kind` presses through any text showing when it +// starts; a step of another kind is stopped by it (a walk, a talk). +bool presses_through_text(Pokemon::StoryStepKind kind); + + +// How long the console looks at the screen before a step: a few frames, +// for what came up after the step before had settled. +constexpr Milliseconds BETWEEN_STEPS_LOOK = Milliseconds(300); + +// The console's look between steps: BDSP's screen events for +// BETWEEN_STEPS_LOOK, everything showing in it judged. The Switch's HOME +// menu comes first (Pokemon::SwitchHomeObserver): BDSP's detectors read it +// as a quiet overworld (lab-B 2026-11-09 15:31). +class ConsoleScreenLook{ +public: + ConsoleScreenLook(ConsoleHandle& console, ProControllerContext& context); + + Pokemon::ScreenLook look(bool fresh); + +private: + VideoStream& m_stream; + ProControllerContext& m_context; + BdspScreenObserver m_observer; + Pokemon::SwitchHomeObserver m_eyes; + Pokemon::ScreenEventWatcher m_watcher; + WallClock m_start; +}; + + + +} // 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 index 6d181824fc..f90a495045 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryMaps_Tests.cpp @@ -27,6 +27,8 @@ #include "Data/PokemonBDSP_AutoStory_TrainerSight.h" #include "Data/PokemonBDSP_AutoStory_WalkRules.h" #include "PokemonBDSP_AutoStory_StoryMaps_Tests.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "PokemonBDSP_AutoStory_StoryTable.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -36,6 +38,7 @@ namespace PokemonBDSP{ namespace{ using Pokemon::Direction; +using Pokemon::StoryStep; using Pokemon::TileKind; using Pokemon::TilePos; @@ -90,34 +93,62 @@ UnitTestResult test_route202_catch_grass(Logger& logger){ 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. +// The table's step `name` in row `row`. +const StoryStep& table_step(const std::string& row, const std::string& name){ + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const StoryStep& step : checkpoint.steps){ + if (checkpoint.id == row && step.name == name){ + return step; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + name + " in " + row); +} + +// 00.04b's way to Sandgem's Pokemon Center from the road's last row, +// wherever on it the run in stopped (lab-B 2026-11-09 20:09: two columns +// short): west to the row's wall and south onto the Center's sign, the +// table's walls, then its taps round the sign to below the door, each +// open, the door straight north of where they end. 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.", + const TilePos entry = map_point("SandgemTown", "route_202_entry_stop"); + if (town.tile(sign) != TileKind::SIGN || town.tile(door) != TileKind::DOOR){ + return std::format("The Center's sign {} and door {} are not a sign and a door.", 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."; + const StoryStep& walls = table_step("00.04b", "above_center_sign"); + const StoryStep& taps = table_step("00.04b", "below_center_door"); + const auto& walls_legs = Pokemon::story_arg>(walls.args, "legs"); + const auto& taps_legs = Pokemon::story_arg>(taps.args, "legs"); + const TilePos above_sign = sign.next(Direction::NORTH); + for (TilePos start = entry; standable(town, start); start = start.next(Direction::WEST)){ + TilePos pos = start; + for (const Pokemon::StoryLeg& leg : walls_legs){ + pos = slide_to_wall(town, pos, leg.direction).stop; + } + if (!(pos == above_sign)){ + return std::format("From {} the walls end at {}, not above the sign {}.", + Pokemon::to_string(start), Pokemon::to_string(pos), Pokemon::to_string(sign)); } - 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."; + } + TilePos pos = above_sign; + for (const Pokemon::StoryLeg& leg : taps_legs){ + for (int tap = 0; tap < leg.tiles; tap++){ + const std::optional next = step(town, pos, leg.direction); + if (!next){ + return std::format("{} from {} is blocked.", Pokemon::direction_name(leg.direction), Pokemon::to_string(pos)); + } + pos = *next; } - 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))); + logger.log(std::format("Sandgem: from the road's last row by walls to {}, {} tap legs to below the door {}.", + Pokemon::to_string(above_sign), taps_legs.size(), Pokemon::to_string(door))); return true; } @@ -303,7 +334,7 @@ const StoryMapsCase STORY_MAPS_CASES[] = { .expectation = {}, }, { - .input = {"Sandgem Town: below the Center's sign to below its door", test_sandgem_center_approach}, + .input = {"Sandgem Town: from the road's last row by walls to below the Center's door", test_sandgem_center_approach}, .expectation = {}, }, { diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp index f172d91bef..d5768918b6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.cpp @@ -6,8 +6,13 @@ #include #include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Filesystem/Filesystem.h" #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" +#include "CommonFramework/GlobalAutoPaths.h" #include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" #include "CommonTools/Async/InferenceRoutines.h" #include "CommonTools/VisualDetectors/BlackScreenDetector.h" @@ -18,7 +23,9 @@ #include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" #include "PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LocationBannerWatcher.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "Actions/PokemonBDSP_AutoStory_TalkOver.h" #include "Actions/PokemonBDSP_AutoStory_Talks.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkDpad.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkResult.h" @@ -38,72 +45,6 @@ using Pokemon::Direction; namespace{ -// One rule for scenes and map changes: v2's long B mashes, with an end -// check. Press through the text, and keep pressing B while the screen is -// quiet: a scene can pause while someone walks off (Dawn and Barry after -// Rowan leaves, r23), fade dimly, not to black, to another map (r25), or -// wait on a box the detector misses (r26). B never starts a talk on the -// overworld. Done once the overworld has shown, with no text and a still -// screen, for 5 s of presses: after r31's fade home a scripted walk-in ran -// 5 s with no text before Mom spoke. -// -// A step or scene that ends on another map (`fade`) must fade on the way, -// and only the quiet after the fade counts: r30's scene went quiet for 5 s -// before the fade home, and r28 "went out" a tile beside the door and -// walked a whole route in the house. No fade is a map mismatch. -constexpr double FADE_DARKNESS = 75; // brightness 0 to 255; cave fades reach ~45..64, r24's dim fade goes darker -void settle(VideoStream& stream, ProControllerContext& context, Button button, const std::string& label, bool fade){ - const WallClock none = WallClock::max(); - const WallClock deadline = current_time() + 120s; - ShortDialogDetector dialog; - OverworldDetector overworld; - BattleMenuDetector battle_menu(BattleType::STANDARD); - WallClock quiet_since = none, calm_since = none; - double darkest = 255; - VideoSnapshot previous; - while (current_time() < deadline){ - context.wait_for_all_requests(); - const auto frame = stream.video().snapshot(); - const WallClock now = current_time(); - if (frame && battle_menu.detect(frame)){ - stream.log("[Story] " + label + ": in wild battle during settle; fleeing."); - run_from_wild_battle(stream, context); - continue; - } - if (frame){ - darkest = std::min(darkest, image_average(*frame.frame).sum() / 3); - } - const bool talking = frame && dialog.detect(frame); - const bool still = frame && previous && walk_screen_change(*previous.frame, *frame.frame) < WALK_TAP_BLOCKED_CHANGE; - previous = frame; - const bool calm = !talking && overworld.detect(frame) && (!fade || darkest < FADE_DARKNESS); - calm_since = calm ? (calm_since == none ? now : calm_since) : none; - if (calm && now - calm_since >= 15000ms){ - stream.log(std::format("[Story] {}: settled on calm overworld; darkest frame {:.0f}.", label, darkest)); - return; - } - if (!talking && still && overworld.detect(frame) && (!fade || darkest < FADE_DARKNESS)){ - quiet_since = quiet_since == none ? now : quiet_since; - if (now - quiet_since >= 5000ms){ - stream.log(std::format("[Story] {}: settled; darkest frame {:.0f}.", label, darkest)); - return; - } - }else{ - quiet_since = none; - } - pbf_press_button(context, talking ? button : BUTTON_B, 80ms, 1200ms); - } - OperationFailedExceptionWithScreenshot::fire(ErrorReportMode::SEND_ERROR_REPORT, - fade && darkest >= FADE_DARKNESS - ? label + ": no fade within 120 s, so we are not where the step goes (map mismatch)." - : label + ": not back on a quiet overworld within 120 s.", - stream); -} - -// Holds the D-pad toward a door (with B after the shoes) until the screen goes -// dark or a line shows, up to 12 s. Returns whether it went dark. A line -// stops it: holding on under Mom's "Oh, Kosmos!" wasted 12 s (r45). A wild -// battle in a cave corridor runs away before returning. DpadPosition dpad_toward(Direction direction){ return direction == Direction::NORTH ? DPAD_UP : @@ -111,24 +52,119 @@ DpadPosition dpad_toward(Direction direction){ direction == Direction::WEST ? DPAD_LEFT : DPAD_RIGHT; } -bool run_into_door(VideoStream& stream, ProControllerContext& context, Direction direction, bool run, Milliseconds timeout){ - const DpadPosition dpad = dpad_toward(direction); - BlackScreenWatcher dark(COLOR_RED, {0.1, 0.1, 0.8, 0.8}, 3 * FADE_DARKNESS, 60); - WhiteScreenWatcher white(COLOR_BLUE, {0.1, 0.1, 0.8, 0.8}, WhiteScreenWatcher::FinderType::PRESENT, 60ms); +// A door run's fade watch (DOOR_FADE_RULE) that fires only from `from` on. +// It keeps a small copy of each frame for the scene comparison, and the +// fade it saw. +class DoorFadeFrom : public VisualInferenceCallback{ +public: + explicit DoorFadeFrom(WallClock from) + : VisualInferenceCallback("DoorFadeFrom") + , m_watch(DOOR_FADE_RULE) + , m_from(from) + {} + virtual void make_overlays(VideoOverlaySet& items) const override{ + items.add(COLOR_RED, {0.1, 0.1, 0.8, 0.8}); + } + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ + const Pokemon::TransitionSample sample = Pokemon::transition_sample(VideoSnapshot(frame.scale_to(192, 108), timestamp)); + m_fade = m_watch.push(sample); + return m_fade != WarpFade::NONE && timestamp >= m_from; + } + WarpFade fade() const{ + return m_fade; + } + const WarpFadeWatch& watch() const{ + return m_watch; + } + +private: + WarpFadeWatch m_watch; + WallClock m_from; + WarpFade m_fade = WarpFade::NONE; +}; + +// How one hold toward a door ended: run_until()'s index (0 the fade, 1 a +// line, 2 a wild battle, 3 the far map's banner; -1 time up), the fade +// and how it showed, when the screen last went dark, and the banner read. +struct DoorHoldEnd{ + int ret; + WarpFade fade; + std::string how; + WallClock went_dark; + std::string banner; +}; + +DoorHoldEnd hold_into_door(VideoStream& stream, ProControllerContext& context, DpadPosition dpad, bool run, Milliseconds hold, Milliseconds dark_from, const std::string& banner){ + DoorFadeFrom fade(current_time() + dark_from); ShortDialogWatcher dialog(COLOR_YELLOW); BattleMenuWatcher battle(BattleType::STANDARD, COLOR_YELLOW); + LocationBannerWatcher far_banner(banner); + std::vector watchers{{fade}, {dialog}, {battle}}; + if (!banner.empty()){ + watchers.emplace_back(far_banner); + } const int ret = run_until(stream, context, [&](ProControllerContext& context){ if (run){ - ssf_press_button(context, BUTTON_B, 0ms, timeout, 0ms); + ssf_press_button(context, BUTTON_B, 0ms, hold, 0ms); } - pbf_press_dpad(context, dpad, timeout, 0ms); - }, {{dark}, {white}, {dialog}, {battle}}); - if (ret == 3){ - stream.log("[Story] run_into_door: wild battle; fleeing."); - run_from_wild_battle(stream, context); - return false; + pbf_press_dpad(context, dpad, hold, 0ms); + }, watchers); + return { + .ret = ret, + .fade = ret == 0 ? fade.fade() : WarpFade::NONE, + .how = fade.watch().how(), + .went_dark = fade.watch().went_dark().value_or(WallClock::max()), + .banner = ret == 3 ? far_banner.seen() : "", + }; +} + +// Wild battles a run into a door flees and runs on after. +constexpr size_t DOOR_RUN_BATTLES = 3; + +// Holds the D-pad toward a door (with B after the shoes) for `timeout` +// until its fade (DOOR_FADE_RULE) or a line shows. Returns what it saw. +// A fade whose hold fell between two frames shows at the scene after it, +// so a missed 50 ms fade no longer runs the whole timeout. +// A line stops it: holding on under Mom's "Oh, Kosmos!" wasted 12 s (r45). +// Dark in the first `dark_from` of running is not the door (lab-B +// 2026-11-08: dark at 1.8 s, halfway down the mine's entrance hall). A wild +// battle on the way is fled, and the run goes on for the time it had left: +// only the running counts, up to the battle's fade. +// The far map's banner `banner` shows after the fade, so it ends the run +// only when the fade went unseen (#268 slice 1). +WarpSeen run_into_door(VideoStream& stream, ProControllerContext& context, Direction direction, bool run, Milliseconds timeout, Milliseconds dark_from, const std::string& banner){ + Milliseconds left = timeout; + for (size_t battles = 0;; battles++){ + const WallClock start = current_time(); + const DoorHoldEnd end = hold_into_door(stream, context, dpad_toward(direction), run, left, dark_from, banner); + if (end.ret == 2){ + const WallClock stopped = std::min(end.went_dark, current_time()); + const Milliseconds ran = std::chrono::duration_cast(stopped - start) - ROUTE_START_DELAY; + const Milliseconds counted = std::clamp(ran, 0ms, left); + left -= counted; + dark_from -= std::min(dark_from, counted); + stream.log(std::format("[Story] run_into_door: wild battle after {} ms of running; fleeing.", counted.count())); + run_from_wild_battle(stream, context); + if (battles < DOOR_RUN_BATTLES && left > 0ms){ + continue; + } + return {}; + } + if (end.ret == 0){ + stream.log(std::format("[Story] run_into_door: {} detected ({}).", warp_fade_name(end.fade), end.how)); + }else if (end.ret == 1){ + stream.log("[Story] run_into_door: dialog detected."); + }else if (end.ret == 3){ + stream.log("[Story] run_into_door: no fade seen, but the banner \"" + end.banner + "\" read."); + }else if (end.went_dark != WallClock::max()){ + // Dark only before dark_from: early, or the door's fade itself. + stream.log(std::format("[Story] run_into_door: timed out; dark {} ms in, before dark_from {} ms.", + std::chrono::duration_cast(end.went_dark - start).count(), dark_from.count())); + }else{ + stream.log("[Story] run_into_door: timed out without detecting fade."); + } + return {.fade = end.fade, .banner = end.banner}; } - return ret == 0 || ret == 1; } // What the screen showed after a tap toward a door or a cave mouth. @@ -138,20 +174,59 @@ enum class TapLook{ BANNER, }; -// Looks for the location banner `banner` (and, if `dark_too`, the fade) -// for up to `wait`. -TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const std::string& banner, Milliseconds wait, bool dark_too){ - const WallClock deadline = current_time() + wait; +// The mean of r, g and b over the screen, 0 to 255; 255 with no frame. +double brightness_of(const VideoSnapshot& screen){ + return screen ? image_average(*screen.frame).sum() / 3 : 255; +} + +void keep_banner_frame(const ImageViewRGB32& frame, const std::string& folder, const std::string& banner){ + Filesystem::create_directories(Filesystem::Path(folder)); + frame.save(folder + now_to_filestring() + "-" + normalize_location_name(banner) + ".png"); +} +void log_new_banner_read(VideoStream& stream, const std::string& read, std::string& last_read, const std::string& banner, WallClock start){ + if (read.empty() || read == last_read){ + return; + } + stream.log(std::format("[Banner] read \"{}\" after {} ms, looking for \"{}\".", + read, std::chrono::duration_cast(current_time() - start).count(), banner)); + last_read = read; +} + +// Looks for the location banner `banner` for up to `wait`, and with +// `fade` for the fade, each frame to `fade`'s watch (TAP_FADE_RULE), which +// follows the taps from before the first. Logs each distinct banner read +// and how the wait ended: the Oreburgh Gate's entry missed its banner twice +// (lab-B, 2026-11-08 15:31 and 15:39) though a hand probe saw it 1.5 s +// after the fade, and nothing said why. +TapLook look_after_tap(VideoStream& stream, ProControllerContext& context, const std::string& banner, Milliseconds wait, WarpFadeWatch* fade){ + const WallClock start = current_time(); + const WallClock deadline = start + wait; + std::string last_read; + LocationBannerReads reads; + double darkest = 255; + // Every 500 ms of a long wait (the one after a fade) a frame goes to + // Screenshots/AutoStory/banner/, to see what the game showed. + const std::string folder = SCREENSHOTS_PATH() + "AutoStory/banner/"; + WallClock next_frame = start; while (true){ context.wait_for_all_requests(); const VideoSnapshot screen = stream.video().snapshot(); - if (screen && location_banner_matches(read_location_banner(*screen.frame), banner)){ + if (!fade && screen && current_time() >= next_frame){ + keep_banner_frame(*screen.frame, folder, banner); + next_frame += 500ms; + } + const std::string read = screen ? reads.read(*screen.frame, current_time()) : ""; + log_new_banner_read(stream, read, last_read, banner, start); + if (screen && location_banner_matches(read, banner)){ return TapLook::BANNER; } - if (dark_too && screen && image_average(*screen.frame).sum() / 3 < FADE_DARKNESS){ + darkest = std::min(darkest, brightness_of(screen)); + if (fade != nullptr && screen && fade->push(Pokemon::transition_sample(screen)) != WarpFade::NONE){ return TapLook::DARK; } if (current_time() >= deadline){ + stream.log(std::format("[Banner] no \"{}\" in {} ms; darkest frame {:.0f}, last read \"{}\".", + banner, wait.count(), darkest, last_read)); return TapLook::NOTHING; } context.wait_for(100ms); @@ -190,36 +265,51 @@ bool ConsoleStoryStepIO::run_until_map(Direction direction, Milliseconds limit, return walk.stop == WalkStop::ARRIVED; } -bool ConsoleStoryStepIO::run_into_door(Direction direction, bool run, Milliseconds timeout){ - return PokemonBDSP::run_into_door(m_stream, m_context, direction, run, timeout); +WarpSeen ConsoleStoryStepIO::run_into_door(Direction direction, bool run, Milliseconds timeout, Milliseconds dark_from, const std::string& banner){ + return PokemonBDSP::run_into_door(m_stream, m_context, direction, run, timeout, dark_from, banner); } // A held walk can carry on past a fade that goes unseen: out of the Gym it // walked on south (r219g), and through the Oreburgh Gate's west mouth on // west into a pocket by Route 203's pond (r75). Taps during the fade are -// eaten. +// eaten, so a fade ends the taps; the banner after it is evidence, not +// required (#268 slice 1). The watch starts before the first tap: a walk +// before that slid onto the warp unseen may have left its banner up +// (lab-B 2026-11-08 15:31). std::optional ConsoleStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ const std::string& banner = story_banner_name(map); + m_context.wait_for_all_requests(); + WarpFadeWatch watch(TAP_FADE_RULE); + if (look_after_tap(m_stream, m_context, banner, 0ms, &watch) == TapLook::BANNER){ + m_stream.log("[Banner] \"" + banner + "\" shows before the first tap: through already."); + return 0; + } for (size_t tap = 1; tap <= max_taps; tap++){ pbf_press_dpad(m_context, dpad_toward(direction), 160ms, 0ms); - TapLook look = look_after_tap(m_stream, m_context, banner, 1500ms, true); - const bool faded = look == TapLook::DARK; - if (faded){ - look = look_after_tap(m_stream, m_context, banner, 8000ms, false); + const TapLook look = look_after_tap(m_stream, m_context, banner, 1500ms, &watch); + if (look == TapLook::DARK){ + m_stream.log("[Banner] the fade: " + watch.how() + "."); } - if (look == TapLook::BANNER){ + if (look == TapLook::DARK && look_after_tap(m_stream, m_context, banner, 8000ms, nullptr) != TapLook::BANNER){ + m_stream.log("[Banner] a fade, no \"" + banner + "\" banner after it: counting the fade.", COLOR_ORANGE); + } + if (look != TapLook::NOTHING){ m_context.wait_for(1000ms); return tap; } - if (faded){ - break; - } } return std::nullopt; } -void ConsoleStoryStepIO::settle(Button button, const std::string& label, bool fade){ - PokemonBDSP::settle(m_stream, m_context, button, label, fade); +// One rule for scenes and map changes (talk_over()): press through the +// text, and keep pressing B while the screen is quiet, until the overworld +// is quiet. A step or scene that ends on another map (`fade`) must fade on +// the way, and only the quiet after the fade counts: r28 "went out" a tile +// beside the door and walked a whole route in the house. The far map's +// banner `banner`, if it has one, counts as the fade: a fade the run +// missed is over, but its banner comes after it (#268 slice 1). +void ConsoleStoryStepIO::settle(Button button, const std::string& label, bool fade, const std::string& banner){ + talk_over(m_stream, m_context, label, {.next = button, .rule = {.warp = fade}, .banner = banner}); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h index dd0f6b8a58..5abf30ba7e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h @@ -22,12 +22,24 @@ #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteIO.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Walk.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkResult.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkScreen.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonBDSP{ +// How a door run takes a warp's fade (WarpFadeWatch), on the console and +// the simulation alike: the partial tier's dark (a doorway's dim fade +// frames) held 50 ms, white held 60 ms, as its black and white watchers +// did (lab-B to 2026-11-08), or a fade whose hold it did not see, at the +// other scene after the fall. +constexpr WarpFadeRule DOOR_FADE_RULE{.partial_dark = true, .dark_for = Milliseconds(50), .white_for = Milliseconds(60)}; +// How a tap step, looking every 100 ms, takes one: the uniform tier at +// once, as fade_of() did, or a fade whose hold it did not see. +constexpr WarpFadeRule TAP_FADE_RULE{}; + + // Abstract interface for story step input/output operations. class StoryStepIO{ public: @@ -44,17 +56,25 @@ class StoryStepIO{ // Runs `direction` on the D-pad until the location banner of `map` (a // JSON map's name) shows, for at most `limit`. Returns whether it showed. virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string& label) = 0; - // Holds the D-pad toward a door (running with `run`) until the screen - // goes dark or a line shows. Returns whether it went dark. - virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000)) = 0; + // Holds the D-pad toward a door (running with `run`) for `timeout` until + // its fade (DOOR_FADE_RULE), `banner` (a map's banner name, "" for + // none) reads, or a line shows. A dark screen in the first `dark_from` + // of running is not the door's fade, and a wild battle on the way is + // fled, the run going on for the time left. Returns what it saw of the + // warp: the fade or the banner, either one alone (#268 slice 1). + virtual WarpSeen run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), + Milliseconds dark_from = Milliseconds(0), const std::string& banner = "") = 0; // D-pad taps `direction` one at a time, each looked at, toward a door - // or cave mouth, until the fade (then no more taps) and the location - // banner of `map` (a JSON map's name), for at most `max_taps`. Returns - // the taps it took, or nothing if no banner showed. + // or cave mouth, until its fade (TAP_FADE_RULE: uniform, so a dim cave + // floor is none) or the location banner of `map` (a JSON map's name), for at + // most `max_taps`; after a fade, no more taps. Either one alone is the + // way through. The watch starts before the first tap: a banner up then + // is 0 taps. Returns the taps it took, or nothing if neither showed. virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) = 0; // Presses through any text until the overworld is quiet; with `fade`, a - // fade must come first (a map change). Fails otherwise. - virtual void settle(Button button, const std::string& label, bool fade) = 0; + // warp must come first (a map change): a fade, or the banner `banner` + // ("" for a fade only). Fails otherwise. + virtual void settle(Button button, const std::string& label, bool fade, const std::string& banner) = 0; }; @@ -69,9 +89,10 @@ class ConsoleStoryStepIO : public StoryStepIO{ virtual void fight(const std::string& trainer) override; virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string& label) override; - virtual bool run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000)) override; + virtual WarpSeen run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), + Milliseconds dark_from = Milliseconds(0), const std::string& banner = "") override; virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) override; - virtual void settle(Button button, const std::string& label, bool fade) override; + virtual void settle(Button button, const std::string& label, bool fade, const std::string& banner) override; private: VideoStream& m_stream; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index 09f4e95ba9..a48158f2ca 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -5,13 +5,17 @@ */ #include +#include #include +#include #include #include #include #include +#include #include #include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Filesystem/FileIO.h" #include "Common/Cpp/TestRunners/UnitTest.h" #include "Pokemon/AutoStory/Pokemon_StoryEvents.h" #include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" @@ -22,10 +26,15 @@ #include "Data/PokemonBDSP_AutoStory_RobustRoute.h" #include "Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "Data/PokemonBDSP_AutoStory_StoryMaps.h" +#include "Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "Actions/PokemonBDSP_AutoStory_Events.h" #include "Data/PokemonBDSP_AutoStory_WalkRules.h" +#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_TableRoutes.h" #include "PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_StoryTable_Tests.h" +#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -42,10 +51,9 @@ using Pokemon::story_arg; // The actions each kind does itself, besides the story's events. const std::map>& built_in_actions(){ static const std::map> actions{ - {StoryStepKind::ROUTE, {"", "route", "town", "robust", "line"}}, - {StoryStepKind::LEGS, {"", "legs", "one_short_ok", "to_wall", "to_dialogue", "to_map", "counted_wall"}}, - {StoryStepKind::STEP, {"", "face", "to_banner", "tap"}}, - {StoryStepKind::MASH, {"", "a"}}, + {StoryStepKind::ROUTE, {"", "route", "town", "robust", "line", std::string(ROUTE_ONTO_TRIGGER), std::string(ROUTE_INTO_SCENE)}}, + {StoryStepKind::LEGS, {"", "legs", "one_short_ok", "to_wall", "to_dialogue", "to_map", "counted_wall", "measured"}}, + {StoryStepKind::STEP, {"", "face", "to_banner", "tap", "or_legs"}}, {StoryStepKind::MASH, {"", "a"}}, {StoryStepKind::BATTLE, {"", "fight", "doubles", "starter"}}, {StoryStepKind::TALK, {"", "talk_to_wanderer"}}, {StoryStepKind::SHOP, {"", "sandgem_potions"}}, @@ -231,6 +239,376 @@ UnitTestResult test_route204_north_line(Logger& logger){ return true; } +// 01.10's line 5, "north 10 (open)" to (19, 12), after Aroma Lady Taylor's +// battle (lab-B 2026-11-08 18:15:47): we may stand anywhere on (19, 12..20). +// Column 19 is open floor from row 7 to 13 below the wall on row 6, so north +// to that wall and 5 south reach the goal; the console's plan, "south 12 (to +// wall) to (19, 24), north 12 (open) to (19, 12)", pinned the wall with the +// fewest held tiles and walked back twice as far. +UnitTestResult test_line_5_recovery_pins_the_wall_nearest_the_goal(Logger& logger){ + const StoryWorld& world = *story_plan_world("Route204North", "Route204North"); + std::vector from; + for (int y = 12; y <= 20; y++){ + from.push_back(story_to_world(world, "Route204North", {19, y})); + } + const TilePos goal = story_to_world(world, "Route204North", {19, 12}); + const auto legs = plan_recovered_route(world, from, [&](const TilePos& pos){ return pos == goal; }, *story_route_costs("line")); + if (!legs || legs->empty()){ + return "no plan from (19, 12..20)."; + } + for (const PlannedLeg& planned : *legs){ + logger.log("01.10 line 5 recovery: " + to_string(planned)); + } + const PlannedLeg& first = legs->front(); + const TilePos wall = story_to_world(world, "Route204North", {19, 7}); + if (first.leg.direction != Direction::NORTH || !first.leg.ends_at_wall || first.after != std::vector{wall}){ + return "the recovery starts " + to_string(first) + ", not north to the wall at (19, 7)."; + } + return true; +} + +// Why `planned` may slide into a door or a warp, or "": an open leg (not to +// a wall) that may end on the tile before one, walking toward it. A part of +// a tile too far takes the warp (lab-B 2026-11-08 15:31 to 15:54: 01.05's +// open walk west to (2, 13), beside the Oreburgh Gate's mouth, slid into +// the Gate, and the tap after it waited for a banner already gone). The +// maps draw every warp as a door tile, cave mouths too. +std::string slides_into_door(const StoryWorld& world, const PlannedLeg& planned){ + if (planned.leg.ends_at_wall){ + return ""; + } + for (const TilePos& pos : planned.after){ + const TilePos ahead = pos.next(planned.leg.direction); + if (world.tile(ahead) == Pokemon::TileKind::DOOR){ + return std::format("the open leg {} may end on {}, the tile before the door {}", + to_string(planned.leg), describe(world, pos), describe(world, ahead)); + } + } + return ""; +} + +// A ROUTE step of the table from a known place: the world it plans on and +// its plan, or nothing if it finds none. +struct PlannedStoryRoute{ + std::string name; // " " + const StoryWorld* world; + std::vector from; + std::optional> legs; +}; + +// Every ROUTE step of the table that starts from a known place, planned as +// walk_route() plans it. Where a row's steps leave the player is followed +// from its start through each step's target or pose_after; a route from an +// unknown place is logged, not planned. +std::vector plan_story_routes(Logger& logger){ + std::vector routes; + for (const TableRoute& route : table_routes()){ + if (route.world == nullptr){ + logger.log(std::format("{} {}: not checked, from {}.", route.row, route.step->name, + route.from ? Pokemon::to_string(*route.from) : "nowhere known")); + continue; + } + RouteStepPlan plan = plan_table_route(route); + routes.push_back({route.row + " " + route.step->name, route.world, std::move(plan.start), std::move(plan.legs)}); + } + return routes; +} + +// No ROUTE step of the table plans an open leg that ends before a door it +// walks toward: a door is gone through by a step that runs or taps into it +// from where the route ends on a wall or off its line. +UnitTestResult test_story_routes_stop_short_of_doors(Logger& logger){ + std::vector found; + size_t checked = 0; + for (const PlannedStoryRoute& route : plan_story_routes(logger)){ + checked += route.legs ? 1 : 0; + for (const PlannedLeg& planned : route.legs ? *route.legs : std::vector{}){ + const std::string why = slides_into_door(*route.world, planned); + if (!why.empty()){ + found.push_back(std::format("{}: {}.", route.name, why)); + } + } + } + logger.log(std::format("{} routes planned.", checked)); + std::string out; + for (const std::string& line : found){ + out += "\n " + line; + } + return found.empty() ? UnitTestResult(true) : UnitTestResult("Open legs that end before a door they walk toward:" + out); +} + +// The tiles a planned leg walks over from `from`, `from` first: to the wall, +// or its tiles' worth of steps. +std::vector walked_tiles(const StoryWorld& world, const TilePos& from, const TileLeg& leg){ + std::vector tiles{from}; + size_t walked = 0; + while (leg.ends_at_wall || walked < leg.tiles){ + const std::optional next = step(world, tiles.back(), leg.direction); + if (!next){ + break; + } + walked += (size_t)(std::abs(next->x - tiles.back().x) + std::abs(next->y - tiles.back().y)); + tiles.push_back(*next); + } + return tiles; +} + +// The most tiles of `zone` one leg of `legs` walks over, from any tile the +// player may be on, and that leg. +std::pair most_zone_tiles( + const StoryWorld& world, std::vector from, const std::vector& legs, + const std::function& zone +){ + std::pair most{0, ""}; + for (const PlannedLeg& planned : legs){ + for (const TilePos& pos : from){ + const std::vector tiles = walked_tiles(world, pos, planned.leg); + const size_t in_zone = (size_t)std::count_if(tiles.begin(), tiles.end(), zone); + if (in_zone > most.first){ + most = {in_zone, to_string(planned.leg) + " from " + describe(world, pos)}; + } + } + from = planned.after; + } + return most; +} + +// Where a planned leg from `from` runs along a zone where someone wanders, +// or "": two zone tiles in a row on a straight leg are tiles of one zone. +std::string along_wander_zone(const StoryWorld& world, const TilePos& from, const TileLeg& leg){ + const std::vector tiles = walked_tiles(world, from, leg); + for (size_t i = 1; i < tiles.size(); i++){ + if (wandering_hazard(world, tiles[i - 1]) && wandering_hazard(world, tiles[i])){ + return std::format("{} from {} runs along a wander zone at {}", to_string(leg), describe(world, from), describe(world, tiles[i])); + } + } + return ""; +} + +// Every ROUTE step of the table from a known place has a plan, and no leg +// of it runs along a zone where someone wanders: plan_robust_route() never +// plans one, so a step with no other way finds no plan here. +UnitTestResult test_story_routes_keep_off_wander_zones(Logger& logger){ + std::string out; + for (const PlannedStoryRoute& route : plan_story_routes(logger)){ + if (!route.legs){ + out += "\n " + route.name + ": no plan."; + continue; + } + std::vector from = route.from; + for (const PlannedLeg& planned : *route.legs){ + for (const TilePos& pos : from){ + const std::string along = along_wander_zone(*route.world, pos, planned.leg); + out += along.empty() ? "" : "\n " + route.name + ": " + along + "."; + } + from = planned.after; + } + } + return out.empty() ? UnitTestResult(true) : UnitTestResult("ROUTE steps:" + out); +} + +// 01.08's walk below the Ravaged Path keeps off the row Route 204 South's +// youngster_3 wanders, (12, 2) to (14, 2): on lab-B (2026-11-08) the plan +// "north 35 (to wall) to (13, 2), west 2 (to wall) to (11, 2)" walked along +// it, and he stopped the leg west twice. A leg may cross his row through +// one of his tiles, not walk two of them. +UnitTestResult test_ravaged_path_keeps_off_the_youngster(Logger& logger){ + for (const PlannedStoryRoute& route : plan_story_routes(logger)){ + if (route.name != "01.08 below_the_ravaged_path"){ + continue; + } + if (!route.legs){ + return "01.08 below_the_ravaged_path: no plan."; + } + const StoryWorld& world = *route.world; + for (const PlannedLeg& planned : *route.legs){ + logger.log("01.08 below_the_ravaged_path: " + to_string(planned)); + } + const auto youngster_row = [&](const TilePos& pos){ + const std::optional local = story_to_local(world, "Route204South", pos); + return local && local->y == 2 && local->x >= 12 && local->x <= 14; + }; + const auto [most, leg] = most_zone_tiles(world, route.from, *route.legs, youngster_row); + if (most >= 2){ + return std::format("the leg {} walks {} tiles of the youngster's row (12..14, 2).", leg, most); + } + return true; + } + return "01.08 below_the_ravaged_path is not a ROUTE step from a known place."; +} + + +// The route plan dump: every table ROUTE step's legs, in a golden file +// beside the story data, so a planner or table change shows its plans' diff +// in review. + +constexpr std::string_view ROUTE_PLANS_HEADER = + "BDSP AutoStory: the legs each ROUTE step of the story table plans.\n" + "Planned as the console's RouteWalker plans them: plan_recovered_route() on\n" + "story_plan_world(), from the tiles the row's steps before it leave the\n" + "player on, with the step's costs, then the default costs if those find none.\n" + "Written by the StoryTable test \"every ROUTE step plans as\n" + "Data/route_plans.golden.txt says\". After a planner or table change, run\n" + "that test with PA_UPDATE_ROUTE_PLANS=1 to rewrite this file\n" + "(PA_ROUTE_PLANS_GOLDEN= reads or writes another copy), and review\n" + "its diff.\n" + "turns: direction changes between legs. open: legs that stop in the open\n" + "(tapped, not held to a wall). localization: the wall holds at the start\n" + "that only bring several start tiles to one (plan_recovered_route()'s\n" + "anchor); 0 from one start tile.\n"; + +std::string tile_list(const StoryWorld& world, const std::vector& tiles){ + std::string out; + for (const TilePos& pos : tiles){ + out += (out.empty() ? "" : ", ") + describe(world, pos); + } + return out; +} + +// plan_recovered_route()'s wall holds from several start tiles: the legs up +// to where the tiles the player may be on first become one. +size_t localization_legs(const std::vector& start, const std::vector& legs){ + if (start.size() < 2){ + return 0; + } + for (size_t i = 0; i < legs.size(); i++){ + if (legs[i].after.size() == 1){ + return i + 1; + } + } + return 0; +} + +std::string plan_totals(const RouteStepPlan& plan){ + const std::vector& legs = *plan.legs; + size_t turns = 0; + size_t open = 0; + for (size_t i = 0; i < legs.size(); i++){ + turns += i > 0 && legs[i].leg.direction != legs[i - 1].leg.direction ? 1 : 0; + open += legs[i].leg.ends_at_wall ? 0 : 1; + } + return std::format(" totals: {} legs, {} turns, {} open, {} localization\n", + legs.size(), turns, open, localization_legs(plan.start, legs)); +} + +std::string dump_plan(const StoryWorld& world, const RouteStepPlan& plan){ + std::string out = " start candidates: " + tile_list(world, plan.start) + "\n"; + if (!plan.legs){ + return out + " NO PLAN\n"; + } + if (plan.default_costs){ + out += " the step's costs found no plan; planned with the default costs\n"; + } + for (size_t i = 0; i < plan.legs->size(); i++){ + const PlannedLeg& planned = (*plan.legs)[i]; + out += std::format(" {}. {} -> {}\n", i + 1, to_string(planned.leg), tile_list(world, planned.after)); + } + return out + plan_totals(plan); +} + +std::string dump_route(const TableRoute& route){ + const Pokemon::StoryStep& step = *route.step; + std::string out = std::format("== {} {} (costs: {})\n", route.row, step.name, step.action.empty() ? "route" : step.action); + out += " from: " + (route.from ? Pokemon::to_string(*route.from) : std::string("unknown")) + "\n"; + const Pokemon::Pose target = Pokemon::pose_of(story_arg(step.args, "target")); + out += " target: " + Pokemon::to_string(target) + "\n"; + if (route.world == nullptr){ + return out + (route.from && !Pokemon::tiles_of(*route.from).empty() + ? " not planned: no story world joins the two maps\n" + : " not planned: the start is unknown (a LEGS or STEP step before it does not say where it ends)\n"); + } + return out + dump_plan(*route.world, plan_table_route(route)); +} + +std::string route_plans_text(){ + std::string out = std::string(ROUTE_PLANS_HEADER); + for (const TableRoute& route : table_routes()){ + out += "\n" + dump_route(route); + } + return out; +} + +// The golden file, in the Data folder beside this file's. +std::string route_plans_golden_path(){ + // code-health: allow char_pointer -- std::getenv returns a const char pointer + const char* path = std::getenv("PA_ROUTE_PLANS_GOLDEN"); + if (path != nullptr && path[0] != '\0'){ + return path; + } + const std::string self = __FILE__; + const size_t slash = self.find_last_of("/\\"); + return (slash == std::string::npos ? std::string() : self.substr(0, slash + 1)) + "Data/route_plans.golden.txt"; +} + +// `text` without carriage returns or a byte order mark. +std::string plain_lines(const std::string& text){ + std::string out = text.starts_with("\xef\xbb\xbf") ? text.substr(3) : text; + std::erase(out, '\r'); + return out; +} + +// `text` split into the header and one block per "== " step line. +std::vector plan_blocks(const std::string& text){ + std::vector blocks{""}; + size_t begin = 0; + while (begin < text.size()){ + const size_t end = std::min(text.find('\n', begin), text.size() - 1) + 1; + const std::string line = text.substr(begin, end - begin); + if (line.starts_with("== ")){ + blocks.push_back(""); + } + blocks.back() += line; + begin = end; + } + return blocks; +} + +// Each step whose block changed, as "-" (golden) and "+" (planned) blocks. +std::string plan_differences(const std::string& golden, const std::string& planned){ + const std::vector expected = plan_blocks(golden); + const std::vector actual = plan_blocks(planned); + std::string out; + size_t changed = 0; + for (size_t i = 0; i < std::max(expected.size(), actual.size()); i++){ + const std::string& was = i < expected.size() ? expected[i] : ""; + const std::string& now = i < actual.size() ? actual[i] : ""; + if (was != now && changed++ < 5){ + out += "\n--- golden:\n" + was + "+++ planned:\n" + now; + } + } + return changed == 0 ? "" : std::format("{} block(s) differ, the first ones:{}", changed, out); +} + +// Every table ROUTE step plans the legs the golden file lists. +UnitTestResult test_route_plans_golden(Logger& logger){ + const std::string path = route_plans_golden_path(); + const std::string planned = route_plans_text(); + // code-health: allow char_pointer -- std::getenv returns a const char pointer + const char* update = std::getenv("PA_UPDATE_ROUTE_PLANS"); + if (update != nullptr && update[0] != '\0' && update[0] != '0'){ + std::string crlf; + for (char ch : planned){ + crlf += ch == '\n' ? std::string("\r\n") : std::string(1, ch); + } + FileIO file; + if (!file.open(path, FileMode::WRITE | FileMode::BINARY) || file.write(crlf) != crlf.size()){ + return "Could not write " + path + "."; + } + logger.log("Wrote " + path + "."); + return true; + } + std::string golden; + if (!file_to_string(path, golden)){ + return "Could not read " + path + " (set PA_ROUTE_PLANS_GOLDEN to its path)."; + } + const std::string differences = plan_differences(plain_lines(golden), planned); + if (differences.empty()){ + return true; + } + return "The route plans differ from " + path + ". If the change is meant, rerun with PA_UPDATE_ROUTE_PLANS=1 " + "and review the file's diff. " + differences; +} + struct AutoStoryStoryTableInput{ std::string name; @@ -283,6 +661,26 @@ const AutoStoryStoryTableCase AUTO_STORY_STORY_TABLE_CASES[] = { .input = {"Route 204 North: the line into Floaroma", test_route204_north_line}, .expectation = {}, }, + { + .input = {"01.10: line 5's recovery pins the wall nearest its goal (lab-B, 2026-11-08)", test_line_5_recovery_pins_the_wall_nearest_the_goal}, + .expectation = {}, + }, + { + .input = {"Story table: no open leg ends before a door it walks toward (lab-B, 2026-11-08)", test_story_routes_stop_short_of_doors}, + .expectation = {}, + }, + { + .input = {"Story table: every ROUTE step plans as Data/route_plans.golden.txt says", test_route_plans_golden}, + .expectation = {}, + }, + { + .input = {"Story table: every route plans, and none runs along a wander zone", test_story_routes_keep_off_wander_zones}, + .expectation = {}, + }, + { + .input = {"01.08: the walk below the Ravaged Path keeps off the youngster's row (lab-B, 2026-11-08)", test_ravaged_path_keeps_off_the_youngster}, + .expectation = {}, + }, }; void add_tests_AutoStory_StoryTable(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp index ecf0c0fac6..2f70e26a01 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.cpp @@ -6,22 +6,29 @@ #include #include +#include +#include #include "Common/Cpp/Color.h" #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Pokemon/Navigation/Pokemon_LegTrace.h" #include "Pokemon/Navigation/Pokemon_MapData.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RobustRoute.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TrainerSight.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_CountedWallLeg.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkDpad.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkResult.h" #include "PokemonBDSP_AutoStory_StoryExecutor.h" #include "PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_StoryWalkSteps.h" -#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" #include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" #include "Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h" @@ -40,6 +47,44 @@ using Pokemon::StoryStep; using Pokemon::TilePos; +namespace{ + +// The leg records of a step: its legs are this event's, and one still +// open when the step ends is written with its end unknown. +class EventTrace{ +public: + EventTrace(Pokemon::LegTracer& legs, const std::string& row, const std::string& step) + : m_legs(legs) + { + m_legs.begin_event(row, step); + } + ~EventTrace(){ + try{ + m_legs.end_event(); + }catch (...){} + } + EventTrace(const EventTrace&) = delete; + EventTrace& operator=(const EventTrace&) = delete; + +private: + Pokemon::LegTracer& m_legs; +}; + +// `tiles` of `map` as the route lines name them: by the story world's +// map names, where the map has a world. +std::vector traced_tiles(const std::string& map, const std::vector& tiles){ + const StoryWorld* world = story_plan_world(map, map); + std::vector out; + for (const TilePos& pos : tiles){ + const std::optional local = world == nullptr ? std::nullopt : world->to_local(story_to_world(*world, map, pos)); + out.push_back(local ? Pokemon::RouteTile{local->map, local->pos} : Pokemon::RouteTile{map, pos}); + } + return out; +} + +} // namespace + + namespace{ // "to_catch_grass" as "to catch grass", for the logs. @@ -55,29 +100,117 @@ std::string label_of(const StoryStep& step){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "RouteIO::note() returned from a failure: " + message); } +// A trainer every pass of a row fights, by that row. +struct FoughtTrainer{ + std::string_view row; + std::string_view name; +}; +// 01.02's walk east along Route 203's row 18 crosses his sight down +// column 31 (route_203_trainer_sights()). +const FoughtTrainer FOUGHT_TRAINERS[] = { + {"01.02", "Youngster (above row 18)"}, +}; + } // namespace -void StoryWalkSteps::begin_attempt(const std::string& row){ +std::vector row_trainers(const StoryWorld& world, const std::string& row){ + std::vector sights = story_trainers(world); + std::erase_if(sights, [&row](const TrainerSight& sight){ + return std::any_of(std::begin(FOUGHT_TRAINERS), std::end(FOUGHT_TRAINERS), [&](const FoughtTrainer& fought){ + return row > std::string(fought.row) && sight.name == fought.name; + }); + }); + return sights; +} + +CenterEntry run_into_center( + StoryStepIO& io, bool run, + const std::function& inside, const std::function& line_up, + const std::string& label +){ + if (io.run_into_door(Direction::NORTH, run).any()){ + io.settle(BUTTON_B, label + ": into the Center", false, ""); + return CenterEntry::FADED; + } + if (inside()){ + return CenterEntry::INSIDE; + } + line_up(); + return CenterEntry::LINED_UP; +} + +TappedEnd tapped_end(const StoryWorld& world, const std::string& map, const TilePos& pos, const Pokemon::StoryLeg& leg){ + const size_t open = slide_to_wall(world, story_to_world(world, map, pos), leg.direction).tiles; + TappedEnd tapped{.end = pos, .moved = std::min(open, (size_t)leg.tiles)}; + for (size_t i = 0; i < tapped.moved; i++){ + tapped.end = tapped.end.next(leg.direction); + } + return tapped; +} + +std::optional measured_ends(const Pose& from, const StoryStep& step){ + const StoryWorld* world = story_plan_world(from.map, from.map); + const auto& legs_list = story_arg>(step.args, "legs"); + if (world == nullptr || legs_list.empty()){ + return std::nullopt; + } + std::vector at = Pokemon::tiles_of(from); + for (const Pokemon::StoryLeg& leg : legs_list){ + std::vector next; + for (const TilePos& pos : at){ + const TilePos end = tapped_end(*world, from.map, pos, leg).end; + if (std::find(next.begin(), next.end(), end) == next.end()){ + next.push_back(end); + } + } + at = std::move(next); + } + return Pokemon::tile_pose(from.map, at, legs_list.back().direction); +} + +void StoryWalkSteps::begin_attempt(const std::string& row, const std::vector& steps){ m_row = row; // A row starts from its save: after the shoes' row, the save has them. m_can_run = row > std::string(RUNNING_SHOES_ROW); m_trainers.clear(); + m_warp = {}; + m_scene_next.clear(); + m_scene_open = false; + // A route right before a scene, or before a plain step onto the scene's + // trigger (the decomp's tile, which the console may have elsewhere). + const auto onto_trigger = [](const StoryStep& step){ + return step.kind == Pokemon::StoryStepKind::STEP && step.action.empty() && !step.pose_after; + }; + const auto route = [](const StoryStep& step){ + return step.kind == Pokemon::StoryStepKind::ROUTE; + }; + for (size_t c = 1; c < steps.size(); c++){ + if (steps[c].kind != Pokemon::StoryStepKind::MASH){ + continue; + } + if (route(steps[c - 1])){ + m_scene_next.insert(steps[c - 1].name); + } + if (c >= 2 && onto_trigger(steps[c - 1]) && route(steps[c - 2])){ + m_scene_next.insert(steps[c - 2].name); + } + } } void StoryWalkSteps::turn(Direction direction){ - m_io.route().note(std::string("[Route] Turning ") + direction_name(direction) + ".", RouteNote::LOG); - m_io.route().press(route_turn_tap(direction)); + m_route.note(std::string("[Route] Turning ") + direction_name(direction) + ".", RouteNote::LOG); + m_route.press(route_turn_tap(direction)); } void StoryWalkSteps::log(const std::string& text){ - m_io.route().note(text, RouteNote::LOG); + m_route.note(text, RouteNote::LOG); } Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep& step){ const StoryWorld* maps = story_plan_world(from.map, goal.map); if (maps == nullptr){ - fail(m_io.route(), std::format("{}: no maps join {} and {}.", step.name, from.map, goal.map)); + fail(m_route, std::format("{}: no maps join {} and {}.", step.name, from.map, goal.map)); } const std::optional costs = story_route_costs(step.action); if (!costs){ @@ -92,22 +225,25 @@ Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep targets.push_back(story_to_world(*maps, goal.map, pos)); } // The ones fought stay off m_trainers until the next attempt. - std::vector& sights = m_trainers.try_emplace(maps, story_trainers(*maps)).first->second; + std::vector& sights = m_trainers.try_emplace(maps, row_trainers(*maps, m_row)).first->second; RouteTrainers trainers{ sights, [this](const std::string& trainer){ m_io.fight(trainer); } }; const RouteWalkPlan plan{ [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }, - label_of(step), {}, *costs, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK + label_of(step), {}, *costs, m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK, m_scene_next.contains(step.name), + step.action == ROUTE_ONTO_TRIGGER, }; - const std::vector at = walk_route(m_io.route(), *maps, start, trainers, plan); + RouteEnd end = walk_route_to_warp(m_route, *maps, start, trainers, plan); sights = std::move(trainers.sights); + m_warp = std::move(end.warp); + m_scene_open = end.scene; std::vector local; - for (const TilePos& pos : at){ + for (const TilePos& pos : end.tiles){ const std::optional tile = story_to_local(*maps, goal.map, pos); if (!tile){ - fail(m_io.route(), std::format("{}: the walk ended off {}.", step.name, goal.map)); + fail(m_route, std::format("{}: the walk ended off {}.", step.name, goal.map)); } local.push_back(*tile); } @@ -115,34 +251,51 @@ Pose StoryWalkSteps::walk_to(const Pose& from, const Pose& goal, const StoryStep } Outcome StoryWalkSteps::route(RunState& state, const StoryStep& step){ + const EventTrace trace(m_legs, m_row, step.name); + m_warp = {}; if (Pokemon::tiles_of(state.pose).empty()){ return Pokemon::outcome_failed("no_pose", Pokemon::to_string(state.pose)); } const GridPose& target = story_arg(step.args, "target"); - return Pokemon::outcome_ok(walk_to(state.pose, Pokemon::pose_of(target), step)); + const Pose end = walk_to(state.pose, Pokemon::pose_of(target), step); + const auto legs_list = step.args.contains("legs") ? story_arg>(step.args, "legs") : std::vector{}; + // The next step's scene started on the way: its step plays it. + if (legs_list.empty() || m_scene_open){ + return Pokemon::outcome_ok(end); + } + return run_to_dialogue(step); } -// A LEGS step "to_dialogue": taps its one leg until a dialogue starts on the -// way, wherever it starts (Dawn's at Sandgem's edge, r35/r36: an exact tile -// and banner raced her scene). The scene's lines are the next step's. -Outcome StoryWalkSteps::leg_to_dialogue(const StoryStep& step){ +// The run of a ROUTE step with a leg, after its route: on toward the leg's +// direction until a dialogue starts, wherever on the run it starts (a +// scene's trigger: r35/r36 raced Dawn's to an exact tile and banner), for +// the leg's tiles at most. A wild battle on the way is run from and the run +// goes on. No dialogue fails the step. The scene's lines are the next step's. +// The leg's tiles are timed at the slowest pace of the player's speed (a +// walk before the Running Shoes): a run past the trigger's tile is ended by +// its dialogue anyway, where one cut short fails (lab-B 2026-11-09, 00.03). +Outcome StoryWalkSteps::run_to_dialogue(const StoryStep& step){ const auto& legs_list = story_arg>(step.args, "legs"); const Pokemon::StoryLeg& leg = legs_list.front(); - turn(leg.direction); - const WalkResult walk = m_io.route().walk_taps(leg.direction, (size_t)leg.tiles, step.name); - if (walk.wild_battles > 0){ - return Pokemon::outcome_failed("interrupted_dialogue_approach", step.name); - } - log(std::format("[{}] {}: taps {} to a dialogue: {} tiles, {}.", m_row, step.name, direction_name(leg.direction), walk.moved_chunks, walk_stop_name(walk.stop))); + const MoveSpeed speed = m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK; + m_legs.begin_leg({.direction = leg.direction, .tiles = (size_t)leg.tiles, .end_kind = Pokemon::LegEndKind::OPEN}); + const WalkResult walk = m_route.walk_to_wall({ + .direction = leg.direction, + .limit = route_limit_for_tiles(speed, leg.tiles), + .label = label_of(step), + .options = {.arrived = nullptr, .pace = m_can_run ? DpadPace::RUN : DpadPace::WALK}, + }); + log(std::format("[{}] {}: ran {} to a dialogue: {} moved chunks, {} tiles at most, {}, {} wild battle(s).", m_row, step.name, + direction_name(leg.direction), walk.moved_chunks, leg.tiles, walk_stop_name(walk.stop), walk.wild_battles)); + m_legs.end_leg({}, walk.stop == WalkStop::DIALOG ? Pokemon::LegEndKnown::DIALOGUE : Pokemon::LegEndKnown::UNKNOWN); if (walk.stop == WalkStop::DIALOG){ return Pokemon::outcome_ok(); } - // A scene can lock us before its first line: Dawn walks over first (r37), - // or Mom walks over to us on the mat (r7). - if (m_io.route().dialog_within(10000ms, COLOR_CYAN)){ + // A scene can lock us before its first line: Dawn walks over first (r37). + if (m_route.dialog_within(10000ms, COLOR_CYAN)){ return Pokemon::outcome_ok(); } - return Pokemon::outcome_failed("no_dialogue", step.name); + return Pokemon::outcome_failed("no_dialogue", std::format("{}: no dialogue in {} tiles {}", step.name, leg.tiles, direction_name(leg.direction))); } // A LEGS step "to_map": runs its one leg until the location banner of @@ -157,22 +310,119 @@ Outcome StoryWalkSteps::leg_to_map(const StoryStep& step){ return arrived ? Pokemon::outcome_ok() : Pokemon::outcome_failed("no_banner", map); } +namespace{ +// Taps toward a door with no table door ahead of it. +constexpr size_t TAPS_TO_BANNER = 30; +// How many taps `direction` a tap step from `from` takes at most: the +// tiles to the door its map has ahead of every tile of `from`, and two +// more; TAPS_TO_BANNER where the map has none. A step through already, +// its banner gone, then stops a few tiles on (lab-B 2026-11-08: 01.05's +// walk slid into the Oreburgh Gate, whose row 22 runs 24 tiles on). +size_t taps_to_banner(const Pose& from, Direction direction){ + size_t most = 0; + try{ + const Pokemon::MapData& map = story_map(from.map); + for (const TilePos& pos : Pokemon::tiles_of(from)){ + const size_t tiles = Pokemon::tiles_to_door(map, pos, direction); + TilePos door = pos; + for (size_t i = 0; i < tiles; i++){ + door = door.next(direction); + } + if (tiles == 0 || map.tiles.at(door) != Pokemon::TileKind::DOOR){ + return TAPS_TO_BANNER; + } + most = std::max(most, tiles); + } + }catch (...){ + return TAPS_TO_BANNER; + } + return most == 0 ? TAPS_TO_BANNER : most + 2; +} +} // namespace + // A STEP "to_banner": D-pad taps toward a door or cave mouth until the fade // and pose_after's map's location banner. No banner fails the step right -// there. -Outcome StoryWalkSteps::tap_to_banner(const StoryStep& step){ - const std::string map = step.pose_after ? Pokemon::grid_pose_of(*step.pose_after).map : ""; +// there; a banner before any tap means the walk before took us through. +Outcome StoryWalkSteps::tap_to_banner(const Pose& from, const StoryStep& step){ const Direction direction = story_arg(step.args, "direction"); - const std::optional taps = m_io.tap_to_banner(direction, map, 30); + const std::string map = step.pose_after ? Pokemon::grid_pose_of(*step.pose_after).map : ""; + if (through_already(step)){ + return Pokemon::outcome_ok(); + } + const size_t limit = taps_to_banner(from, direction); + const std::optional taps = m_io.tap_to_banner(direction, map, limit); if (!taps){ - return Pokemon::outcome_failed("no_banner", map); + return Pokemon::outcome_failed("no_banner", std::format("no fade and no {} banner in {} taps {}", + map, limit, direction_name(direction))); + } + if (*taps == 0){ + log(std::format("[{}] {}: {}'s banner before any tap: through already.", m_row, step.name, map)); + }else{ + log(std::format("[{}] {}: through to {} after {} taps {}.", m_row, step.name, map, *taps, direction_name(direction))); } - log(std::format("[{}] {}: {}'s banner after {} taps {}.", m_row, step.name, map, *taps, direction_name(direction))); return Pokemon::outcome_ok(); } +// A STEP "or_legs" whose run into the door saw nothing (`seen`): the run +// stopped beside the door's column, against the wall it is in. The step's +// legs, a tap a tile, put us on the door's tile, then the run goes again +// (00.03: from (5, 10) east onto the mat (6, 10), then south). A tap onto +// the tile that is itself the way through ends it. `seen` itself for +// another variant, or when the run saw the warp. +WarpSeen StoryWalkSteps::door_from_beside(const StoryStep& step, const WarpSeen& seen, Milliseconds timeout, const std::string& banner){ + if (seen.any() || step.action != "or_legs"){ + return seen; + } + const auto& legs_list = story_arg>(step.args, "legs"); + for (const Pokemon::StoryLeg& leg : legs_list){ + turn(leg.direction); + const WalkResult walk = m_route.walk_taps(leg.direction, (size_t)leg.tiles, step.name); + log(std::format("[{}] {}: no fade; {} {} taps {}, {}.", m_row, step.name, leg.tiles, + direction_name(leg.direction), walk.moved_chunks, walk_stop_name(walk.stop))); + if (walk.warp.any()){ + return walk.warp; + } + } + const Direction direction = story_arg(step.args, "direction"); + const WarpSeen again = m_io.run_into_door(direction, m_can_run, timeout, Milliseconds(0), banner); + log(std::format("[{}] {}: {} through the door again: {}.", m_row, step.name, + direction_name(direction), again.any() ? describe(again) : "nothing yet")); + return again; +} + +// The route before ran on through this step's warp (walk_route_to_warp()): +// the step is done, unless the banner it read names another map. +bool StoryWalkSteps::through_already(const StoryStep& step){ + const WarpSeen through = std::exchange(m_warp, {}); + if (!through.any()){ + return false; + } + const std::string map = step.pose_after ? Pokemon::grid_pose_of(*step.pose_after).map : ""; + if (!through.banner.empty() && !location_banner_matches(through.banner, story_banner_name(map))){ + fail(m_route, std::format("{}: the walk before went through a warp to \"{}\", not {}.", step.name, through.banner, map)); + } + log(std::format("[{}] {}: through already; the walk before saw {}.", m_row, step.name, describe(through))); + return true; +} + namespace{ -Milliseconds door_timeout(const std::string& map_name, const Pose& pose, Direction direction, bool can_run){ +// A run into a door: how long to hold, and for how long of it a dark screen +// is not yet the door's fade (run_into_door()). +struct DoorRun{ + Milliseconds timeout; + Milliseconds dark_from; +}; +// Dark before this share of the run's time to the door is not the door: +// lab-B 2026-11-08 09:27:33 read dark at 1.8 s of the 4050 ms run down the +// mine's entrance hall (3250 ms to the mouth), stopped there, and the next +// step walked on through the mouth. +constexpr double DOOR_DARK_FROM_SHARE = 0.85; +// The shortest hold: the one-tile step onto the mine's warp faded 3.35 s +// after its hold began (lab-B 2026-11-07 12:19 and 12:27); a 1500 ms hold +// gave up just before the fade (2026-11-08 09:27:16) and settle() pressed B +// 15 s before it called the overworld calm. +constexpr Milliseconds DOOR_MIN_HOLD = 4500ms; +DoorRun door_run(const std::string& map_name, const Pose& pose, Direction direction, bool can_run){ try{ const Pokemon::MapData& map = story_map(map_name); const auto tiles_list = Pokemon::tiles_of(pose); @@ -180,11 +430,15 @@ Milliseconds door_timeout(const std::string& map_name, const Pose& pose, Directi const size_t tiles = Pokemon::tiles_to_door(map, tiles_list.front(), direction); if (tiles > 0){ const Milliseconds per_tile = route_ms_per_tile(direction, can_run ? MoveSpeed::RUN : MoveSpeed::WALK); - return std::max(1500ms, ROUTE_START_DELAY + per_tile * (int64_t)tiles + 800ms); + const Milliseconds to_door = ROUTE_START_DELAY + per_tile * (int64_t)tiles; + return { + .timeout = std::max(DOOR_MIN_HOLD, to_door + 800ms), + .dark_from = std::chrono::duration_cast(to_door * DOOR_DARK_FROM_SHARE), + }; } } }catch (...){} - return Milliseconds(12000); + return {.timeout = 12000ms, .dark_from = 0ms}; } enum class CountedEndPolicy{ EXACT, ONE_SHORT }; std::vector counted_ends(const std::vector& starts, const Pokemon::StoryLeg& leg, CountedEndPolicy policy){ @@ -203,98 +457,200 @@ std::vector counted_ends(const std::vector& starts, const Poke } // namespace Pose StoryWalkSteps::recover_tapped_leg(const Pose& from, const std::vector& starts, - const std::vector& goals, const Pokemon::StoryLeg& leg, const StoryStep& step){ + const std::vector& goals, Direction facing, const Pokemon::StoryLeg& leg, const StoryStep& step, + const std::optional& moved){ const StoryWorld* world = story_plan_world(from.map, from.map); if (world == nullptr){ - fail(m_io.route(), "interrupted leg has no recovery world: " + from.map); + fail(m_route, "interrupted leg has no recovery world: " + from.map); } std::vector global; for (const TilePos& at : starts){ global.push_back(story_to_world(*world, from.map, at)); } std::vector possible; - for (const TilePos& at : interrupted_leg_positions(*world, global, leg.direction, (size_t)leg.tiles)){ + // Placed by the leg's screen events: a tile or so from where the taps + // left us. Else anywhere along the leg. + const std::vector along = moved + ? tiles_moved(*world, global, leg.direction, *moved) + : interrupted_leg_positions(*world, global, leg.direction, (size_t)leg.tiles); + for (const TilePos& at : along){ const auto local = story_to_local(*world, from.map, at); if (!local){ - fail(m_io.route(), "interrupted leg crossed an unconfirmed map transition"); + fail(m_route, "interrupted leg crossed an unconfirmed map transition"); } possible.push_back(*local); } StoryStep recovery = step; recovery.name += "_recovery"; recovery.action.clear(); - const Pose found = walk_to(Pokemon::tile_pose(from.map, possible), Pokemon::tile_pose(from.map, goals, leg.direction), recovery); + const Pose found = walk_to(Pokemon::tile_pose(from.map, possible), Pokemon::tile_pose(from.map, goals, facing), recovery); // The route back can approach from another direction. Establish the - // original leg's facing before publishing that pose to the story runner. - turn(leg.direction); + // step's facing before publishing that pose to the story runner. + turn(facing); return found; } // Counted legs retain their normal path. An observed encounter invalidates -// the exact pose; localize from every legal prefix before the next leg. +// the exact pose; localize from every legal prefix and re-plan to the end of +// the step, skipping the legs left. A battle that may have begun before +// the leg (WalkOrigin::MAY_PRECEDE_LEG) found us on the tile the leg before +// ended on, since a battle starts on a tile stepped onto: the same prefixes +// hold. A re-plan to the end of the interrupted +// leg ended on an open tile, its last leg overshot a row, and the taps after +// went on a row off (lab-B 2026-11-08 11:55); a step that ends in a corner +// ends its re-plan on wall clips. Outcome StoryWalkSteps::tap_legs(const Pose& from, const StoryStep& step){ - const bool one_short_ok = step.action == "one_short_ok"; + const CountedEndPolicy policy = step.action == "one_short_ok" ? CountedEndPolicy::ONE_SHORT : CountedEndPolicy::EXACT; + const bool one_short_ok = policy == CountedEndPolicy::ONE_SHORT; std::vector at = Pokemon::tiles_of(from); const auto& legs_list = story_arg>(step.args, "legs"); - for (const Pokemon::StoryLeg& leg : legs_list){ - turn(leg.direction); - const size_t tiles = (size_t)leg.tiles; - const WalkResult walk = m_io.route().walk_taps(leg.direction, tiles, step.name); - log(std::format("[{}] {}: taps {} moved {} of {} tiles.", m_row, step.name, direction_name(leg.direction), walk.moved_chunks, tiles)); - const auto next = counted_ends(at, leg, one_short_ok ? CountedEndPolicy::ONE_SHORT : CountedEndPolicy::EXACT); + for (auto leg = legs_list.begin(); leg != legs_list.end(); ++leg){ + turn(leg->direction); + const size_t tiles = (size_t)leg->tiles; + const auto next = counted_ends(at, *leg, policy); + m_legs.begin_leg({.direction = leg->direction, .tiles = tiles, .end_kind = Pokemon::LegEndKind::TILE, + .ends = traced_tiles(from.map, next)}); + const WalkResult walk = m_route.walk_taps(leg->direction, tiles, step.name); + log(std::format("[{}] {}: taps {} moved {} of {} tiles.", m_row, step.name, direction_name(leg->direction), walk.moved_chunks, tiles)); if (walk.wild_battles > 0){ - if (walk.origin == WalkOrigin::MAY_PRECEDE_LEG){ - return Pokemon::outcome_failed("encounter_origin_unknown", step.name); - } if (walk.stop != WalkStop::LIMIT && walk.stop != WalkStop::BLOCKED){ return Pokemon::outcome_failed("interrupted_leg_unconfirmed", step.name); } - at = Pokemon::tiles_of(recover_tapped_leg(from, at, next, leg, step)); - continue; + const LegBattlePlace place = place_leg_battle(walk, tiles); + m_legs.end_leg({}, Pokemon::LegEndKnown::UNKNOWN, "recovery"); + m_route.note(std::format("[{}] {}", m_row, leg_battle_line(step.name, walk, place)), RouteNote::LOG); + std::vector ends = next; + for (auto rest = std::next(leg); rest != legs_list.end(); ++rest){ + ends = counted_ends(ends, *rest, policy); + } + return Pokemon::outcome_ok(recover_tapped_leg(from, at, ends, legs_list.back().direction, *leg, step, place.moved)); } if (walk.moved_chunks + (one_short_ok ? 1 : 0) < tiles){ - return Pokemon::outcome_failed("short_leg", std::format("{} {} moved {}", direction_name(leg.direction), tiles, walk.moved_chunks)); + return Pokemon::outcome_failed("short_leg", std::format("{} {} moved {}", direction_name(leg->direction), tiles, walk.moved_chunks)); } at = next; + m_legs.end_leg(traced_tiles(from.map, at), Pokemon::LegEndKnown::COUNTED); } return Pokemon::outcome_ok(Pokemon::tile_pose(from.map, at, legs_list.back().direction)); } +// A LEGS step "measured": each leg tapped, its taps that moved counted +// against the map's from each tile the player may stand on; the tiles +// whose count matches are where we are. A wall a tap bumps tells us +// where we are, where a fixed leg from a guessed tile walks on astray +// (00.03, lab-B 2026-11-09: a row low, the taps crossed the door's mat). +Outcome StoryWalkSteps::measured_legs(const Pose& from, const StoryStep& step){ + const StoryWorld* world = story_plan_world(from.map, from.map); + std::vector at = Pokemon::tiles_of(from); + if (world == nullptr || at.empty()){ + return Pokemon::outcome_failed("measured", "no map or tiles: " + Pokemon::to_string(from)); + } + const auto& legs_list = story_arg>(step.args, "legs"); + for (const Pokemon::StoryLeg& leg : legs_list){ + turn(leg.direction); + const size_t tiles = (size_t)leg.tiles; + m_legs.begin_leg({.direction = leg.direction, .tiles = tiles, .end_kind = Pokemon::LegEndKind::TILE}); + const WalkResult walk = m_route.walk_taps(leg.direction, tiles, step.name); + if (walk.wild_battles > 0){ + return Pokemon::outcome_failed("interrupted_leg_unconfirmed", step.name); + } + std::vector next; + for (const TilePos& pos : at){ + const TappedEnd tapped = tapped_end(*world, from.map, pos, leg); + if (tapped.moved == walk.moved_chunks){ + next.push_back(tapped.end); + } + } + log(std::format("[{}] {}: taps {} moved {} of {}: {} of {} tiles fit.", m_row, step.name, + direction_name(leg.direction), walk.moved_chunks, tiles, next.size(), at.size())); + if (next.empty()){ + return Pokemon::outcome_failed("measured", std::format("{} moved {}: no tile of {} fits", + direction_name(leg.direction), walk.moved_chunks, Pokemon::to_string(from))); + } + at = std::move(next); + m_legs.end_leg(traced_tiles(from.map, at), Pokemon::LegEndKnown::COUNTED); + } + return Pokemon::outcome_ok(Pokemon::tile_pose(from.map, at, legs_list.back().direction)); +} + +// A LEGS step "counted_wall": its one leg held to the wall, its tiles +// counted against the map's from each tile the table may have us on +// (walk_counted_wall_leg()). The leg's tiles are the table's reading of +// the map, and must be among them. +Outcome StoryWalkSteps::counted_wall(const Pose& from, const StoryStep& step){ + const auto& legs_list = story_arg>(step.args, "legs"); + const StoryWorld* world = story_plan_world(from.map, from.map); + const std::vector starts = Pokemon::tiles_of(from); + if (legs_list.size() != 1 || world == nullptr || starts.empty()){ + return Pokemon::outcome_failed("counted_wall", std::format("{} legs from {}", legs_list.size(), Pokemon::to_string(from))); + } + const Pokemon::StoryLeg& leg = legs_list.front(); + size_t fewest = SIZE_MAX; + size_t most = 0; + for (const TilePos& pos : starts){ + const size_t tiles = slide_to_wall(*world, story_to_world(*world, from.map, pos), leg.direction).tiles; + fewest = std::min(fewest, tiles); + most = std::max(most, tiles); + } + if ((size_t)leg.tiles < fewest || (size_t)leg.tiles > most){ + return Pokemon::outcome_failed("map_mismatch", + std::format("{} {} where the map has {} to {}", direction_name(leg.direction), leg.tiles, fewest, most)); + } + turn(leg.direction); + m_legs.begin_leg({.direction = leg.direction, .tiles = (size_t)leg.tiles, .end_kind = Pokemon::LegEndKind::WALL}); + walk_counted_wall_leg(m_route, {.direction = leg.direction, .fewest = fewest, .most = most, + .speed = m_can_run ? MoveSpeed::RUN : MoveSpeed::WALK, .label = label_of(step)}); + m_legs.end_leg({}, Pokemon::LegEndKnown::WALL); + return Pokemon::outcome_ok(); +} + Outcome StoryWalkSteps::legs(RunState& state, const StoryStep& step){ + const EventTrace trace(m_legs, m_row, step.name); + m_warp = {}; + m_scene_open = false; + if (step.action == "counted_wall"){ + return counted_wall(state.pose, step); + } + if (step.action == "measured"){ + return measured_legs(state.pose, step); + } if (step.action == "to_wall"){ const auto& legs_list = story_arg>(step.args, "legs"); + // The walls end these legs; the step's pose_after says where. for (const Pokemon::StoryLeg& leg : legs_list){ + m_legs.begin_leg({.direction = leg.direction, .tiles = (size_t)leg.tiles, .end_kind = Pokemon::LegEndKind::WALL}); m_io.walk_until_stopped(leg.direction, (size_t)leg.tiles, label_of(step)); + m_legs.end_leg({}, Pokemon::LegEndKnown::WALL); } return Pokemon::outcome_ok(); } - if (step.action == "to_dialogue"){ - return leg_to_dialogue(step); - } if (step.action == "to_map"){ return leg_to_map(step); } - const bool one_short_ok = step.action == "one_short_ok"; - if (!one_short_ok && !step.action.empty() && step.action != "legs"){ + if (step.action == "to_dialogue"){ + return run_to_dialogue(step); + } + if (step.action != "one_short_ok" && !step.action.empty() && step.action != "legs"){ return Pokemon::outcome_failed("unknown_action", step.action); } return tap_legs(state.pose, step); } Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ + const EventTrace trace(m_legs, m_row, step.name); const Direction direction = story_arg(step.args, "direction"); if (step.action == "to_banner"){ turn(direction); - return tap_to_banner(step); + return tap_to_banner(state.pose, step); } if (step.action == "tap"){ // No separate turn tap first: at 1 tile from the door, a turn tap // steps onto the warp, causing walk_taps to take an extra step on the far map. - const WalkResult walk = m_io.route().walk_taps(direction, 1, step.name); + const WalkResult walk = m_route.walk_taps(direction, 1, step.name); if (walk.wild_battles > 0){ return Pokemon::outcome_failed("interrupted_step", step.name); } - m_io.settle(BUTTON_B, label_of(step), false); + m_io.settle(BUTTON_B, label_of(step), false, ""); return Pokemon::outcome_ok(); } // A step through a door: walk (or run) on until the screen goes dark, @@ -303,15 +659,36 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ // 00.01; Dawn's tour, 00.04). Without the fade, settle must see it itself // (r33 was outside, "no fade"). No separate turn tap first: at 1 tile // from the door, a 50 ms turn tap can step in before run_into_door() watches. + // A fade or the far map's banner is the way through, either one (#268 + // slice 1); with neither yet, settle() waits for one. if (step.pose_after && Pokemon::grid_pose_of(*step.pose_after).map != state.pose.map){ - const Milliseconds timeout = door_timeout(state.pose.map, state.pose, direction, m_can_run); - const bool faded = m_io.run_into_door(direction, m_can_run, timeout); - log(std::format("[{}] {}: {} through the door (timeout {} ms): {}.", m_row, step.name, direction_name(direction), timeout.count(), faded ? "faded" : "no fade yet")); - m_io.settle(BUTTON_B, label_of(step), !faded); + if (through_already(step)){ + m_io.settle(BUTTON_B, label_of(step), false, ""); + return Pokemon::outcome_ok(); + } + const std::string banner = story_arrival_banner(state.pose.map, Pokemon::grid_pose_of(*step.pose_after).map); + const DoorRun door = door_run(state.pose.map, state.pose, direction, m_can_run); + WarpSeen seen = m_io.run_into_door(direction, m_can_run, door.timeout, door.dark_from, banner); + log(std::format("[{}] {}: {} through the door (timeout {} ms, dark from {} ms): {}.", m_row, step.name, + direction_name(direction), door.timeout.count(), door.dark_from.count(), seen.any() ? describe(seen) : "nothing yet")); + seen = door_from_beside(step, seen, door.timeout, banner); + m_io.settle(BUTTON_B, label_of(step), !seen.any(), banner); return Pokemon::outcome_ok(); } + return one_step(state, step); +} + +// A plain D-pad step: onto a scene's trigger, mostly. Not taken when the +// route before ran into that scene already (RouteEnd::scene): it holds us +// where it started. +Outcome StoryWalkSteps::one_step(const RunState& state, const StoryStep& step){ + if (std::exchange(m_scene_open, false)){ + log(std::format("[{}] {}: its scene started on the walk before; no step.", m_row, step.name)); + return Pokemon::outcome_ok(state.pose); + } + const Direction direction = story_arg(step.args, "direction"); turn(direction); - const WalkResult walk = m_io.route().walk_taps(direction, 1, step.name); + const WalkResult walk = m_route.walk_taps(direction, 1, step.name); if (walk.wild_battles > 0){ return Pokemon::outcome_failed("interrupted_step", step.name); } @@ -324,30 +701,34 @@ Outcome StoryWalkSteps::step(RunState& state, const StoryStep& step){ } Outcome StoryWalkSteps::talk(RunState& state, const StoryStep& step){ + m_warp = {}; + m_scene_open = false; // Face whom we talk to: a route ends facing its last leg, not its goal // (r40 reached Mom facing north). They block the tile, so the tap only turns. if (const std::optional facing = Pokemon::facing_of(state.pose)){ turn(*facing); } - m_io.route().press({.kind = RouteInputKind::BUTTON_A, .direction = Direction::NORTH, .hold = 80ms, .release = 200ms, + m_route.press({.kind = RouteInputKind::BUTTON_A, .direction = Direction::NORTH, .hold = 80ms, .release = 200ms, .count = 1, .end = RouteInputEnd::DONE}); // Roark's first line in the mine comes after the camera zooms in on // us, which can take some seconds (r98; the old event waited 8 s). - if (!m_io.route().dialog_within(8000ms, COLOR_YELLOW)){ - fail(m_io.route(), label_of(step) + ": nobody answered."); + if (!m_route.dialog_within(8000ms, COLOR_YELLOW)){ + fail(m_route, label_of(step) + ": nobody answered."); } return Pokemon::outcome_ok(); } Outcome StoryWalkSteps::mash(RunState& state, const StoryStep& step){ + m_warp = {}; + m_scene_open = false; // The step before may have played the scene already (a door step settles // its arrival scene), so its first line is not required. - if (!m_io.route().dialog_within(15000ms, COLOR_CYAN)){ - m_io.route().note(label_of(step) + ": no line within 15 s; the step before played it.", RouteNote::WARNING); + if (!m_route.dialog_within(15000ms, COLOR_CYAN)){ + m_route.note(label_of(step) + ": no line within 15 s; the step before played it.", RouteNote::WARNING); } m_io.settle(step.action == "a" ? BUTTON_A : BUTTON_B, label_of(step), step.pose_after && Pokemon::grid_pose_of(*step.pose_after).map != state.pose.map && - story_plan_world(state.pose.map, Pokemon::grid_pose_of(*step.pose_after).map) == nullptr); + story_plan_world(state.pose.map, Pokemon::grid_pose_of(*step.pose_after).map) == nullptr, ""); if (m_row == RUNNING_SHOES_ROW && step.name == RUNNING_SHOES_STEP){ m_can_run = true; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h index 44dade0915..344e2b80c1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h @@ -11,7 +11,10 @@ #ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryWalkSteps_H #define PokemonAutomation_PokemonBDSP_AutoStory_StoryWalkSteps_H +#include #include +#include +#include #include #include #include "Pokemon/AutoStory/Pokemon_StoryEvent.h" @@ -21,6 +24,8 @@ #include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TrainerSight.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegBattle.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegTraceIO.h" #include "PokemonBDSP_AutoStory_StoryStepIO.h" namespace PokemonAutomation{ @@ -28,22 +33,65 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ +// How a run north into a Pokemon Center's door got us in. +enum class CenterEntry{ + FADED, // its fade showed + INSIDE, // no fade, but the inside shows: the run went on in, as + // far as the nurse's counter (lab-B 2026-11-08, Oreburgh) + LINED_UP, // no fade and no inside: lined up with the lit doorway +}; + +// Runs north into the Pokemon Center's door ahead, running with `run`. +// After its fade, waits until the inside is a quiet overworld (settle()): +// a walk while it still fades in goes nowhere (lab-B 2026-11-10, 00.04b). +// Without a fade, `inside` says whether the Center's inside shows, and if +// not, `line_up` lines up with the lit doorway and walks in (or fails). +CenterEntry run_into_center( + StoryStepIO& io, bool run, + const std::function& inside, const std::function& line_up, + const std::string& label +); + +// Where a leg's taps end, and how many of them moved. +struct TappedEnd{ + Pokemon::TilePos end; + size_t moved = 0; +}; +// Where `leg`'s taps from `pos` (a tile of `map`) end on `world`: each tap +// moves a tile until a wall stops them. +TappedEnd tapped_end(const StoryWorld& world, const std::string& map, const Pokemon::TilePos& pos, const Pokemon::StoryLeg& leg); +// The tiles a "measured" LEGS step may end on from `from`, one a tile of +// it; the step measures which. Nothing if `from`'s map has no world. +std::optional measured_ends(const Pokemon::Pose& from, const Pokemon::StoryStep& step); +// The trainers of `world` who can see us in row `row`: story_trainers(), +// less those an earlier row fights, whom its save and every later one's +// keep beaten. +std::vector row_trainers(const StoryWorld& world, const std::string& row); + + // Executes walking and movement-related story steps via StoryStepIO. class StoryWalkSteps{ public: explicit StoryWalkSteps(StoryStepIO& io) : m_io(io) + , m_legs(legs_to_log(io.route())) + , m_route(io.route(), m_legs) {} // A new attempt of the row `row`: every trainer can see us again, and - // the pace is the row's save's (a run after the Running Shoes). - void begin_attempt(const std::string& row); + // the pace is the row's save's (a run after the Running Shoes). With + // the row's `steps`, a route followed by a scene, or by a plain step onto + // the scene's trigger, hands a dialogue that starts on the way to that + // scene (RouteWalkPlan::scene_next). + void begin_attempt(const std::string& row, const std::vector& steps = {}); // Whether the player has the Running Shoes: the pace routes are timed at. bool can_run() const{ return m_can_run; } // Walks the planned route to `step.target`. Variant: the plan's costs. + // With a leg, then runs on toward its direction until a dialogue starts, + // for its tiles at most (run_to_dialogue()). Pokemon::Outcome route(Pokemon::RunState& state, const Pokemon::StoryStep& step); // See StoryExecutor::legs(). Pokemon::Outcome legs(Pokemon::RunState& state, const Pokemon::StoryStep& step); @@ -56,23 +104,43 @@ class StoryWalkSteps{ private: Pokemon::Pose walk_to(const Pokemon::Pose& from, const Pokemon::Pose& goal, const Pokemon::StoryStep& step); + // After a wild battle on `leg`'s taps from `starts`: walks to one of + // `goals` from wherever the leg could have left us, then faces `facing`. Pokemon::Pose recover_tapped_leg(const Pokemon::Pose& from, const std::vector& starts, const std::vector& goals, - const Pokemon::StoryLeg& leg, const Pokemon::StoryStep& step); + Pokemon::Direction facing, const Pokemon::StoryLeg& leg, const Pokemon::StoryStep& step, + const std::optional& moved); Pokemon::Outcome tap_legs(const Pokemon::Pose& from, const Pokemon::StoryStep& step); - Pokemon::Outcome leg_to_dialogue(const Pokemon::StoryStep& step); + Pokemon::Outcome counted_wall(const Pokemon::Pose& from, const Pokemon::StoryStep& step); + Pokemon::Outcome measured_legs(const Pokemon::Pose& from, const Pokemon::StoryStep& step); + Pokemon::Outcome run_to_dialogue(const Pokemon::StoryStep& step); Pokemon::Outcome leg_to_map(const Pokemon::StoryStep& step); - Pokemon::Outcome tap_to_banner(const Pokemon::StoryStep& step); + Pokemon::Outcome one_step(const Pokemon::RunState& state, const Pokemon::StoryStep& step); + Pokemon::Outcome tap_to_banner(const Pokemon::Pose& from, const Pokemon::StoryStep& step); + bool through_already(const Pokemon::StoryStep& step); + WarpSeen door_from_beside(const Pokemon::StoryStep& step, const WarpSeen& seen, Milliseconds timeout, const std::string& banner); void turn(Pokemon::Direction direction); void log(const std::string& text); StoryStepIO& m_io; + // The leg records of the walks, written to m_io's route log. + Pokemon::LegTracer m_legs; + // m_io's route walker console, telling m_legs of each leg walked. + LegTraceRouteIO m_route; std::string m_row; bool m_can_run = false; // The trainers who can still see us on each story_plan_world() world, // in its tiles, from its first walk this attempt; all of them again at // each attempt. std::map> m_trainers; + // The warp the last route ran on through at its end (walk_route_to_warp()), + // for the step after it, which goes through that warp. + WarpSeen m_warp; + // The row's steps followed by a scene (begin_attempt()). + std::set m_scene_next; + // The last route ended in the scene of the step after it, or after the + // plain step onto its trigger (RouteEnd::scene); that step is not taken. + bool m_scene_open = false; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.cpp new file mode 100644 index 0000000000..9f55f5a6c2 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.cpp @@ -0,0 +1,108 @@ +/* BDSP AutoStory - Table Routes + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Data/PokemonBDSP_AutoStory_RobustRoute.h" +#include "Data/PokemonBDSP_AutoStory_WallRecovery.h" +#include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" +#include "Utils/PokemonBDSP_AutoStory_RouteChoice.h" +#include "PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_TableRoutes.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + + +namespace{ + +using Pokemon::story_arg; + +std::optional pose_after_step(const std::optional& at, const Pokemon::StoryStep& step){ + if (step.kind == StoryStepKind::ROUTE){ + return Pokemon::pose_of(story_arg(step.args, "target")); + } + if (step.pose_after){ + return Pokemon::pose_of(*step.pose_after); + } + return step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP ? std::nullopt : at; +} + +// A ROUTE step after a "measured" LEGS step plans from the one tile the +// taps measured: one TableRoute for each tile of `at`. +void add_measured_routes(std::vector& routes, const std::string& row, const Pokemon::StoryStep& step, const Pokemon::Pose& at){ + const Pokemon::Pose target = Pokemon::pose_of(story_arg(step.args, "target")); + for (const TilePos& pos : Pokemon::tiles_of(at)){ + const Pokemon::Pose one = Pokemon::tile_pose(at.map, {pos}, Pokemon::facing_of(at)); + routes.push_back({row, &step, one, story_plan_world(at.map, target.map)}); + } +} + +} // namespace + + +std::vector table_routes(){ + std::vector routes; + for (const StoryCheckpoint& row : story_checkpoints()){ + std::optional at = row.start ? std::optional(Pokemon::pose_of(*row.start)) : std::nullopt; + bool measured = false; + for (const Pokemon::StoryStep& step : row.steps){ + const bool known = at && !Pokemon::tiles_of(*at).empty(); + if (step.kind == StoryStepKind::ROUTE && known && std::exchange(measured, false)){ + add_measured_routes(routes, row.id, step, *at); + }else if (step.kind == StoryStepKind::ROUTE){ + const Pokemon::Pose target = Pokemon::pose_of(story_arg(step.args, "target")); + routes.push_back({row.id, &step, at, known ? story_plan_world(at->map, target.map) : nullptr}); + } + measured = false; + if (step.kind == StoryStepKind::LEGS && step.action == "measured" && known && !step.pose_after){ + at = measured_ends(*at, step); + measured = at.has_value(); + continue; + } + at = pose_after_step(at, step); + } + } + return routes; +} + +std::vector world_tiles(const StoryWorld& world, const Pokemon::Pose& pose){ + std::vector tiles; + for (const TilePos& pos : Pokemon::tiles_of(pose)){ + tiles.push_back(story_to_world(world, pose.map, pos)); + } + return tiles; +} + +RouteStepPlan plan_table_route(const TableRoute& route){ + const StoryWorld& world = *route.world; + const Pokemon::Pose target = Pokemon::pose_of(story_arg(route.step->args, "target")); + const std::vector targets = world_tiles(world, target); + const auto goal = [&](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }; + RouteStepPlan plan{.start = world_tiles(world, *route.from)}; + const MoveSpeed speed = route.row > std::string(RUNNING_SHOES_ROW) ? MoveSpeed::RUN : MoveSpeed::WALK; + plan.legs = plan_fastest_route({ + .world = world, .from = plan.start, .goal = goal, .costs = *story_route_costs(route.step->action), .speed = speed, + .goal_is_trigger = route.step->action == ROUTE_ONTO_TRIGGER, + }); + if (!plan.legs){ + plan.legs = plan_recovered_route(world, plan.start, goal, RobustPlanCosts()); + plan.default_costs = plan.legs.has_value(); + } + return plan; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.h new file mode 100644 index 0000000000..57092298bf --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_TableRoutes.h @@ -0,0 +1,64 @@ +/* BDSP AutoStory - Table Routes + * + * From: https://github.com/PokemonAutomation/ + * + * The story table's ROUTE steps, each from where the steps before it in + * its row leave the player, and the legs the program plans for them: what + * the route tests and the route bench check. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_TableRoutes_H +#define PokemonAutomation_PokemonBDSP_AutoStory_TableRoutes_H + +#include +#include +#include +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" +#include "Data/PokemonBDSP_AutoStory_RobustRoute.h" +#include "Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "Data/PokemonBDSP_AutoStory_StoryWorld.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// A ROUTE step of the table, and where the steps before it in its row leave +// the player: the row's start, then each step's target or pose_after. A LEGS +// or STEP step that does not say where it ends leaves the start unknown. +struct TableRoute{ + std::string row; + const Pokemon::StoryStep* step; + std::optional from; + // The world the step is planned on; none if the start is unknown or no + // world joins its map and the target's. + const StoryWorld* world; +}; + +// Every ROUTE step of the story table, in table order. +std::vector table_routes(); + +// The world tiles of `pose` on `world`. +std::vector world_tiles(const StoryWorld& world, const Pokemon::Pose& pose); + +// The legs a table ROUTE step plans, as walk_route() plans them: the step's +// costs, then the default ones; no legs if neither plans. +struct RouteStepPlan{ + std::vector start; + std::optional> legs; + bool default_costs = false; // the step's own costs found no plan +}; + +// Plans `route`, which must have a world. +RouteStepPlan plan_table_route(const TableRoute& route); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp index 155418cd5a..36df0774d0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.cpp @@ -4,6 +4,7 @@ * */ +#include #include #include #include @@ -12,12 +13,16 @@ #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "CommonFramework/GlobalAutoPaths.h" #include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_TrainerSight.h" #include "Utils/PokemonBDSP_AutoStory_Indoors.h" #include "Utils/PokemonBDSP_AutoStory_LegBattle.h" #include "Utils/PokemonBDSP_AutoStory_Location.h" #include "Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "Utils/PokemonBDSP_AutoStory_Walk.h" #include "Actions/PokemonBDSP_AutoStory_Talks.h" +#include "PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP_AutoStory_StoryWalkSteps.h" #include "PokemonBDSP_AutoStory_Walk_Tests.h" #include "Utils/PokemonBDSP_AutoStory_WalkResult.h" #include "Utils/PokemonBDSP_AutoStory_WalkScreen.h" @@ -181,6 +186,38 @@ UnitTestResult test_door_fade(Logger&){ return true; } +// A fade is uniform (fade_of(): the shared watchers' stddev test), dark or +// white; a floor is textured. The Oreburgh Gate's floor, about 46, is no +// fade: read as one, the tap into the Gate from Oreburgh, already +// through, waited 8 s for a banner gone (lab-B, 2026-11-08 15:31 to +// 15:54). A cave mouth's dim fade (45 to 64 measured) is one. The stddevs +// are a model; the Gate's frames on the console are to check them. +UnitTestResult test_fade_of(Logger&){ + struct Case{ + std::string name; + double brightness; + double stddev; + WarpFade fade; + }; + const std::vector cases{ + {.name = "inside the Gate, its floor", .brightness = 46, .stddev = 20, .fade = WarpFade::NONE}, + {.name = "Oreburgh's street at night", .brightness = 88, .stddev = 20, .fade = WarpFade::NONE}, + {.name = "a door's black", .brightness = 7, .stddev = 1, .fade = WarpFade::BLACK}, + {.name = "a cave mouth's dim fade", .brightness = 64, .stddev = 2, .fade = WarpFade::BLACK}, + {.name = "a grey screen, neither dark nor white", .brightness = 120, .stddev = 1, .fade = WarpFade::NONE}, + {.name = "a cave exit's white", .brightness = 250, .stddev = 1, .fade = WarpFade::WHITE}, + {.name = "a bright textured screen", .brightness = 250, .stddev = 20, .fade = WarpFade::NONE}, + }; + for (const Case& item : cases){ + const ImageStats stats(FloatPixel(item.brightness, item.brightness, item.brightness), FloatPixel(item.stddev, item.stddev, item.stddev), 1); + const WarpFade fade = fade_of(stats); + if (fade != item.fade){ + return item.name + ": " + warp_fade_name(fade) + ", expected " + warp_fade_name(item.fade) + "."; + } + } + return true; +} + UnitTestResult test_location_banner(Logger&){ struct Case{ @@ -298,6 +335,27 @@ UnitTestResult test_pokemon_center_on_screen(Logger&){ return true; } +// 01.02's walk east beats the Youngster above Route 203's row 18; the rows +// after it, from saves made since, do not meet him again. +UnitTestResult test_row_trainers(Logger&){ + const StoryWorld* world = story_plan_world("Route203", "JubilifeCity"); + if (world == nullptr){ + return std::string("no world joins Route 203 and Jubilife"); + } + const auto has_youngster = [world](const std::string& row){ + const std::vector sights = row_trainers(*world, row); + return std::any_of(sights.begin(), sights.end(), [](const TrainerSight& sight){ + return sight.name == "Youngster (above row 18)"; + }); + }; + if (!has_youngster("01.02")){ + return std::string("01.02 fights the Youngster: he must be on its trainers"); + } + if (has_youngster("01.06")){ + return std::string("01.06 starts from a save after 01.02 beat the Youngster"); + } + return true; +} struct AutoStoryWalkInput{ std::string name; @@ -385,6 +443,10 @@ const AutoStoryWalkCase AUTO_STORY_WALK_CASES[] = { .input = {"out of a door needs its fade", test_door_fade}, .expectation = {}, }, + { + .input = {"a fade is uniform, dark or white; a dim floor is none (lab-B, 2026-11-08)", test_fade_of}, + .expectation = {}, + }, { .input = {"a warp's fade, followed frame by frame, its hold seen or not", test_warp_fade_watch}, .expectation = {}, @@ -409,6 +471,10 @@ const AutoStoryWalkCase AUTO_STORY_WALK_CASES[] = { .input = {"a wild battle on an open leg's taps, placed by its screen events", test_leg_battle_place}, .expectation = {}, }, + { + .input = {"a row's trainers leave out those an earlier row beat", test_row_trainers}, + .expectation = {}, + }, }; void add_tests_AutoStory_Walk(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp new file mode 100644 index 0000000000..c3beaa348f --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.cpp @@ -0,0 +1,466 @@ +/* BDSP AutoStory - Fault sweeps on the story simulation + * + * From: https://github.com/PokemonAutomation/ + * + * Each class of failure console B showed, injected at every step of every + * row where the game can cause it, instead of only where it was seen: + * + * - SCENE_END_POSE: a step whose end pose the game sets (a talk, a scene, + * a battle, an event) leaves the player on another walkable tile within + * one of the table's (00.03, lab-B 2026-11-09: Rowan's scene ended a row + * low). SimWorldKnobs::lands. + * - BATTLE_OPENING: a battle's opening is still playing when a step starts + * (00.02's Starly, lab-B 2026-11-09), at each battle step and at each + * step after a walk, which can end in a trainer's sight or in grass. + * SimWorldKnobs::battle_opening_before. + * - GRASS_BATTLES: a wild battle on every pass through tall grass, one + * each 8 grass tiles (00.04, lab-B 2026-11-09 16:14: four in a row on + * Route 201, each replan back through the grass, "too many plans"). + * SimWorldKnobs::grass. One variant a row: the whole row so. + * - SCENE_EARLY: a scene starts early, on the last tiles of the route walk + * before its step, or before the plain step onto its trigger: the + * trigger lies on the way, not where the decomp has it (00.04's Mom's call on + * (6, 9), lab-B 2026-11-09 17:29: the walk took it for a trainer and + * pressed through it). A variant also fails when the walk fights it. + * SimWorldKnobs::scene_at_walk_end. + * + * Missed and short fades are swept by SimFailureCases_Tests (every single + * missed fade, banner and fade hold). + * A lost tap from the input lockout waits for the measured movement + * table (FRLG #293); FaultClass::LOST_TAP is its slot. + * + * Each row is run clean first; a row that fails clean is not swept. A + * variant fails when the row then fails. A sweep the program fails today + * is on KNOWN_FAILING with its likely fix: its test passes while it still + * fails, and fails once it passes, to be taken off the list. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/Navigation/Pokemon_MapData.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WalkRules.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_StorySim.h" +#include "PokemonBDSP_AutoStory_FaultSweep_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +namespace{ + +using Pokemon::Direction; +using Pokemon::Pose; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + +enum class FaultClass{ + SCENE_END_POSE, + BATTLE_OPENING, + GRASS_BATTLES, + SCENE_EARLY, + // Not swept yet: the measured movement table's lost taps (#293). + LOST_TAP, +}; +std::string_view fault_class_name(FaultClass fault){ + switch (fault){ + case FaultClass::SCENE_END_POSE: + return "scene end pose"; + case FaultClass::BATTLE_OPENING: + return "battle opening at step start"; + case FaultClass::GRASS_BATTLES: + return "wild battles on every grass pass"; + case FaultClass::SCENE_EARLY: + return "scene starts during the walk before it"; + case FaultClass::LOST_TAP: + return "lost tap"; + } + return "?"; +} + +// The rows swept: those the clean simulation runs (SimFailureCases_Tests). +constexpr std::string_view FIRST_ROW = "00.00"; +constexpr std::string_view LAST_ROW = "01.11"; + +// Sweeps the program fails today, by test name, with the likely fix. +const std::map KNOWN_FAILING{ +}; + +// Scenes whose end the console has proven, by step name: the sweep leaves +// them out, as the tiles next to it are not where the game leaves us. +const std::map PROVEN_SCENE_ENDS{ + // Mom's Running Shoes scene: (6, 8) facing east in 7 of 7 runs stopped + // right after it (lab-B 2026-11-09). The rows 7, 9 and 10 seen before + // were our input landing in its closing fade, now waited out. + {"rowan_and_dawn", "lab-B 2026-11-09, 7 of 7 runs on (6, 8)"}, +}; + +// Runs row `row` with `knobs`: "" if it passes, else where and why it stopped. +std::string run_row(Logger& logger, const std::string& row, SimWorldKnobs knobs){ + SimExecutor executor(logger, {.fade = {}, .banner = {}}, std::move(knobs)); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = row, .to = row}); + return report.completed ? "" : std::format("stopped in {}: {}", executor.result().failed_step, executor.result().error); +} + +// Whether the game, not our walking, sets where `kind` ends. +bool game_sets_end(StoryStepKind kind){ + switch (kind){ + case StoryStepKind::NEW_GAME: + case StoryStepKind::TALK: + case StoryStepKind::ANSWER: + case StoryStepKind::MASH: + case StoryStepKind::BATTLE: + case StoryStepKind::GAME: + return true; + default: + return false; + } +} +bool walks(StoryStepKind kind){ + return kind == StoryStepKind::ROUTE || kind == StoryStepKind::LEGS || kind == StoryStepKind::STEP; +} +// Whether row `row` run clean up to its step `c` leaves the player on one +// of `pose`'s tiles: a talk, a trainer's battle or a scene that only turns +// the player ends where our walk did, so its end is not the game's. +bool already_there(Logger& logger, const StoryCheckpoint& row, size_t c, const Pose& pose){ + StoryCheckpoint head = row; + head.steps.resize(c); + SimExecutor executor(logger, {.fade = {}, .banner = {}}, {}); + if (!run_rows_on(executor, logger, {.from = row.id, .to = row.id}, {head}).completed || executor.result().world == nullptr){ + return false; + } + const SimRun& run = executor.result(); + for (const TilePos& tile : Pokemon::tiles_of(pose)){ + try{ + if (story_to_world(*run.world, pose.map, tile) == run.end){ + return true; + } + }catch (const InternalProgramError&){} + } + return false; +} +// Whether walk `step` ends where a battle can start: on a route (grass, a +// trainer's sight) or in a cave. Towns and rooms have neither. +bool wild_or_trainers(const StoryStep& step){ + std::string map; + if (step.pose_after){ + map = Pokemon::grid_pose_of(*step.pose_after).map; + }else if (step.args.contains("target")){ + map = Pokemon::story_arg(step.args, "target").map; + }else{ + return true; + } + for (std::string_view place : {"Route", "Gate", "Mine", "RavagedPath"}){ + if (map.find(place) != std::string::npos){ + return true; + } + } + return false; +} + +// The tiles within one of `center`, diagonals too, that the player can +// reach from it in one or two steps, and not in `seen`: where a scene can +// leave them instead. A tile behind a wall is not one, nor a door's: a +// step onto it goes through (00.04's moms_hat by the house's door). +void walkable_neighbors(const StoryWorld* world, const Pose& pose, const TilePos& center, std::set>& seen, std::vector& out){ + const auto step = [](const TilePos& tile, Direction direction){ + switch (direction){ + case Direction::NORTH: + return TilePos{tile.x, tile.y - 1}; + case Direction::SOUTH: + return TilePos{tile.x, tile.y + 1}; + case Direction::WEST: + return TilePos{tile.x - 1, tile.y}; + default: + return TilePos{tile.x + 1, tile.y}; + } + }; + const auto can_step = [&](const TilePos& from, Direction direction){ + GridSim sim(SimWorld{.world = world}, story_to_world(*world, pose.map, from), direction, false); + return detail::sim_can_step(sim, direction); + }; + const Pokemon::MapData& map = story_map(pose.map); + const auto add = [&](const TilePos& tile){ + if (map.tiles.at(tile) == Pokemon::TileKind::DOOR){ + return; + } + if (seen.insert({tile.x, tile.y}).second){ + out.push_back(tile); + } + }; + const Direction all[] = {Direction::NORTH, Direction::SOUTH, Direction::WEST, Direction::EAST}; + for (Direction first : all){ + if (!can_step(center, first)){ + continue; + } + const TilePos one = step(center, first); + add(one); + for (Direction second : all){ + const TilePos two = step(one, second); + const bool diagonal = two.x != center.x && two.y != center.y; + if (diagonal && can_step(one, second)){ + add(two); + } + } + } +} +// The walkable tiles next to any of `pose`'s tiles, not its own. +std::vector walkable_neighbors(const Pose& pose){ + const std::vector tiles = Pokemon::tiles_of(pose); + const StoryWorld* world = pose.map.empty() ? nullptr : story_plan_world(pose.map, pose.map); + std::vector out; + if (world == nullptr){ + return out; + } + std::set> seen; + for (const TilePos& tile : tiles){ + seen.insert({tile.x, tile.y}); + } + for (const TilePos& tile : tiles){ + walkable_neighbors(world, pose, tile, seen, out); + } + return out; +} + +// One injected variant that failed its row. +struct SweepFailure{ + std::string step; + std::string variant; + std::string stopped; +}; + +UnitTestResult sweep_result(Logger& logger, FaultClass fault, const std::string& row, size_t variants, const std::vector& failures){ + logger.log(std::format("Fault sweep {} {}: {} variants, {} fail.", row, fault_class_name(fault), variants, failures.size())); + if (failures.empty()){ + return true; + } + std::string out = std::format("{} of {} variants fail {}:", failures.size(), variants, row); + for (const SweepFailure& failure : failures){ + logger.log(std::format("| {} | {} | {} | {} | {} |", row, failure.step, fault_class_name(fault), failure.variant, failure.stopped)); + out += std::format("\n {} {}: {}", failure.step, failure.variant, failure.stopped); + } + return out; +} + +// Row `row`'s steps whose end the game sets, each ending on every walkable +// tile next to the table's pose in turn. +UnitTestResult sweep_scene_end_pose(Logger& logger, const StoryCheckpoint& row){ + std::vector failures; + size_t variants = 0; + for (size_t c = 0; c < row.steps.size(); c++){ + const StoryStep& step = row.steps[c]; + if (!game_sets_end(step.kind) || !step.pose_after || PROVEN_SCENE_ENDS.contains(step.name) || + already_there(logger, row, c, Pokemon::pose_of(*step.pose_after))){ + continue; + } + for (const TilePos& tile : walkable_neighbors(Pokemon::pose_of(*step.pose_after))){ + SimWorldKnobs knobs; + knobs.lands[step.name] = Pokemon::tile_pose(Pokemon::grid_pose_of(*step.pose_after).map, {tile}, Pokemon::facing_of(Pokemon::pose_of(*step.pose_after))); + variants++; + const std::string stopped = run_row(logger, row.id, std::move(knobs)); + if (!stopped.empty()){ + failures.push_back({step.name, std::format("ends on ({}, {})", tile.x, tile.y), stopped}); + } + } + } + return sweep_result(logger, FaultClass::SCENE_END_POSE, row.id, variants, failures); +} + +// Row `row` with a battle's opening still playing at the start of each +// battle step and of each step after a walk, one at a time. +UnitTestResult sweep_battle_opening(Logger& logger, const StoryCheckpoint& row){ + std::vector failures; + size_t variants = 0; + for (size_t c = 0; c < row.steps.size(); c++){ + const StoryStep& step = row.steps[c]; + const bool after_walk = c > 0 && walks(row.steps[c - 1].kind) && wild_or_trainers(row.steps[c - 1]); + if (step.kind != StoryStepKind::BATTLE && !after_walk){ + continue; + } + SimWorldKnobs knobs; + knobs.battle_opening_before = [id = row.id, name = step.name](const std::string& r, const std::string& s){ + return r == id && s == name; + }; + variants++; + const std::string stopped = run_row(logger, row.id, std::move(knobs)); + if (!stopped.empty()){ + failures.push_back({step.name, "opening at its start", stopped}); + } + } + return sweep_result(logger, FaultClass::BATTLE_OPENING, row.id, variants, failures); +} + +// Row `row` with a wild battle each 8 tall-grass tiles stepped onto, all +// through the row. +UnitTestResult sweep_grass_battles(Logger& logger, const StoryCheckpoint& row){ + SimWorldKnobs knobs; + knobs.grass.every = 8; + const std::string stopped = run_row(logger, row.id, std::move(knobs)); + std::vector failures; + if (!stopped.empty()){ + failures.push_back({"", "a battle each 8 grass tiles", stopped}); + } + return sweep_result(logger, FaultClass::GRASS_BATTLES, row.id, 1, failures); +} + +// The route before scene step `c` of `steps`, right before it or before +// the plain step onto its trigger; none if there is none. +std::optional route_before_scene(const std::vector& steps, size_t c){ + if (steps[c].kind != StoryStepKind::MASH || c == 0){ + return std::nullopt; + } + if (steps[c - 1].kind == StoryStepKind::ROUTE){ + return c - 1; + } + const StoryStep& step = steps[c - 1]; + const bool onto_trigger = step.kind == StoryStepKind::STEP && step.action.empty() && !step.pose_after; + if (onto_trigger && c >= 2 && steps[c - 2].kind == StoryStepKind::ROUTE){ + return c - 2; + } + return std::nullopt; +} + +// Row `row` with the scene of each scene step after a route starting on +// that route's target, one at a time. +UnitTestResult sweep_scene_early(Logger& logger, const StoryCheckpoint& row){ + std::vector failures; + size_t variants = 0; + for (size_t c = 1; c < row.steps.size(); c++){ + const std::optional w = route_before_scene(row.steps, c); + if (!w){ + continue; + } + const StoryStep& walk = row.steps[*w]; + SimWorldKnobs knobs; + knobs.scene_at_walk_end = [id = row.id, name = walk.name](const std::string& r, const std::string& s){ + return r == id && s == name; + }; + variants++; + SimExecutor executor(logger, {.fade = {}, .banner = {}}, std::move(knobs)); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = row.id, .to = row.id}); + const SimRun& run = executor.result(); + const std::string early = "early scene after " + walk.name; + const bool fought = std::any_of(run.scenes_fought.begin(), run.scenes_fought.end(), [&](const std::string& scene){ + return scene.ends_with(early); + }); + if (!report.completed){ + failures.push_back({row.steps[c].name, "starts on " + walk.name + "'s end", std::format("stopped in {}: {}", run.failed_step, run.error)}); + }else if (fought){ + failures.push_back({row.steps[c].name, "starts on " + walk.name + "'s end", "the walk fought it as a trainer's"}); + } + } + return sweep_result(logger, FaultClass::SCENE_EARLY, row.id, variants, failures); +} + +// A fault class swept over row `row` (empty in FAULT_SWEEP_CASES: each +// row from FIRST_ROW to LAST_ROW). +struct FaultSweepInput{ + FaultClass fault = FaultClass::SCENE_END_POSE; + std::string row = {}; +}; +// Whether a sweep is expected to fail is KNOWN_FAILING's, by name. +struct FaultSweepExpectation{ +}; +struct FaultSweepCase{ + FaultSweepInput input; + FaultSweepExpectation expectation; +}; + +// The table's row `id`. +const StoryCheckpoint& table_row(const std::string& id){ + for (const StoryCheckpoint& row : story_checkpoints()){ + if (row.id == id){ + return row; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No row " + id); +} + +class Test_AutoStoryFaultSweep : public UnitTest{ +public: + explicit Test_AutoStoryFaultSweep(FaultSweepCase test_case) + : UnitTest(std::format("PokemonBDSP::AutoStory - Fault sweep: {}, {}", test_case.input.row, fault_class_name(test_case.input.fault))) + , m_fault(test_case.input.fault) + , m_row(table_row(test_case.input.row)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + UnitTestResult result; + try{ + result = sweep(logger); + }catch (Exception& e){ + result = std::string(e.name()) + ": " + e.message(); + } + const auto known = KNOWN_FAILING.find(name()); + if (known == KNOWN_FAILING.end()){ + return result; + } + if (result.result == UnitTestResult::PASSED){ + return "on KNOWN_FAILING (" + known->second + ") but passes now: take it off the list."; + } + logger.log("Known failing until " + known->second + ": " + result.message); + return true; + } + +private: + UnitTestResult sweep(Logger& logger) const{ + const std::string clean = run_row(logger, m_row.id, {}); + if (!clean.empty()){ + logger.log(std::format("Fault sweep {}: not swept, the row fails clean: {}", m_row.id, clean)); + return true; + } + switch (m_fault){ + case FaultClass::SCENE_END_POSE: + return sweep_scene_end_pose(logger, m_row); + case FaultClass::BATTLE_OPENING: + return sweep_battle_opening(logger, m_row); + case FaultClass::GRASS_BATTLES: + return sweep_grass_battles(logger, m_row); + case FaultClass::SCENE_EARLY: + return sweep_scene_early(logger, m_row); + case FaultClass::LOST_TAP: + break; + } + return true; + } + + FaultClass m_fault; + const StoryCheckpoint& m_row; +}; + +} // namespace + +const FaultSweepCase FAULT_SWEEP_CASES[] = { + {.input = {.fault = FaultClass::SCENE_END_POSE}, .expectation = {}}, + {.input = {.fault = FaultClass::BATTLE_OPENING}, .expectation = {}}, + {.input = {.fault = FaultClass::GRASS_BATTLES}, .expectation = {}}, + {.input = {.fault = FaultClass::SCENE_EARLY}, .expectation = {}}, +}; + +void add_tests_AutoStory_FaultSweep(UnitTestDatabase& database){ + for (const FaultSweepCase& item : FAULT_SWEEP_CASES){ + for (const StoryCheckpoint& row : story_checkpoints()){ + if (row.id < FIRST_ROW || row.id > LAST_ROW){ + continue; + } + database.add(FaultSweepCase{.input = {.fault = item.input.fault, .row = row.id}, .expectation = item.expectation}); + } + } +} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.h new file mode 100644 index 0000000000..7222d25869 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_FaultSweep_Tests.h @@ -0,0 +1,27 @@ +/* BDSP AutoStory - Fault sweeps on the story simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_FaultSweep_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_FaultSweep_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// Each class of console failure injected at every step of every row where +// the game can cause it; the rows the program still fails are known failing. +void add_tests_AutoStory_FaultSweep(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp index 8c3647e593..09c39e1164 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.cpp @@ -12,11 +12,13 @@ #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkDpad.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkResult.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WildBattlePolicy.h" #include "PokemonBDSP_AutoStory_GridSim.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonBDSP{ +using namespace detail; using namespace std::chrono_literals; using Pokemon::Direction; @@ -68,8 +70,23 @@ bool is_door(const StoryWorld& world, const TilePos& pos){ return tile && *tile == TileKind::DOOR && !world.occupied(pos); } +// Held time per tile of a walk east or west to a wall: slower than the +// walker's 160 ms. On the console 3520 ms held east before the Running +// Shoes went fewer than 20 tiles (lab-B 2026-11-09, 00.03): at least 176 ms +// a tile. A limit timed at the walker's pace stops short here as it did +// there. North and south keep their measured 240 ms. +constexpr Milliseconds SIM_WALK_MS_PER_TILE_ACROSS = Milliseconds(200); + Milliseconds per_tile(Direction direction, SimPace pace, bool can_run){ - return route_ms_per_tile(direction, pace == SimPace::RUN && can_run ? MoveSpeed::RUN : MoveSpeed::WALK); + if (pace == SimPace::RUN && can_run){ + return route_ms_per_tile(direction, MoveSpeed::RUN); + } + return std::max(route_ms_per_tile(direction, MoveSpeed::WALK), SIM_WALK_MS_PER_TILE_ACROSS); +} + +uint32_t step_rng(uint64_t& state){ + state = state * 6364136223846793005ULL + 1442695040888963407ULL; + return static_cast(state >> 32); } } // namespace @@ -88,8 +105,6 @@ TilePos nearest_tile(const SimPos& pos){ std::string to_string(const SimPos& pos){ return std::format("({:g}, {:g})", pos.x / (double)SIM_TILE, pos.y / (double)SIM_TILE); } -} // namespace detail - std::string_view sim_stop_name(SimStop stop){ switch (stop){ case SimStop::DONE: @@ -105,28 +120,116 @@ std::string_view sim_stop_name(SimStop stop){ } return "?"; } - +} // namespace detail GridSim::GridSim(SimWorld world, const TilePos& start, Direction facing, bool can_run) : m_world(std::move(world)) + , m_wanderers(m_world.wanderers) { m_player.pos = sim_pos(start); m_player.facing = facing; m_player.can_run = can_run; + for (SimWanderer& wanderer : m_wanderers){ + if (wanderer.time_offset > 0ms){ + advance_wanderer(wanderer, wanderer.time_offset); + } + } } void GridSim::place(SimWorld world, const TilePos& start, std::optional facing){ m_world = std::move(world); + m_wanderers = m_world.wanderers; m_player.pos = sim_pos(start); if (facing){ m_player.facing = *facing; } m_player.dialog = false; m_player.trainer.reset(); + m_player.scene.reset(); m_player.warped.reset(); if (m_world.can_run){ m_player.can_run = *m_world.can_run; } + for (SimWanderer& wanderer : m_wanderers){ + if (wanderer.time_offset > 0ms){ + advance_wanderer(wanderer, wanderer.time_offset); + } + } +} + +bool GridSim::can_wander_to(const SimWanderer& wanderer, const TilePos& next) const{ + if (next.x < wanderer.box.x0 || next.x > wanderer.box.x1 || next.y < wanderer.box.y0 || next.y > wanderer.box.y1){ + return false; + } + if (!standable(*m_world.world, next) || m_world.world->occupied(next) != StoryWorld::NOBODY){ + return false; + } + if (nearest_tile(m_player.pos) == next){ + return false; + } + for (const SimWanderer& other : m_wanderers){ + if (&other != &wanderer && other.pos == next){ + return false; + } + } + return true; +} + +void GridSim::step_wanderer(SimWanderer& wanderer){ + const uint32_t choice = step_rng(wanderer.seed) % 5; + if (choice >= 4){ + return; + } + const Direction dir = static_cast(choice); + const TilePos next = wanderer.pos.next(dir); + if (can_wander_to(wanderer, next)){ + wanderer.pos = next; + } +} + +void GridSim::advance_wanderer(SimWanderer& wanderer, Milliseconds time){ + wanderer.elapsed += time; + while (wanderer.step_interval > 0ms && wanderer.elapsed >= wanderer.step_interval){ + wanderer.elapsed -= wanderer.step_interval; + step_wanderer(wanderer); + } +} + +namespace detail{ +void sim_advance_time(GridSim& sim, Milliseconds time){ + for (SimWanderer& wanderer : sim.m_wanderers){ + sim.advance_wanderer(wanderer, time); + } +} + +const std::vector& sim_wanderers(const GridSim& sim){ + return sim.m_wanderers; +} + +void sim_add_trigger(GridSim& sim, SimTrigger trigger){ + sim.m_world.triggers.push_back(std::move(trigger)); +} +const std::vector& sim_triggers(const GridSim& sim){ + return sim.m_world.triggers; +} +void sim_forget_warp(GridSim& sim){ + sim.m_player.warped.reset(); +} +void sim_fight(GridSim& sim){ + if (sim.m_player.scene){ + sim.m_player.scenes_fought.push_back(*sim.m_player.scene); + } + sim.end_dialogue(); +} +} // namespace detail + +bool GridSim::wanderer_at(const TilePos& pos) const{ + for (const SimWanderer& wanderer : m_wanderers){ + if (wanderer.pos == pos){ + return true; + } + } + return false; } // Moves into the next tile toward `direction`, `part` of the way (a whole @@ -143,13 +246,21 @@ std::optional GridSim::enter_next(Direction direction, int part, int& m part = 2 * SIM_TILE; }else if (!landing && (is_door(world, ahead[0]) || std::find(m_world.doors.begin(), m_world.doors.end(), ahead[0]) != m_world.doors.end())){ m_player.pos = sim_pos(ahead[0]); - m_player.warped = ahead[0]; moved += SIM_TILE; + if (const std::optional stop = arrive()){ + return stop; + } + m_player.warped = ahead[0]; return SimStop::WARP; }else if (!landing){ return SimStop::BLOCKED; } } + for (const TilePos& pos : ahead){ + if (wanderer_at(pos)){ + return SimStop::BLOCKED; + } + } // Off the grid, both tiles must be open: a door frame or a corner stops us. for (const TilePos& pos : ahead){ if (ahead.size() > 1 && !standable(world, pos)){ @@ -168,7 +279,9 @@ std::optional GridSim::arrive(){ const bool fired = std::find(m_player.fired.begin(), m_player.fired.end(), trigger.name) != m_player.fired.end(); if (!fired && std::find(trigger.tiles.begin(), trigger.tiles.end(), tile) != trigger.tiles.end()){ m_player.fired.push_back(trigger.name); + m_player.fired.insert(m_player.fired.end(), trigger.spends.begin(), trigger.spends.end()); m_player.dialog = true; + m_player.scene = trigger.name; return SimStop::DIALOG; } } @@ -190,6 +303,7 @@ SimMove GridSim::advance(Direction direction, int distance){ if (m_player.dialog){ return {.stop = SimStop::DIALOG}; } + m_player.warped.reset(); int moved = 0; while (moved < distance){ const int offset = along(m_player.pos, direction) % SIM_TILE; @@ -222,6 +336,7 @@ SimMove GridSim::tap(Direction direction, Milliseconds hold, bool stick){ if (!stick){ distance = std::max(1, (int)((hold + tile_time / 2) / tile_time)) * SIM_TILE; } + sim_advance_time(*this, hold); SimMove move = advance(direction, distance); move.time = hold; return move; @@ -233,6 +348,7 @@ SimMove GridSim::hold(Direction direction, Milliseconds limit, SimPace pace){ int moved = 0; SimStop stop = SimStop::LIMIT; while (moved < tiles * SIM_TILE){ + sim_advance_time(*this, tile_time); const SimMove step = advance(direction, SIM_TILE); moved += step.distance; if (step.stop != SimStop::DONE){ @@ -261,6 +377,11 @@ bool GridSim::press_a(){ m_player.trainer = trainer.name; } } + for (const SimWanderer& wanderer : m_wanderers){ + if (wanderer.pos == faced){ + m_player.dialog = true; + } + } return m_player.dialog; } @@ -269,15 +390,18 @@ void GridSim::end_dialogue(){ m_player.fought.push_back(*m_player.trainer); } m_player.trainer.reset(); + m_player.scene.reset(); m_player.dialog = false; } +namespace detail{ bool sim_can_step(const GridSim& sim, Direction direction){ GridSim probe = sim; const SimMove move = probe.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); return move.distance > 0; } +} // namespace detail namespace{ @@ -297,14 +421,90 @@ WalkStop walk_stop(SimStop stop){ return WalkStop::LIMIT; } +// The escape policy's game steps on a scripted battle. +class SimWildBattleEscape : public WildBattleEscapeActions{ +public: + SimWildBattleEscape(const SimWildBattle& battle, std::vector& notes) + : m_refusals_left(battle.run_refusals) + , m_notes(notes) + {} + virtual WildRunOutcome run() override{ + if (m_refusals_left == 0){ + return WildRunOutcome::ESCAPED; + } + m_refusals_left--; + return WildRunOutcome::TRAPPED; + } + virtual void fight() override{ + m_notes.push_back("[Sim escape] Fought with the best move until the battle ended."); + } + virtual void note(const std::string& text) override{ + m_notes.push_back("[Sim escape] " + text); + } + +private: + size_t m_refusals_left; + std::vector& m_notes; +}; + } // namespace +std::optional GridSimRouteIO::take_wall_encounter(const RouteWallWalk& walk){ + const auto found = std::find_if(m_wall_encounters.begin(), m_wall_encounters.end(), [&](const SimWallEncounter& encounter){ + return encounter.direction == walk.direction && encounter.label == walk.label; + }); + if (found == m_wall_encounters.end()){ + return std::nullopt; + } + SimWallEncounter encounter = *found; + m_wall_encounters.erase(found); + return encounter; +} + +void GridSimRouteIO::escape_scripted_battle(const SimWildBattle& battle, const std::string& label){ + SimWildBattleEscape actions(battle, m_notes); + const WildEscapeResult result = escape_wild_battle(actions, WildBattleEscapePolicy()); + if (result == WildEscapeResult::UNCONFIRMED){ + note(std::format("escape_wild_battle: {}: the Run attempts ran out without the exit.", label), RouteNote::FAILURE); + } + const std::string_view ended = result == WildEscapeResult::FOUGHT ? "fought to its end" : "run from"; + m_notes.push_back(std::format("[Sim] {}: wild battle {}.", label, ended)); +} + +bool GridSimRouteIO::grass_battle(const TilePos& tile){ + if (m_grass.every == 0 || m_sim.world().tile(tile) != TileKind::TALL_GRASS){ + return false; + } + if (++m_grass_tiles < m_grass.every){ + return false; + } + m_grass_tiles = 0; + return true; +} + +// A grass battle on the hold does not stop it: the hold goes on to the +// wall after it, as a scripted one's does. WalkResult GridSimRouteIO::walk_to_wall(const RouteWallWalk& walk){ + size_t wild_battles = 0; + if (const auto encounter = take_wall_encounter(walk)){ + escape_scripted_battle(encounter->battle, walk.label); + wild_battles = 1; + } const SimPace pace = walk.options.pace == DpadPace::RUN ? SimPace::RUN : SimPace::WALK; + TilePos stepped = nearest_tile(m_sim.player().pos); const SimMove move = m_sim.hold(walk.direction, walk.limit, pace); + for (int tile = 0; tile < move.distance / SIM_TILE; tile++){ + stepped = stepped.next(walk.direction); + if (grass_battle(stepped)){ + escape_scripted_battle(SimWildBattle{}, walk.label); + wild_battles++; + } + } m_notes.push_back(std::format("[Sim] {}: held {} to {} at {}.", walk.label, direction_name(walk.direction), sim_stop_name(move.stop), to_string(m_sim.player().pos))); - return {.stop = walk_stop(move.stop), .walked = move.time, .wild_battles = 0, .moved_chunks = (size_t)(move.distance / SIM_TILE)}; + WalkResult result{.stop = walk_stop(move.stop), .walked = move.time, .wild_battles = wild_battles, .moved_chunks = (size_t)(move.distance / SIM_TILE)}; + result.warp.fade = move.stop == SimStop::WARP ? WarpFade::BLACK : WarpFade::NONE; + return result; } std::optional GridSimRouteIO::take_encounter(Direction direction, size_t tiles, size_t tap, const std::string& label){ @@ -328,9 +528,12 @@ WalkResult GridSimRouteIO::walk_taps(Direction direction, size_t tiles, const st size_t still = 0; size_t moved_at_battle = 0; for (size_t tap = 0; tap < tiles && result.stop == WalkStop::LIMIT; tap++){ - const auto encounter = take_encounter(direction, tiles, tap + 1, label); + std::optional encounter = take_encounter(direction, tiles, tap + 1, label); const SimMove move = encounter && encounter->phase == SimEncounterPhase::BEFORE_MOVEMENT ? SimMove{} : m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + if (!encounter && move.distance > 0 && grass_battle(nearest_tile(m_sim.player().pos))){ + encounter = SimWildTap{.label = label, .direction = direction, .requested_tiles = tiles, .tap = tap + 1}; + } result.walked += 800ms; if (encounter){ // Match the production escape_battle() credit, independently @@ -354,6 +557,7 @@ WalkResult GridSimRouteIO::walk_taps(Direction direction, size_t tiles, const st result.moved_chunks += move.distance > 0 ? 1 : 0; if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ result.stop = walk_stop(move.stop); + result.warp.fade = move.stop == SimStop::WARP ? WarpFade::BLACK : WarpFade::NONE; }else if (still >= 2){ result.stop = WalkStop::BLOCKED; } @@ -380,6 +584,7 @@ void GridSimRouteIO::press(const RouteInput& input){ break; case RouteInputKind::WAIT: case RouteInputKind::PAUSE: + sim_advance_time(m_sim, input.hold * input.count); break; } } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h index 426c566185..b0bee7418e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim.h @@ -65,10 +65,12 @@ Pokemon::TilePos nearest_tile(const SimPos& pos); std::string to_string(const SimPos& pos); // A scene that starts when the player steps onto one of `tiles` (a coord -// event): its dialogue opens and the player stops. It fires once. +// event): its dialogue opens and the player stops. It fires once, and +// spends the triggers named in `spends` with it: the same scene's. struct SimTrigger{ std::string name; std::vector tiles; + std::vector spends = {}; }; } // namespace detail @@ -93,12 +95,40 @@ using detail::SimTrigger; // the tiles that warp like doors though the maps draw them as walls (a // house's stairs, entered from beside them); and, if the caller knows, // whether B runs from here on (the Running Shoes, 00.03). +// A person who wanders pseudo-randomly within their wander box. +struct SimWanderer{ + std::string name; + Pokemon::TileBox box; // wander boundary in world tiles + Pokemon::TilePos pos; // current position + uint64_t seed = 0; // PRNG seed for deterministic walk + Milliseconds step_interval = Milliseconds(2000); // how often the NPC attempts a move + Milliseconds elapsed = Milliseconds(0); // time accumulated towards next step + Milliseconds time_offset = Milliseconds(0); // initial start time offset +}; + +// Simulated grid environment. +class GridSim; +namespace detail{ +// Advance simulation time. +void sim_advance_time(GridSim& sim, Milliseconds time); +// Get simulated wanderers. +const std::vector& sim_wanderers(const GridSim& sim); +// Add a simulated trigger. +void sim_add_trigger(GridSim& sim, SimTrigger trigger); +// Get simulated triggers. +const std::vector& sim_triggers(const GridSim& sim); +// Forget warp state. +void sim_forget_warp(GridSim& sim); +// Set simulated fight. +void sim_fight(GridSim& sim); +} // namespace detail struct SimWorld{ const StoryWorld* world = nullptr; std::vector trainers = {}; std::vector triggers = {}; std::vector doors = {}; std::optional can_run = std::nullopt; + std::vector wanderers = {}; }; // Reason why simulated player movement stopped. @@ -109,8 +139,10 @@ enum class SimStop{ WARP, // stepped onto a door LIMIT, // a held walk ran out of time }; +namespace detail{ // Returns the debug string for a SimStop reason. std::string_view sim_stop_name(SimStop stop); +} // namespace detail // What one input did. struct SimMove{ @@ -129,6 +161,10 @@ struct SimPlayer{ bool dialog = false; // The trainer whose dialogue is open, if one is. std::optional trainer; + // The scene (SimTrigger) whose dialogue is open, if one is. + std::optional scene; + // Scenes whose dialogue was fought as a trainer's (sim_fight()). + std::vector scenes_fought = {}; // The door the last warp stepped onto. std::optional warped; std::vector fought = {}; @@ -167,16 +203,43 @@ class GridSim{ } private: + friend void detail::sim_advance_time(GridSim& sim, Milliseconds time); + friend const std::vector& detail::sim_wanderers(const GridSim& sim); + friend void detail::sim_add_trigger(GridSim& sim, SimTrigger trigger); + friend const std::vector& detail::sim_triggers(const GridSim& sim); + friend void detail::sim_forget_warp(GridSim& sim); + friend void detail::sim_fight(GridSim& sim); + SimMove advance(Pokemon::Direction direction, int distance); std::optional enter_next(Pokemon::Direction direction, int part, int& moved); std::optional arrive(); + void advance_wanderer(SimWanderer& wanderer, Milliseconds time); + void step_wanderer(SimWanderer& wanderer); + bool can_wander_to(const SimWanderer& wanderer, const Pokemon::TilePos& next) const; + bool wanderer_at(const Pokemon::TilePos& pos) const; SimWorld m_world; SimPlayer m_player; + std::vector m_wanderers; }; +namespace detail{ +// Advances simulated time for world events and wandering NPCs. +void sim_advance_time(GridSim& sim, Milliseconds time); +// The wandering NPCs on the simulation's world. +const std::vector& sim_wanderers(const GridSim& sim); +// A scene's trigger on the world the player is on, from now on. +void sim_add_trigger(GridSim& sim, SimTrigger trigger); +// The scene triggers on the world the player is on. +const std::vector& sim_triggers(const GridSim& sim); +// A new step starts: the warp a step before stepped onto is not this one's. +void sim_forget_warp(GridSim& sim); +// The open dialogue is fought as a trainer's: a scene's is noted in +// SimPlayer::scenes_fought, as it is pressed through under a walk. +void sim_fight(GridSim& sim); // Whether the player could take a step toward `direction` from where they stand. bool sim_can_step(const GridSim& sim, Pokemon::Direction direction); +} // namespace detail // A deterministic, already-cleared encounter at a tap boundary. This is @@ -193,14 +256,44 @@ struct SimWildTap{ WalkOrigin origin = WalkOrigin::CURRENT_LEG; }; +// A scripted wild battle, as the escape policy's game steps see it: how +// many Run presses the game refuses ("Can't escape!": Bind, Wrap) before +// one works. Not a model of the battle itself. +struct SimWildBattle{ + size_t run_refusals = 0; +}; +// A wild battle that interrupts the walk to a wall (walk_to_wall()) with +// this label toward this direction, once; the hold goes on to the wall +// after it, as the console's does. +struct SimWallEncounter{ + std::string label; + Pokemon::Direction direction = Pokemon::Direction::NORTH; + SimWildBattle battle; +}; +// Wild battles in tall grass on every pass: one each `every` grass tiles +// the player steps onto, counted across walks, each run from at once. A +// fixed count, not the game's dice, so a route that crosses the grass +// again after each battle's replan meets a battle every time (00.04 on +// Route 201's row 5, lab-B 2026-11-09 16:14: a battle on each of four +// passes of 10 grass tiles). 0: no grass battles. +struct SimGrassBattles{ + size_t every = 0; +}; + // The walker's RouteIO on a GridSim. A failure throws GridSimFailure. class GridSimRouteIO : public RouteIO{ public: // Every line noted goes to `notes`, which must outlive this. - GridSimRouteIO(GridSim& sim, std::vector& notes, std::vector encounters = {}) + GridSimRouteIO( + GridSim& sim, std::vector& notes, + std::vector encounters = {}, std::vector wall_encounters = {}, + SimGrassBattles grass = {} + ) : m_sim(sim) , m_notes(notes) , m_encounters(std::move(encounters)) + , m_wall_encounters(std::move(wall_encounters)) + , m_grass(grass) {} virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override; @@ -213,10 +306,19 @@ class GridSimRouteIO : public RouteIO{ private: std::optional take_encounter(Pokemon::Direction direction, size_t tiles, size_t tap, const std::string& label); + std::optional take_wall_encounter(const RouteWallWalk& walk); + // The escape policy on `battle`; notes a FAILURE where the console + // would fail the program. + void escape_scripted_battle(const SimWildBattle& battle, const std::string& label); + // Whether stepping onto `tile` sets off a grass battle (SimGrassBattles). + bool grass_battle(const Pokemon::TilePos& tile); GridSim& m_sim; std::vector& m_notes; std::vector m_encounters; + std::vector m_wall_encounters; + SimGrassBattles m_grass; + size_t m_grass_tiles = 0; // grass tiles stepped onto since the last grass battle }; // What GridSimRouteIO throws for RouteNote::FAILURE. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp index 76e6cc9d35..56d9c6c25d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_GridSim_Tests.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" @@ -28,14 +29,18 @@ #include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" #include "Pokemon/AutoStory/Types/Pokemon_StoryActionArg.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" +#include "PokemonBDSP_AutoStory_OldStorySteps.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" #include "PokemonBDSP_AutoStory_GridSim_Tests.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonBDSP{ +using namespace detail; namespace{ @@ -47,10 +52,12 @@ using Pokemon::story_arg; using Pokemon::Pose; using Pokemon::StoryStep; using Pokemon::StoryStepKind; +using Pokemon::TileBox; using Pokemon::TilePos; -StoryWorld make_world(const std::vector& rows){ +// A map of `rows`, with someone wandering `wander` if given. +StoryWorld make_world(const std::vector& rows, const std::optional& wander = std::nullopt){ Pokemon::MapData map; map.name = "Test"; map.tiles = Pokemon::Grid{(int)rows[0].size(), (int)rows.size(), {}}; @@ -59,6 +66,10 @@ StoryWorld make_world(const std::vector& rows){ map.tiles.cells.push_back(*Pokemon::tile_from_glyph(glyph)); } } + if (wander){ + map.objects.push_back({.name = "wanderer", .x = wander->x0, .y = wander->y0, .facing = std::nullopt, + .wander = wander, .trainer = std::nullopt, .hide_flag = std::nullopt}); + } StoryWorld world; world.add("Test", map, {0, 0}); return world; @@ -218,11 +229,16 @@ SimWalk walk_on_sim(const SimRoute& route, bool stick_turns){ RouteIO& io = stick_turns ? static_cast(stick_io) : sim_io; RouteTrainers trainers{story_trainers(*route.world), [&sim](const std::string&){ sim.end_dialogue(); }}; const std::vector& targets = route.targets; + std::vector avoid = wandering_hazards(*route.world); + std::erase_if(avoid, [&](const TilePos& pos){ + return std::find(route.from.begin(), route.from.end(), pos) != route.from.end() + || std::find(targets.begin(), targets.end(), pos) != targets.end(); + }); try{ out.believed = walk_route(io, *route.world, route.from, trainers, { .goal = [&targets](const TilePos& pos){ return std::find(targets.begin(), targets.end(), pos) != targets.end(); }, .label = route.label, - .avoid = {}, + .avoid = std::move(avoid), .costs = route.costs, .speed = route.can_run ? MoveSpeed::RUN : MoveSpeed::WALK, }); @@ -396,6 +412,492 @@ UnitTestResult test_door_routes(Logger& logger){ } +// The story's walking steps on a GridSim: the route walker's IO and walks +// until something stops us (as the story simulation walks them). Anything +// else fails the walk. +class WalkStepsIO : public StoryStepIO{ +public: + WalkStepsIO(GridSim& sim, GridSimRouteIO& route) + : m_sim(sim) + , m_route(route) + {} + + virtual RouteIO& route() override{ + return m_route; + } + virtual void fight(const std::string& trainer) override{ + unsupported("a fight with " + trainer); + } + virtual void walk_until_stopped(Direction direction, size_t tiles, const std::string& label) override{ + m_sim.tap(direction, ROUTE_TURN_TAP, false); + const Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); + const SimMove move = m_sim.hold(direction, limit, SimPace::WALK); + if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ + m_route.note(label + ": " + std::string(sim_stop_name(move.stop)) + " instead of a stop.", RouteNote::FAILURE); + } + } + virtual bool run_until_map(Direction, Milliseconds, const std::string& map, const std::string&) override{ + unsupported("a run onto " + map); + return false; + } + virtual WarpSeen run_into_door(Direction, bool, Milliseconds, Milliseconds, const std::string&) override{ + unsupported("a run into a door"); + return {}; + } + virtual std::optional tap_to_banner(Direction, const std::string& map, size_t) override{ + unsupported("taps to " + map + "'s banner"); + return std::nullopt; + } + virtual void settle(Button, const std::string& label, bool, const std::string&) override{ + unsupported(label + "'s settle"); + } + +private: + void unsupported(const std::string& what){ + m_route.note(what + " is not simulated here.", RouteNote::FAILURE); + } + + GridSim& m_sim; + GridSimRouteIO& m_route; +}; + +// Row `row`'s steps from `first` up to the one before `last`, and where +// the table has the player before `first`. +struct TableSteps{ + Pose start; + std::vector steps; +}; +std::optional table_steps(const std::string& row, const std::string& first, const std::string& last){ + const std::vector& table = story_checkpoints(); + const auto checkpoint = std::find_if(table.begin(), table.end(), [&row](const StoryCheckpoint& item){ return item.id == row; }); + if (checkpoint == table.end()){ + return std::nullopt; + } + std::optional out; + std::optional at = checkpoint->start ? std::optional(Pokemon::pose_of(*checkpoint->start)) : std::nullopt; + for (const StoryStep& step : checkpoint->steps){ + if (step.name == last){ + return out; + } + if (step.name == first && at){ + out = TableSteps{*at, {}}; + } + if (out){ + out->steps.push_back(step); + } + at = pose_after_step(at, step); + } + return std::nullopt; +} + +// Where each of `table`'s steps, walked on `sim` from wherever its player +// stands, left the player, and why the walk failed if it did. +struct StepsWalk{ + std::vector> ends; + std::string failure; +}; +StepsWalk walk_steps(GridSim& sim, const TableSteps& table){ + StepsWalk out; + std::vector notes; + GridSimRouteIO route_io(sim, notes); + WalkStepsIO io(sim, route_io); + StoryWalkSteps walk(io); + walk.begin_attempt("01.03"); + Pokemon::RunState state{.pose = table.start, .flags = {}}; + try{ + for (const StoryStep& step : table.steps){ + const Pokemon::Outcome outcome = step.kind == StoryStepKind::ROUTE ? walk.route(state, step) + : step.kind == StoryStepKind::LEGS ? walk.legs(state, step) + : Pokemon::outcome_failed("not_a_walk", step.name); + out.ends.emplace_back(step.name, sim.player().pos); + if (!outcome.succeeded()){ + out.failure = step.name + ": " + Pokemon::to_string(outcome); + break; + } + state.pose = step.pose_after ? Pokemon::pose_of(*step.pose_after) : outcome.pose ? *outcome.pose : state.pose; + } + }catch (const GridSimFailure& e){ + out.failure = e.message; + } + return out; +} +// Where `table`'s steps, walked from `start` instead of where the table +// has the player, failed or left the player off `checks`' tiles; empty if +// they did not. +std::string walk_misses(const StoryWorld& world, const TableSteps& table, const TilePos& start, + const std::vector>& checks, Logger& logger){ + GridSim sim({.world = &world, .trainers = story_trainers(world)}, start, Direction::SOUTH, true); + const StepsWalk walk = walk_steps(sim, table); + std::string ends; + for (const auto& [name, end] : walk.ends){ + ends += std::format(" {} {}", name, to_string(end)); + } + logger.log(std::format("from {}:{}{}", Pokemon::to_string(start), ends, walk.failure.empty() ? "" : ", failed: " + walk.failure)); + if (!walk.failure.empty()){ + return std::format("from {}: failed at {}: {}", Pokemon::to_string(start), to_string(sim.player().pos), walk.failure); + } + for (const auto& [name, tile] : checks){ + const auto end = std::find_if(walk.ends.begin(), walk.ends.end(), [&name](const auto& item){ return item.first == name; }); + if (end == walk.ends.end() || end->second != sim_pos(tile)){ + return std::format("from {}: {} ended{}, not on {}.", Pokemon::to_string(start), name, + end == walk.ends.end() ? " nowhere" : " at " + to_string(end->second), Pokemon::to_string(tile)); + } + } + return {}; +} + +// Roark's room the old way: counted taps across the room, down column 29 +// and onto his row from (15, 16), then west against the rock east of him +// and south against the wall. +TableSteps old_taps_across_roarks_room(){ + StoryStep taps; + taps.kind = StoryStepKind::LEGS; + taps.name = "above_roarks_row"; + taps.action = "legs"; + taps.args["legs"] = std::vector{ + {.direction = Direction::EAST, .tiles = 14}, {.direction = Direction::SOUTH, .tiles = 10}, + {.direction = Direction::WEST, .tiles = 2}, {.direction = Direction::SOUTH, .tiles = 2}, + }; + StoryStep walls; + walls.kind = StoryStepKind::LEGS; + walls.name = "beside_roarks_rock"; + walls.action = "to_wall"; + walls.args["legs"] = std::vector{{.direction = Direction::WEST, .tiles = 7}, {.direction = Direction::SOUTH, .tiles = 1}}; + return {Pokemon::tile_pose("OreburghMine", {TilePos{15, 16}}, Direction::SOUTH), {taps, walls}}; +} + +// lab-B 2026-11-08 11:55: a wild battle on 01.03's counted taps through +// Roark's room re-planned to the end of the interrupted leg, (15, 16), and +// the re-plan's open run south overshot a row; the taps after landed a row +// too far south, the walk west went under Roark's rocks, and no one +// answered the talk. From a row south of (15, 16), the old taps miss +// beside his rock (20, 29): the sim shows the console's failure. The +// wild battle itself: Recovery walk tests, "01.03 to Roark's corner". +UnitTestResult test_roarks_room_from_a_row_off(Logger& logger){ + const StoryWorld& world = *story_plan_world("OreburghMine", "OreburghMine"); + const std::string miss = walk_misses(world, old_taps_across_roarks_room(), {15, 17}, {{"beside_roarks_rock", {20, 29}}}, logger); + if (miss.empty()){ + return "The old taps across Roark's room reached (20, 29) from a row south: the test no longer shows the console's failure."; + } + return true; +} + +// lab-B 2026-11-08 15:31 to 15:54: 01.05's open walk west 3 from (5, 13), +// where Barry's push leaves us, to (2, 13) beside the Oreburgh Gate's mouth +// (1, 13) went on into the Gate. D-pad taps move whole tiles but keep a +// part-tile offset: 0.375 of a tile west of (5, 13), the three taps take +// the warp; on the tile, they stop beside it. +UnitTestResult test_gate_walk_part_tile_off(Logger&){ + const StoryWorld& world = *story_plan_world("OreburghCity", "OreburghCity"); + for (const bool off : {false, true}){ + GridSim sim({.world = &world}, story_to_world(world, "OreburghCity", {5, 13}), Direction::WEST, true); + if (off){ + sim.tap(Direction::WEST, 60ms, true); + } + SimStop stop = SimStop::DONE; + for (int tap = 0; tap < 3 && stop == SimStop::DONE; tap++){ + stop = sim.tap(Direction::WEST, 160ms, false).stop; + } + if ((stop == SimStop::WARP) != off){ + return std::format("{} (5, 13): three taps west ended {} at {}.", off ? "0.375 west of" : "on", + sim_stop_name(stop), to_string(sim.player().pos)); + } + } + return true; +} + +// lab-B 2026-11-08 18:41: 01.11's 8 taps west, then north, ended below the +// old man, and no one answered the old woman's talk. Floaroma's banner +// stops us on any of (10..12, 27..29): the old taps miss her from x 10 and +// 11; the table's walk west to the field's edge and 4 taps east end below +// her from all nine. +UnitTestResult test_old_couple_from_each_arrival(Logger& logger){ + const std::optional table = table_steps("01.11", "west_to_the_field_edge", "old_woman"); + const StoryWorld* world = story_plan_world("FloaromaTown", "FloaromaTown"); + if (!table || table->steps.empty() || world == nullptr){ + return "01.11 has no walk west to the field's edge, or Floaroma no map."; + } + const TableSteps old_taps{table->start, {old_west_along_the_field(), table->steps.back()}}; + const TilePos below_her = story_to_world(*world, "FloaromaTown", map_point("FloaromaTown", "old_woman").next(Direction::SOUTH)); + for (int x = 10; x <= 12; x++){ + for (int y = 27; y <= 29; y++){ + const TilePos start = story_to_world(*world, "FloaromaTown", {x, y}); + const std::string old_miss = walk_misses(*world, old_taps, start, {{"up_to_the_old_woman", below_her}}, logger); + if (old_miss.empty() != (x == 12)){ + return std::format("The old taps from ({}, {}): {}", x, y, old_miss.empty() ? "ended below her." : old_miss); + } + const std::string miss = walk_misses(*world, *table, start, {{"up_to_the_old_woman", below_her}}, logger); + if (!miss.empty()){ + return "The table's walk " + miss; + } + } + } + return true; +} + +UnitTestResult test_wandering_npc_mechanics(Logger& logger){ + StoryWorld world = make_world({ + "#######", + "#.....#", + "#.....#", + "#.....#", + "#######", + }); + SimWanderer wanderer{ + .name = "wanderer", + .box = {1, 1, 3, 3}, + .pos = {2, 2}, + .seed = 42, + .step_interval = 2000ms, + }; + GridSim sim({.world = &world, .wanderers = {wanderer}}, {1, 2}, Direction::EAST, false); + sim_advance_time(sim, 100000ms); + const SimWanderer& after = sim_wanderers(sim).front(); + if (after.pos.x < 1 || after.pos.x > 3 || after.pos.y < 1 || after.pos.y > 3){ + return "wanderer stepped outside its bounding box"; + } + GridSim sim2({.world = &world, .wanderers = {wanderer}}, {1, 2}, Direction::EAST, false); + sim_advance_time(sim2, 100000ms); + if (sim_wanderers(sim2).front().pos != after.pos){ + return "wanderer simulation is not deterministic across identical seeds"; + } + return true; +} + +UnitTestResult test_wandering_npc_collision_and_dialog(Logger& logger){ + StoryWorld world = make_world({ + "#####", + "#...#", + "#####", + }); + SimWanderer wanderer{ + .name = "blocker", + .box = {2, 1, 2, 1}, + .pos = {2, 1}, + .seed = 0, + .step_interval = 10000ms, + }; + GridSim sim({.world = &world, .wanderers = {wanderer}}, {1, 1}, Direction::EAST, false); + const SimMove move = sim.tap(Direction::EAST, 160ms, false); + if (move.stop != SimStop::BLOCKED || sim.player().pos != sim_pos({1, 1})){ + return "player was not blocked by wandering NPC"; + } + if (!sim.press_a()){ + return "pressing A facing wandering NPC failed to open dialogue"; + } + return true; +} + +UnitTestResult test_wandering_npc_routes_multi_seed(Logger& logger){ + const StoryWorld* world = story_plan_world("OreburghCity", "OreburghCity"); + if (world == nullptr){ + return "OreburghCity world not found"; + } + const TilePos start = story_to_world(*world, "OreburghCity", {26, 22}); + const TilePos target = story_to_world(*world, "OreburghCity", {46, 58}); + const TileBox hiker_box{ + story_to_world(*world, "OreburghCity", {46, 25}).x, + story_to_world(*world, "OreburghCity", {46, 25}).y, + story_to_world(*world, "OreburghCity", {48, 27}).x, + story_to_world(*world, "OreburghCity", {48, 27}).y + }; + const TilePos hiker_home = story_to_world(*world, "OreburghCity", {47, 26}); + const std::vector seeds = {0, 1, 2, 7, 42, 100, 999, 1337}; + const std::vector start_times = {0ms, 500ms, 1200ms, 2000ms, 3500ms, 5000ms}; + for (uint64_t seed : seeds){ + for (Milliseconds start_time : start_times){ + SimWanderer hiker{ + .name = "hiker_0", + .box = hiker_box, + .pos = hiker_home, + .seed = seed, + .step_interval = 2000ms, + .time_offset = start_time, + }; + GridSim sim({.world = world, .trainers = story_trainers(*world), .wanderers = {hiker}}, start, Direction::NORTH, true); + std::vector notes; + GridSimRouteIO sim_io(sim, notes); + RouteTrainers trainers{story_trainers(*world), [&sim](const std::string&){ sim.end_dialogue(); }}; + const auto result = walk_route(sim_io, *world, {start}, trainers, { + .goal = [&](const TilePos& pos){ return pos == target; }, + .label = "01.03 above_the_mine", + .avoid = {}, + .costs = *story_route_costs("town"), + .speed = MoveSpeed::RUN, + }); + if (result.empty() || result.front() != target || nearest_tile(sim.player().pos) != target){ + return std::format("route failed for seed {} and start_time {} ms", seed, start_time.count()); + } + } + } + return true; +} + +// Routes never run along a wander zone, but cross one: a row someone +// wanders, (2..4, 2), crossed south at (3, 2) while they stand there. +UnitTestResult test_wandering_npc_wait_clearance(Logger& logger){ + const TileBox row_zone{.x0 = 2, .y0 = 2, .x1 = 4, .y1 = 2}; + const StoryWorld room = make_world({"#######", "#.....#", "#.....#", "#.....#", "#.....#", "#######"}, row_zone); + const StoryWorld* world = &room; + const TilePos start{3, 1}; + const TilePos target{3, 4}; + SimWanderer hiker{ + .name = "hiker_0", + .box = row_zone, + .pos = {3, 2}, + .seed = 2, + .step_interval = 2000ms, + }; + GridSim sim({.world = world, .trainers = {}, .wanderers = {hiker}}, start, Direction::NORTH, true); + std::vector notes; + GridSimRouteIO sim_io(sim, notes); + RouteTrainers trainers{{}, [&sim](const std::string&){ sim.end_dialogue(); }}; + const auto result = walk_route(sim_io, *world, {start}, trainers, { + .goal = [&](const TilePos& pos){ return pos == target; }, + .label = "walk_through_hiker", + .avoid = {}, + .costs = *story_route_costs("town"), + .speed = MoveSpeed::RUN, + }); + if (result.empty() || result.front() != target){ + return "wait clearance route did not reach target"; + } + bool saw_blocked_note = false; + for (const std::string& n : notes){ + if (n.find("waiting for the way to clear") != std::string::npos){ + saw_blocked_note = true; + break; + } + } + if (!saw_blocked_note){ + return "expected route to encounter blocked wanderer and wait for clearance"; + } + return true; +} + +UnitTestResult test_wandering_npc_oreburgh_north_multi_seed(Logger& logger){ + const StoryWorld* world = story_plan_world("OreburghCity", "OreburghCity"); + if (world == nullptr){ + return "OreburghCity world not found"; + } + const TilePos start = story_to_world(*world, "OreburghCity", {46, 52}); + const TilePos target = story_to_world(*world, "OreburghCity", {46, 21}); + const TileBox hiker_box{ + story_to_world(*world, "OreburghCity", {46, 25}).x, + story_to_world(*world, "OreburghCity", {46, 25}).y, + story_to_world(*world, "OreburghCity", {48, 27}).x, + story_to_world(*world, "OreburghCity", {48, 27}).y + }; + const TilePos hiker_home = story_to_world(*world, "OreburghCity", {47, 26}); + const std::vector seeds = {0, 1, 2, 7, 42, 100, 999, 1337}; + const std::vector start_times = {0ms, 500ms, 1200ms, 2000ms, 3500ms, 5000ms}; + for (uint64_t seed : seeds){ + for (Milliseconds start_time : start_times){ + SimWanderer hiker{ + .name = "hiker_0", + .box = hiker_box, + .pos = hiker_home, + .seed = seed, + .step_interval = 2000ms, + .time_offset = start_time, + }; + GridSim sim({.world = world, .trainers = story_trainers(*world), .wanderers = {hiker}}, start, Direction::NORTH, true); + std::vector notes; + GridSimRouteIO sim_io(sim, notes); + RouteTrainers trainers{story_trainers(*world), [&sim](const std::string&){ sim.end_dialogue(); }}; + const auto result = walk_route(sim_io, *world, {start}, trainers, { + .goal = [&](const TilePos& pos){ return pos == target; }, + .label = "01.03 oreburgh_north", + .avoid = {}, + .costs = *story_route_costs("town"), + .speed = MoveSpeed::RUN, + }); + if (result.empty() || result.front() != target || nearest_tile(sim.player().pos) != target){ + return std::format("oreburgh north route failed for seed {} and start_time {} ms", seed, start_time.count()); + } + } + } + return true; +} + +class StalledWallLegRouteIO : public GridSimRouteIO{ +public: + StalledWallLegRouteIO(GridSim& sim, std::vector& notes) + : GridSimRouteIO(sim, notes) + {} + + virtual WalkResult walk_to_wall(const RouteWallWalk& walk) override{ + if (m_first_wall_call){ + m_first_wall_call = false; + return WalkResult{ + .stop = WalkStop::LIMIT, + .walked = 5000ms, + .wild_battles = 0, + .moved_chunks = 2, + }; + } + return GridSimRouteIO::walk_to_wall(walk); + } + +private: + bool m_first_wall_call = true; +}; + +UnitTestResult test_wall_leg_check_at_wall_short_distance_safeguard(Logger& logger){ + StoryWorld world = make_world({ + "########################", + "#......................#", + "########################", + }); + const TilePos start{1, 1}; + const TilePos target{22, 1}; + GridSim sim({.world = &world}, start, Direction::EAST, true); + std::vector notes; + StalledWallLegRouteIO sim_io(sim, notes); + RouteTrainers trainers{{}, [](const std::string&){}}; + try{ + walk_route(sim_io, world, {start}, trainers, { + .goal = [&](const TilePos& pos){ return pos == target; }, + .label = "test_check_at_wall_safeguard", + .avoid = {}, + .costs = *story_route_costs("town"), + .speed = MoveSpeed::RUN, + }); + return "check_at_wall falsely accepted leg stalled well short of expected distance"; + }catch (const GridSimFailure& f){ + if (f.message.find("short of the wall") != std::string::npos){ + return true; + } + return "caught unexpected failure: " + f.message; + } +} +// Oreburgh Mine B1F: the entrance hall corridor is traversed to and back by +// running south from (12, 1) to (12, 21), and north from (12, 21), where the +// coal room's warp lands us, to (12, 1). +UnitTestResult test_oreburgh_mine_hall_corridor(Logger& logger){ + const StoryWorld* world = story_plan_world("OreburghMineB1F", "OreburghMineB1F"); + if (world == nullptr){ + return "OreburghMineB1F world not found."; + } + const SimWorld sim_world{.world = world, .can_run = true}; + const auto test_run = [&](TilePos start, Direction dir, TilePos expected, std::string_view label){ + GridSim sim(sim_world, start, dir, true); + const SimMove move = sim.hold(dir, 5000ms, SimPace::RUN); + if (move.stop != SimStop::WARP || sim.player().pos != sim_pos(expected)){ + return std::format("{}: expected WARP at {}, got {} at {}.", label, + Pokemon::to_string(expected), sim_stop_name(move.stop), Pokemon::to_string(nearest_tile(sim.player().pos))); + } + logger.log(std::format("{} hall run reached {} in {} ms.", label, Pokemon::to_string(expected), move.time.count())); + return std::string{}; + }; + std::string err = test_run({12, 1}, Direction::SOUTH, {12, 21}, "Southbound"); + if (!err.empty()){ + return err; + } + err = test_run({12, 21}, Direction::NORTH, {12, 1}, "Northbound"); + return err.empty() ? UnitTestResult(true) : UnitTestResult(err); +} + struct AutoStoryGridSimInput{ std::string name; std::function body; @@ -443,6 +945,46 @@ const AutoStoryGridSimCase AUTO_STORY_GRID_SIM_CASES[] = { .input = {"a stick-tap turn misses the Sandgem Center and Jubilife School doors", test_door_routes}, .expectation = {}, }, + { + .input = {"01.03's old taps across Roark's room miss his rock from a row off (lab-B, 2026-11-08)", test_roarks_room_from_a_row_off}, + .expectation = {}, + }, + { + .input = {"wandering NPC movement and deterministic seed behavior", test_wandering_npc_mechanics}, + .expectation = {}, + }, + { + .input = {"wandering NPC collision stops player and opens dialogue", test_wandering_npc_collision_and_dialog}, + .expectation = {}, + }, + { + .input = {"01.03 above_the_mine paths through wanderer zone across seeds and start times", test_wandering_npc_routes_multi_seed}, + .expectation = {}, + }, + { + .input = {"wandering NPC collision without avoid waits for clearance and resumes", test_wandering_npc_wait_clearance}, + .expectation = {}, + }, + { + .input = {"01.03 oreburgh_north paths straight up column 46 across seeds and start times", test_wandering_npc_oreburgh_north_multi_seed}, + .expectation = {}, + }, + { + .input = {"check_at_wall safeguard rejects legs stalled well short of expected distance", test_wall_leg_check_at_wall_short_distance_safeguard}, + .expectation = {}, + }, + { + .input = {"01.03, Oreburgh Mine B1F entrance hall corridor runs to and back", test_oreburgh_mine_hall_corridor}, + .expectation = {}, + }, + { + .input = {"01.05, a part of a tile off, the old open walk west takes the Gate's warp (lab-B, 2026-11-08)", test_gate_walk_part_tile_off}, + .expectation = {}, + }, + { + .input = {"01.11, the old woman from each tile Floaroma's banner stops us on (lab-B, 2026-11-08)", test_old_couple_from_each_arrival}, + .expectation = {}, + }, }; void add_tests_AutoStory_GridSim(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.cpp new file mode 100644 index 0000000000..d2b6949704 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.cpp @@ -0,0 +1,191 @@ +/* BDSP AutoStory Leg Trace Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The leg records (Pokemon_LegTrace.h) the story's walks write when a row + * runs on the simulation are the route the console should walk too: + * devtools/maps/leg_trace.py compares a console log's records with them. + * The golden copy is checked in beside this file, so a change to the + * route shows as its diff in review. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Filesystem/FileIO.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/Navigation/Pokemon_LegTrace.h" +#include "PokemonBDSP_AutoStory_LegTrace_Tests.h" +#include "PokemonBDSP_AutoStory_StorySim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +namespace{ + +// The rows with a golden trace. +const std::string TRACED_ROW = "00.04"; + +// The leg records' JSON of row `row` run alone on the simulation, or the +// run's failure. +struct SimTrace{ + std::vector legs; + std::string error; +}; +SimTrace sim_leg_trace(Logger& logger, const std::string& row){ + SimExecutor executor(logger); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = row, .to = row}); + SimTrace out; + if (!report.completed){ + out.error = "the row failed on the simulation: " + executor.result().error; + } + const std::string tag = std::string(Pokemon::LEG_TRACE_TAG); + for (const std::string& note : executor.notes()){ + if (note.starts_with(tag)){ + out.legs.push_back(note.substr(tag.size())); + } + } + return out; +} + +// The trace file's text, a leg a line, as devtools/maps/leg_trace.py reads +// it ({"about", "legs"}). +std::string trace_text(const std::string& row, const std::vector& legs){ + std::string out = "{\n"; + out += std::format(" \"about\": \"Leg records of BDSP AutoStory row {} run on the grid simulation " + "(Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.cpp). Rewrite with PA_UPDATE_LEG_TRACE=1.\",\n", row); + out += " \"legs\": [\n"; + for (size_t i = 0; i < legs.size(); i++){ + out += " " + legs[i] + (i + 1 < legs.size() ? ",\n" : "\n"); + } + return out + " ]\n}\n"; +} + +// The golden file, beside this file. +std::string golden_path(const std::string& row){ + const std::string self = __FILE__; + const size_t slash = self.find_last_of("/\\"); + return (slash == std::string::npos ? std::string() : self.substr(0, slash + 1)) + "leg_trace_" + row + ".golden.json"; +} + +// The first line where `a` and `b` differ, both without carriage returns. +std::string first_difference(const std::string& golden, const std::string& traced){ + size_t line = 1; + size_t begin = 0; + while (begin < golden.size() || begin < traced.size()){ + const size_t end_a = std::min(golden.find('\n', begin), golden.size()); + const size_t end_b = std::min(traced.find('\n', begin), traced.size()); + const std::string a = begin < golden.size() ? golden.substr(begin, end_a - begin) : ""; + const std::string b = begin < traced.size() ? traced.substr(begin, end_b - begin) : ""; + if (a != b){ + return std::format("line {}:\n--- golden: {}\n+++ traced: {}", line, a, b); + } + begin = end_a + 1; + line++; + } + return ""; +} + +UnitTestResult test_golden_trace(Logger& logger){ + const SimTrace trace = sim_leg_trace(logger, TRACED_ROW); + if (!trace.error.empty()){ + return trace.error; + } + if (trace.legs.empty()){ + return std::format("row {} wrote no leg records.", TRACED_ROW); + } + const std::string text = trace_text(TRACED_ROW, trace.legs); + const std::string path = golden_path(TRACED_ROW); + // code-health: allow char_pointer -- std::getenv returns a const char pointer + const char* update = std::getenv("PA_UPDATE_LEG_TRACE"); + if (update != nullptr && update[0] != '\0' && update[0] != '0'){ + std::string crlf; + for (char ch : text){ + crlf += ch == '\n' ? std::string("\r\n") : std::string(1, ch); + } + FileIO file; + if (!file.open(path, FileMode::WRITE | FileMode::BINARY) || file.write(crlf) != crlf.size()){ + return "Could not write " + path + "."; + } + logger.log("Wrote " + path + "."); + return true; + } + std::string golden; + if (!file_to_string(path, golden)){ + return "Could not read " + path + "."; + } + std::erase(golden, '\r'); + const std::string difference = first_difference(golden, text); + if (difference.empty()){ + return true; + } + return "The simulation's leg records differ from " + path + ". If the route change is meant, rerun with " + "PA_UPDATE_LEG_TRACE=1 and review the file's diff. First difference at " + difference; +} + +UnitTestResult test_stable_trace(Logger& logger){ + const SimTrace first = sim_leg_trace(logger, TRACED_ROW); + const SimTrace second = sim_leg_trace(logger, TRACED_ROW); + if (first.legs == second.legs){ + return true; + } + return "Two runs of the same row wrote different leg records: " + first_difference( + trace_text(TRACED_ROW, first.legs), trace_text(TRACED_ROW, second.legs)); +} + + +struct LegTraceInput{ + std::string name; + std::function body; +}; +struct LegTraceExpectation{ +}; +struct LegTraceCase{ + LegTraceInput input; + LegTraceExpectation expectation; +}; + +class Test_AutoStoryLegTrace : public UnitTest{ +public: + explicit Test_AutoStoryLegTrace(LegTraceCase test_case) + : UnitTest("PokemonBDSP::AutoStory - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + LegTraceCase m_case; +}; + +const LegTraceCase LEG_TRACE_CASES[] = { + {.input = {"Leg trace: 00.04 on the simulation writes leg_trace_00.04.golden.json", test_golden_trace}, .expectation = {}}, + {.input = {"Leg trace: 00.04 on the simulation writes the same records every run", test_stable_trace}, .expectation = {}}, +}; + +} // namespace + + +void add_tests_AutoStory_LegTrace(UnitTestDatabase& database){ + for (const auto& item : LEG_TRACE_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.h new file mode 100644 index 0000000000..3d457733a8 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.h @@ -0,0 +1,25 @@ +/* BDSP AutoStory Leg Trace Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_LegTrace_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_LegTrace_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// The simulation's leg records of a row, against a golden copy beside this +// file, and the same on every run. +void add_tests_AutoStory_LegTrace(UnitTestDatabase& database); + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp new file mode 100644 index 0000000000..f5152c7a97 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.cpp @@ -0,0 +1,121 @@ +/* BDSP AutoStory - Old story steps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP_AutoStory_OldStorySteps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::Direction; +using Pokemon::GridPose; +using Pokemon::Pose; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + + +StoryStep r75_old_gate_exit(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "out_of_oreburgh_gate"; + step.action = "to_map"; + step.args["legs"] = std::vector{{.direction = Direction::WEST, .tiles = 8}}; + step.args["fight_wild"] = false; + step.pose_after = Pokemon::TileDeclared{.map = "Route203", .tiles = {TilePos{55, 9}}, .facing = Direction::WEST}; + return step; +} +Pose r75_pond_pocket(){ + std::vector tiles; + for (int y = 6; y <= 13; y++){ + for (int x = 49; x <= 54; x++){ + tiles.push_back({x, y}); + } + } + return Pokemon::tile_pose("Route203", tiles); +} + +StoryStep r81_old_cave_exit(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "out_of_the_ravaged_path"; + step.action = "to_wall"; + step.args["legs"] = std::vector{{.direction = Direction::SOUTH, .tiles = 4}}; + step.args["fight_wild"] = false; + step.pose_after = Pokemon::TileDeclared{.map = "Route204North", .tiles = {TilePos{20, 26}}, .facing = Direction::SOUTH}; + return step; +} +Pose r81_below_the_mouth(){ + return Pokemon::tile_pose("Route204North", {TilePos{20, 27}, TilePos{20, 28}, TilePos{20, 29}, TilePos{20, 30}}); +} + +StoryStep old_mine_hall_19(std::string name, Direction direction){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = std::move(name); + step.action = "legs"; + step.args["legs"] = std::vector{{.direction = direction, .tiles = 19}}; + step.args["fight_wild"] = false; + return step; +} + +StoryStep old_coal_room_crate_cut(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "to_roarks_corner"; + step.action = "legs"; + step.args["legs"] = std::vector{ + {.direction = Direction::EAST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 2}, + {.direction = Direction::WEST, .tiles = 1}, {.direction = Direction::SOUTH, .tiles = 5}, + {.direction = Direction::EAST, .tiles = 14}, {.direction = Direction::SOUTH, .tiles = 10}, + {.direction = Direction::SOUTH, .tiles = 2}, {.direction = Direction::WEST, .tiles = 11}, + }; + step.args["fight_wild"] = false; + return step; +} + +std::vector old_round_mom_to_the_mat(){ + StoryStep around; + around.kind = StoryStepKind::ROUTE; + around.name = "around_mom"; + around.action = "route"; + around.args["target"] = GridPose{.map = "PlayerHouse1F", .tiles = {TilePos{6, 9}}, .facing = Direction::SOUTH}; + around.args["fight_wild"] = false; + StoryStep step; + step.kind = StoryStepKind::STEP; + step.name = "to_moms_call"; + step.args["direction"] = Direction::SOUTH; + return {around, step}; +} + +StoryStep old_tap_into_the_gate(){ + StoryStep step; + step.kind = StoryStepKind::STEP; + step.name = "into_oreburgh_gate"; + step.action = "to_banner"; + step.args["direction"] = Direction::WEST; + step.pose_after = Pokemon::TileDeclared{.map = "OreburghGate", .tiles = {TilePos{27, 22}, TilePos{26, 22}}, .facing = Direction::WEST}; + return step; +} + +StoryStep old_west_along_the_field(){ + StoryStep step; + step.kind = StoryStepKind::LEGS; + step.name = "west_along_the_field"; + step.action = "legs"; + step.args["legs"] = std::vector{{.direction = Direction::WEST, .tiles = 8}}; + step.args["fight_wild"] = false; + return step; +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h new file mode 100644 index 0000000000..bbd64ad818 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_OldStorySteps.h @@ -0,0 +1,70 @@ +/* BDSP AutoStory - Old story steps + * + * From: https://github.com/PokemonAutomation/ + * + * Steps the story table had that went wrong on the console, as they were: + * the story simulation's regression tests run them in place of the + * table's step of the same name and check they still go wrong there. + * +// code-health: allow header_symbols -- legacy story steps definitions for test parity verification + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_OldStorySteps_H +#define PokemonAutomation_PokemonBDSP_AutoStory_OldStorySteps_H + +#include +#include +#include "Pokemon/AutoStory/Pokemon_StoryPose.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "Pokemon/AutoStory/Types/Pokemon_StoryStep.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// r75: out of the Oreburgh Gate as a run west until Route 203's banner +// (the old event west_until_transition()). The banner reads a few tiles +// in: the run ends west of the Gate's warp tile (55, 9), in the pocket by +// the pond (Route 203's x 49 to 54, rows 6 to 13). +Pokemon::StoryStep r75_old_gate_exit(); +// Where r75's run west ended: the pocket by Route 203's pond. +Pokemon::Pose r75_pond_pocket(); + +// r81: out of the Ravaged Path as a timed walk south (the old event's +// 4 s walk_dir()), its fade missed: on past cave_exit (20, 26) to the +// cliff, column 20 down to row 30. +Pokemon::StoryStep r81_old_cave_exit(); +// Where r81's walk south ended: below the Ravaged Path's mouth. +Pokemon::Pose r81_below_the_mouth(); + +// Oreburgh Mine B1F: tapping 19 tiles leaves the player 1 tile short of the warp door. +Pokemon::StoryStep old_mine_hall_19(std::string name, Pokemon::Direction direction); + +// Oreburgh Mine: stepping south at col 29 without bypassing the crate +// hits the wooden crate at (29, 28) on the south leg, a tile down. +Pokemon::StoryStep old_coal_room_crate_cut(); + +// 01.05's old tap into the Oreburgh Gate, west to its banner, after an +// open walk to the tile beside its mouth (1, 13) that slid onto the warp: +// the tap step began inside the Gate (lab-B 2026-11-08 15:31 to 15:54). +Pokemon::StoryStep old_tap_into_the_gate(); + +// 01.11's old walk toward the old woman: 8 taps west along the row +// Floaroma's banner stopped us on, from x 10 to 12, so north of it ended +// below the old man (lab-B 2026-11-08 18:41). +Pokemon::StoryStep old_west_along_the_field(); + +// 00.04's old walk round Mom to (6, 9) and step south onto the mat (6, 10) +// for her call: her call fired on (6, 9) at the walk's end, the walk took +// it for a trainer and pressed through it, the step went out of the door, +// and her hat scene saw no fade (lab-B 2026-11-09 17:29). The walker now +// hands such a scene to its step; the table runs into her call instead. +std::vector old_round_mom_to_the_mat(); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp new file mode 100644 index 0000000000..93561162a1 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.cpp @@ -0,0 +1,645 @@ +/* BDSP AutoStory - Console failure cases on the story simulation + * + * From: https://github.com/PokemonAutomation/ + * + * One case per failure console B showed in its events and perception + * (#268's design note, the planner note), run on the story simulation + * with the knobs that make it happen there (SimWorldKnobs, SimMisses): + * walks that slide on onto a warp, fades the walks' watchers miss or read + * as a battle, banners missed or gone, dim floors, late first lines and + * people who wander. + * + * A case the program fails today is on KNOWN_FAILING with the change that + * is to fix it. Its test passes while the case still fails, and fails + * once the case passes: then take it off the list. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RobustRoute.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP_AutoStory_OldStorySteps.h" +#include "PokemonBDSP_AutoStory_StorySim.h" +#include "PokemonBDSP_AutoStory_SimFailureCases_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +using namespace detail; + +namespace{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::GridPose; +using Pokemon::Pose; +using Pokemon::story_arg; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + +// Cases the program fails today, with what is to fix each. +const std::map KNOWN_FAILING{ + {"01.05 through_the_gate is one run west", "planner: goal kinds and ms costs (PLANNER_DESIGN.md)"}, + {"any one missed fade or banner from 00.00 to 01.11: every row still passes", + "a third signal where a warp gives one (ONE_SIGNAL_STEPS): position (PLANNER_DESIGN.md 2, 4)"}, + {"01.08 with Route 204's youngster wandering (12..14, 2)", "planner: one recovery rule, a sidestep round a wanderer (PLANNER_DESIGN.md 4, 7)"}, +}; + +// Warps that give one signal only (#268 slice 1: door = fade or banner), so +// a miss there leaves nothing to go on: a fade and no banner (stairs, into +// a building, between the mine's floors), or a banner and no fade (an open +// border crossed by run_until_map()). +const std::set ONE_SIGNAL_STEPS{ + "00.01 down_the_stairs", "00.01 into_barrys_house", "00.01 up_barrys_stairs", "00.01 down_barrys_stairs", + "00.04 into_the_house", "00.05 into_the_school", "01.03 into_the_coal_room", "01.03 up_to_the_hall", + "00.04 to_route_201", "01.10 into_floaroma", +}; + +// The table's step `name` in row `row`. +const StoryStep& table_step(const std::string& row, const std::string& name){ + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const StoryStep& step : checkpoint.steps){ + if (checkpoint.id == row && step.name == name){ + return step; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + name + " in " + row); +} + +// Runs rows `from` to `to` of `rows` with `misses` and `knobs`: "" if they +// all pass, else where and why the run stopped. +std::string run_case( + Logger& logger, const std::string& from, const std::string& to, + SimMisses misses, SimWorldKnobs knobs, const std::vector& rows = story_checkpoints() +){ + SimExecutor executor(logger, std::move(misses), std::move(knobs)); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = from, .to = to}, rows); + return report.completed ? "" : std::format("stopped in {}: {}", executor.result().failed_step, executor.result().error); +} +UnitTestResult passes(const std::string& stopped){ + return stopped.empty() ? UnitTestResult(true) : UnitTestResult(stopped); +} + +// The old 01.05 walk west along row 22 to the tile beside the west mouth's +// warp (3, 22), as before #269 stopped routes two short of warps. +StoryStep old_walk_beside_the_west_mouth(){ + StoryStep step = table_step("01.05", "through_the_gate"); + step.args["target"] = GridPose{"OreburghGate", {{4, 22}}, Direction::WEST}; + return step; +} + +// 01.05's walk west through the Gate whose last open leg runs a tile on; +// the old walk's slides onto the west mouth's warp to Route 203. +SimWorldKnobs gate_slide(SimFade fade, bool banner_up){ + const Pose far = Pokemon::pose_of(*table_step("01.05", "out_of_oreburgh_gate").pose_after); + return {.slides = {{.step = "through_the_gate", .direction = Direction::WEST, .tiles = 1, + .far = far, .fade = fade, .banner_up = banner_up}}}; +} +UnitTestResult gate_old_walk_slides(Logger& logger, SimFade fade, bool banner_up){ + const std::vector rows = table_with("01.05", old_walk_beside_the_west_mouth()); + return passes(run_case(logger, "01.05", "01.05", {.fade = {}, .banner = {}}, gate_slide(fade, banner_up), rows)); +} + +// The planner's legs for 01.05's walk through the Gate: one run west +// along row 22 works on the console; at most a hold to find the row first. +UnitTestResult gate_plan_one_run(Logger& logger){ + const StoryWorld* world = story_plan_world("OreburghGate", "OreburghGate"); + const std::vector from{story_to_world(*world, "OreburghGate", {27, 22}), story_to_world(*world, "OreburghGate", {26, 22})}; + const TilePos goal = story_to_world(*world, "OreburghGate", {5, 22}); + const auto plan = plan_recovered_route(*world, from, [&](const TilePos& pos){ return pos == goal; }, *story_route_costs(table_step("01.05", "through_the_gate").action)); + if (!plan){ + return "no plan"; + } + std::string legs; + for (const PlannedLeg& leg : *plan){ + legs += (legs.empty() ? "" : ", ") + to_string(leg.leg); + } + logger.log("through_the_gate plans: " + legs); + return plan->size() <= 2 ? UnitTestResult(true) : UnitTestResult(std::format("{} legs: {}", plan->size(), legs)); +} + +// What a single miss leaves out: a fade whole, a fade's hold, or a banner. +enum class SingleMiss{ + FADE, + HOLD, + BANNER, +}; + +// The run of the row the clean run's `index`th fade or banner (`rows`' +// counts) falls in, with that one missed as `kind` says; none if it passes. +std::optional run_single_miss(Logger& logger, const std::vector& rows, SingleMiss kind, size_t index){ + const bool fade = kind != SingleMiss::BANNER; + size_t k = 0; + while (k + 1 < rows.size() && (fade ? rows[k + 1].fades : rows[k + 1].banners) <= index){ + k++; + } + const size_t in_row = index - (fade ? rows[k].fades : rows[k].banners); + SimMisses misses{.fade = {}, .banner = {}}; + (kind == SingleMiss::FADE ? misses.fade : kind == SingleMiss::HOLD ? misses.hold : misses.banner) = in_row; + SimExecutor executor(logger, misses); + if (run_rows_on(executor, logger, {.from = rows[k].row, .to = rows[k].row}).completed){ + return std::nullopt; + } + return executor.result(); +} + +// Each fade and each banner the clean run looks for, missed alone: the +// row it falls in must still pass, but for a miss in one of `skip`'s steps. +// A door step once accepted only its fade, so a missed fade there failed a +// real arrival (#268's Monte Carlo, 19/20 on 01.05). +UnitTestResult every_single_miss(Logger& logger, const std::set& skip){ + SimExecutor clean(logger); + if (!run_rows_on(clean, logger, {.from = "00.00", .to = "01.11"}).completed){ + return "the run fails without misses: " + clean.result().error; + } + const std::vector& rows = clean.result().rows; + std::vector failed; + const auto miss = [&](bool fade, size_t index){ + const std::optional run = run_single_miss(logger, rows, fade ? SingleMiss::FADE : SingleMiss::BANNER, index); + if (run && !skip.contains(run->failed_step)){ + failed.push_back(std::format("{} {} missed: stopped in {}: {}", fade ? "fade" : "banner", index, + run->failed_step, run->error)); + } + }; + for (size_t i = 0; i < clean.misses().fades; i++){ + miss(true, i); + } + for (size_t i = 0; i < clean.misses().banners; i++){ + miss(false, i); + } + std::string out = std::format("{} of {} single misses fail their row:", failed.size(), clean.misses().fades + clean.misses().banners); + for (const std::string& line : failed){ + out += "\n " + line; + } + return failed.empty() ? UnitTestResult(true) : UnitTestResult(out); +} + +// Each fade the clean run looks for with only its hold unseen, a short +// fade between two frames (the door's watcher missed 13 of 35 fades on +// lab-B, 2026-11-08): the program's fade watch takes the scene after the +// fall, so every row passes, at every warp, ONE_SIGNAL_STEPS' too. +UnitTestResult every_single_hold_miss(Logger& logger){ + SimExecutor clean(logger); + if (!run_rows_on(clean, logger, {.from = "00.00", .to = "01.11"}).completed){ + return "the run fails without misses: " + clean.result().error; + } + std::vector failed; + for (size_t i = 0; i < clean.misses().fades; i++){ + const std::optional run = run_single_miss(logger, clean.result().rows, SingleMiss::HOLD, i); + if (run){ + failed.push_back(std::format("fade {}'s hold unseen: stopped in {}: {}", i, run->failed_step, run->error)); + } + } + std::string out = std::format("{} of {} fades with their hold unseen fail their row:", failed.size(), clean.misses().fades); + for (const std::string& line : failed){ + out += "\n " + line; + } + return failed.empty() ? UnitTestResult(true) : UnitTestResult(out); +} + +// Oreburgh's street at night (88, game clock 00:25; 104 by day, r74), the +// Gate's dim floor (46) and a cave mouth's dim fade (45 to 64): the tap +// steps judge their fades with fade_of(): uniform, so a textured floor +// is none. The old "brightness under 75" took the Gate's floor for a fade +// (lab-B 2026-11-08). +UnitTestResult night_and_dim_floors(Logger& logger){ + SimWorldKnobs knobs{ + .floor = {{"OreburghCity", 88}, {"Route203", 88}, {"OreburghGate", 46}}, + .fade_into = {{"OreburghGate", 64}, {"OreburghCity", 255}, {"Route203", 255}}, + }; + return passes(run_case(logger, "01.02", "01.05", {.fade = {}, .banner = {}}, knobs)); +} + +// 01.03: Roark's first line in the mine comes after the camera zooms in on +// us, some seconds after the A press (r98; the old event waited 8 s). +UnitTestResult roark_speaks_late(Logger& logger){ + std::string talk; + for (const StoryCheckpoint& row : story_checkpoints()){ + for (const StoryStep& step : row.steps){ + if (row.id == "01.03" && step.kind == StoryStepKind::TALK){ + talk = step.name; + } + } + } + return passes(run_case(logger, "01.03", "01.03", {.fade = {}, .banner = {}}, {.first_line = {{talk, 7000ms}}})); +} + +// `row` with everyone on its maps walking their wander boxes, seeds 1 to 8. +UnitTestResult wanderers_move(Logger& logger, const std::string& row){ + std::vector failed; + for (uint64_t seed = 1; seed <= 8; seed++){ + const std::string stopped = run_case(logger, row, row, {.fade = {}, .banner = {}}, {.wander_seed = seed}); + if (!stopped.empty()){ + failed.push_back(std::format("seed {}: {}", seed, stopped)); + } + } + std::string out = std::format("{} of 8 seeds fail:", failed.size()); + for (const std::string& line : failed){ + out += "\n " + line; + } + return failed.empty() ? UnitTestResult(true) : UnitTestResult(out); +} + +// Roark's badge speech after the battle: four lines, the fanfare's pause +// with no box, then the badge's and the TM's lines (lab-B 2026-10-31 09:45 +// and 2026-11-08 15:06: "no box for a moment" read as the end, and the +// Potion's menu opened under his next line). Then a scene: someone walks +// off with no box for 6 s before the last line, as Rowan does in r23 (the +// walk is a model, not measured after Roark). Played on the talk-over the +// battle's end runs (confirm_battle_overworld()). +UnitTestResult roark_badge_speech(Logger& logger){ + const SimScene scene{ + sim_line("Roark: the battle's last line"), + sim_line("Roark: you beat me"), + sim_line("Roark: the Coal Badge"), + sim_line("Received the Coal Badge"), + sim_pause("the badge's fanfare", 3000ms, false), + sim_line("Roark: the TM"), + sim_line("Roark: Stealth Rock"), + sim_pause("someone walks off", 6000ms, true), + sim_line("the last line"), + }; + const std::string early = play_scene(scene, {}); + logger.log("Roark's badge speech: " + (early.empty() ? std::string("over after the last line") : early)); + return passes(early); +} + +// 01.07: after the tag battle the screen fades back from the battle and +// the grunts run off before anyone speaks: a scene that opens with no box, +// 6 s of people moving (Rowan's cutscene shape), then Rowan's and Dawn's +// lines, and Bebe walks over with hers. The lengths are a model: r80 saved +// over her lines. +UnitTestResult grunts_run_off_before_rowan(Logger& logger){ + SimWorldKnobs knobs; + knobs.scenes["galactic_grunts"] = { + sim_fade("back from the battle", 1000ms), + sim_pause("the grunts run off", 6000ms, true), + sim_line("Rowan"), + sim_line("Rowan"), + sim_line("Dawn"), + sim_pause("Bebe walks over", 5000ms, true), + sim_line("Bebe"), + sim_line("Bebe: the Pokemon Center's PC"), + }; + return passes(run_case(logger, "01.07", "01.07", {.fade = {}, .banner = {}}, knobs)); +} + +// 00.03: Rowan's scene opens with no box: Rowan and Dawn walk back and +// stand a moment before his first line; after he leaves, Dawn's and +// Barry's lines, the fade home, and Mom walks over before she speaks +// (r23, r24, r31). The scene changes map, so only the quiet after the +// fade counts. +UnitTestResult rowans_scene_opens_with_no_box(Logger& logger){ + SimWorldKnobs knobs; + knobs.scenes["rowan_and_dawn"] = { + sim_pause("Rowan and Dawn walk back", 7000ms, true), + sim_pause("they stand a moment", 3000ms, false), + sim_line("Rowan"), + sim_line("Rowan"), + sim_pause("Rowan leaves", 6000ms, true), + sim_pause("Dawn and Barry stand", 3000ms, false), + sim_line("Dawn"), + sim_line("Barry"), + sim_fade("the fade home", 1500ms), + sim_pause("home, still", 4000ms, false), + sim_pause("Mom walks over", 5000ms, true), + sim_line("Mom: the Running Shoes"), + sim_line("Mom"), + }; + return passes(run_case(logger, "00.03", "00.03", {.fade = {}, .banner = {}}, knobs)); +} + +// 00.03: Mom's lines, a still moment, then the scene's closing fade +// (lab-B 2026-11-09 14:33). The scene once ended as the fade went down, +// and the next step's input landed in it: the talk-over must wait for the +// fade to come back up and for the quiet after it. +UnitTestResult moms_scene_ends_with_a_fade(Logger& logger){ + SimWorldKnobs knobs; + knobs.scenes["rowan_and_dawn"] = { + sim_line("Dawn"), + sim_line("Barry"), + sim_fade("the fade home", 1500ms), + sim_line("Mom: the Running Shoes"), + sim_line("Mom"), + sim_pause("Mom stands", 4000ms, false), + sim_fade("the scene's closing fade", 2000ms), + }; + return passes(run_case(logger, "00.03", "00.03", {.fade = {}, .banner = {}}, knobs)); +} + +// 00.02: the Starly battle's opening is still playing when the battle +// step starts, right after choose_starter (lab-B 2026-11-09 run 3, event +// 7): the battle step's, not interrupt_unsettled before it. +UnitTestResult starly_opening_after_the_starter(Logger& logger){ + SimWorldKnobs knobs; + knobs.battle_opening_before = [](const std::string& row, const std::string& step){ + return row == "00.02" && step == "starly"; + }; + return passes(run_case(logger, "00.02", "00.02", {.fade = {}, .banner = {}}, knobs)); +} + +// 00.04b: the run down Route 202's road into Sandgem stopped two columns +// west of the table's (29, 5), on (27, 5), and the counted walk on to +// the Center's door ended below its west wall: the heal ran north into +// the wall (lab-B 2026-11-09 20:09). The walk to the door must find its +// column on walls, wherever on the road's last row the run stopped. +UnitTestResult sandgem_entry_two_columns_west(Logger& logger){ + SimWorldKnobs knobs; + knobs.lands["into_sandgem"] = Pokemon::tile_pose("SandgemTown", {TilePos{27, 5}}, Direction::SOUTH); + return passes(run_case(logger, "00.04b", "00.04b", {.fade = {}, .banner = {}}, std::move(knobs))); +} + +// 00.03: Rowan's scene ends at home on (6, 8) beside Mom (lab-B +// 2026-11-09, 7 of 7 runs). The way out holds south onto the door's tile +// (6, 10); from a column west, (5, 8), the hold stops on (5, 10) with no +// fade, and a tap east onto the mat goes out. +UnitTestResult home_from_each_scene_end(Logger& logger){ + std::string failures; + for (const TilePos& tile : {TilePos{6, 8}, TilePos{5, 8}}){ + SimWorldKnobs knobs; + knobs.lands["rowan_and_dawn"] = Pokemon::tile_pose("PlayerHouse1F", {tile}, Direction::EAST); + const std::string stopped = run_case(logger, "00.03", "00.03", {.fade = {}, .banner = {}}, std::move(knobs)); + if (!stopped.empty()){ + failures += std::format("\nfrom ({}, {}): {}", tile.x, tile.y, stopped); + } + } + return passes(failures); +} + +// The table with row `id` cut to `step` alone, from `start`. +std::vector table_with_row(const std::string& id, const Pose& start, const StoryStep& step){ + std::vector rows = story_checkpoints(); + for (StoryCheckpoint& checkpoint : rows){ + if (checkpoint.id == id){ + checkpoint.start = Pokemon::TileDeclared{start.map, Pokemon::tiles_of(start), Pokemon::facing_of(start)}; + checkpoint.steps = {step}; + } + } + return rows; +} +// 00.03: Rowan's trigger is the column (5, 14..16) on Route 201 (decomp), +// 20 tiles east of the Lakefront's wall row 21 (Route 201's row 14). The +// step routes from where the lake's scene leaves us, or from a row or two +// lower (21..23), onto that row, then runs east until his scene stops the +// run on a tile of the column. +UnitTestResult rowans_scene_from_each_start(Logger& logger){ + const StoryStep& walk = table_step("00.03", "into_rowans_scene"); + const Pose trigger = Pokemon::tile_pose("Route201", {TilePos{5, 14}, TilePos{5, 15}, TilePos{5, 16}}, Direction::EAST); + std::string failures; + for (const TilePos& tile : {TilePos{17, 14}, TilePos{17, 15}, TilePos{20, 21}, TilePos{20, 22}, TilePos{20, 23}}){ + const Pose start = Pokemon::tile_pose("VerityLakefront", {tile}, Direction::SOUTH); + const std::vector rows = table_with_row("00.03", start, walk); + SimExecutor executor(logger, {.fade = {}, .banner = {}}, {}); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = "00.03", .to = "00.03"}, rows); + if (!report.completed){ + failures += std::format("\nfrom ({}, {}): stopped in {}: {}", tile.x, tile.y, executor.result().failed_step, executor.result().error); + }else if (!ends_on(executor.result(), trigger)){ + failures += std::format("\nfrom ({}, {}): the walk ended at {}, not on Rowan's trigger", tile.x, tile.y, end_of(executor.result())); + } + } + return passes(failures); +} +// 00.03: Dawn's scene starts on Sandgem's column 4 (rows 10..15, decomp), +// five tiles into the run east from Route 201's edge (Sandgem (-1, 12) is +// Route 201 (63, 5)). From the house's doorstep, the step routes to the +// edge and runs on until her scene stops it there (r35, r36: an exact +// tile and banner raced her scene). +UnitTestResult dawns_scene_mid_run(Logger& logger){ + const StoryStep& walk = table_step("00.03", "into_dawns_scene"); + const Pose start = Pokemon::tile_pose("TwinleafTown", {map_point("TwinleafTown", "house_doorstep")}, Direction::SOUTH); + const std::vector rows = table_with_row("00.03", start, walk); + SimExecutor executor(logger, {.fade = {}, .banner = {}}, {}); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = "00.03", .to = "00.03"}, rows); + if (!report.completed){ + return std::format("stopped in {}: {}", executor.result().failed_step, executor.result().error); + } + const Pose trigger = Pokemon::tile_pose("SandgemTown", {TilePos{4, 12}}, Direction::EAST); + if (!ends_on(executor.result(), trigger)){ + return std::format("the walk ended at {}, not on Dawn's trigger (4, 12).", end_of(executor.result())); + } + return true; +} + +// Route 201's grass, as the console met it: a wild battle on each of four +// passes of 10 tiles of row 5's grass (lab-B 2026-11-09 16:14). A battle +// each 8 grass tiles gives one on every such pass. +SimWorldKnobs route_201_grass(){ + SimWorldKnobs knobs; + knobs.grass.every = 8; + return knobs; +} +// 00.04's steps from the east end of Sandgem's path down over Route 201's +// ledge: "to_route_201" through "over_the_ledge", less `skip`. The run +// west leaves us on one of seven tiles, as on the console. +std::vector ledge_walk(const std::set& skip){ + std::vector steps; + bool on = false; + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const StoryStep& step : checkpoint.steps){ + if (checkpoint.id != "00.04"){ + continue; + } + on |= step.name == "to_route_201"; + if (on && !skip.contains(step.name)){ + steps.push_back(step); + } + if (step.name == "over_the_ledge"){ + return steps; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No over_the_ledge after to_route_201 in 00.04"); +} +// 00.04 from the east end of Sandgem's path to below Route 201's ledge, a +// wild battle each 8 grass tiles: "" if it gets there, else where and why +// it stopped. Without `skip`, the table's walk. +std::string ledge_walk_in_grass(Logger& logger, const std::set& skip){ + std::vector rows = story_checkpoints(); + for (StoryCheckpoint& checkpoint : rows){ + if (checkpoint.id == "00.04"){ + const GridPose target = story_arg(table_step("00.04", "onto_the_path").args, "target"); + checkpoint.start = Pokemon::TileDeclared{target.map, target.tiles, target.facing}; + checkpoint.steps = ledge_walk(skip); + } + } + return run_case(logger, "00.04", "00.04", {.fade = {}, .banner = {}}, route_201_grass(), rows); +} + +// The scenes a run's walks fought as trainers', or "none". +std::string fought(const SimRun& run){ + std::string out; + for (const std::string& scene : run.scenes_fought){ + out += (out.empty() ? "" : "; ") + scene; + } + return out.empty() ? "none" : out; +} +// 00.04: Mom's call after her heal fires on (6, 9), above the mat +// (lab-B 2026-11-09 17:29). The walk into it ends in her call, which her +// hat scene's step plays to the fade out with her; no walk fights it. +UnitTestResult moms_call_above_the_mat(Logger& logger){ + SimExecutor executor(logger, {.fade = {}, .banner = {}}, {}); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = "00.04", .to = "00.04"}); + if (!report.completed){ + return std::format("stopped in {}: {}", executor.result().failed_step, executor.result().error); + } + if (!executor.result().scenes_fought.empty()){ + return "a walk fought a scene: " + fought(executor.result()); + } + return true; +} +// 00.04's old walk round Mom to (6, 9) and step onto the mat. On the +// console the walk fought her call, the step went out of the door and her +// hat scene saw no fade. A route before a step onto a scene's trigger now +// hands a scene that starts on the way to the scene's step, and the step +// onto the trigger is not taken. +UnitTestResult old_walk_hands_moms_call_over(Logger& logger){ + std::vector rows = story_checkpoints(); + for (StoryCheckpoint& checkpoint : rows){ + if (checkpoint.id != "00.04"){ + continue; + } + std::vector steps; + for (StoryStep& step : checkpoint.steps){ + if (step.name != "into_moms_call"){ + steps.push_back(std::move(step)); + continue; + } + for (StoryStep& old : old_round_mom_to_the_mat()){ + steps.push_back(std::move(old)); + } + } + checkpoint.steps = std::move(steps); + } + SimExecutor executor(logger, {.fade = {}, .banner = {}}, {}); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, {.from = "00.04", .to = "00.04"}, rows); + const SimRun& run = executor.result(); + if (!report.completed){ + return std::format("stopped in {}: {}", run.failed_step, run.error); + } + if (!run.scenes_fought.empty()){ + return "a walk fought a scene: " + fought(run); + } + return true; +} + +struct FailureCaseInput{ + std::string name; + std::function body; +}; +// Whether a case is expected to fail is KNOWN_FAILING's, by name. +struct FailureCaseExpectation{ +}; +struct FailureCase{ + FailureCaseInput input; + FailureCaseExpectation expectation; +}; + +class Test_AutoStoryFailureCase : public UnitTest{ +public: + explicit Test_AutoStoryFailureCase(FailureCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Console failure on the sim: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + UnitTestResult result; + try{ + result = m_case.input.body(logger); + }catch (Exception& e){ + result = std::string(e.name()) + ": " + e.message(); + } + const auto known = KNOWN_FAILING.find(m_case.input.name); + if (known == KNOWN_FAILING.end()){ + return result; + } + if (result.result == UnitTestResult::PASSED){ + return "on KNOWN_FAILING (" + known->second + ") but passes now: take it off the list."; + } + logger.log("Known failing until " + known->second + ": " + result.message); + return true; + } + +private: + FailureCase m_case; +}; + +} // namespace + +const FailureCase AUTO_STORY_FAILURE_CASES[] = { + {.input = {"01.05 through_the_gate's last leg runs a tile on (lab-B 2026-11-08 15:31)", [](Logger& logger){ + return passes(run_case(logger, "01.05", "01.05", {.fade = {}, .banner = {}}, gate_slide(SimFade::DIM, false))); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, dim fade, banner gone", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::DIM, false); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, dim fade, banner up", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::DIM, true); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, black fade", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::BLACK, true); + }}, .expectation = {}}, + {.input = {"01.05 old walk slides onto the Gate's west mouth, white fade", [](Logger& logger){ + return gate_old_walk_slides(logger, SimFade::WHITE, true); + }}, .expectation = {}}, + {.input = {"01.05 through_the_gate is one run west", gate_plan_one_run}, .expectation = {}}, + {.input = {"any one missed fade or banner from 00.00 to 01.11: every row still passes", [](Logger& logger){ + return every_single_miss(logger, {}); + }}, .expectation = {}}, + {.input = {"any one missed fade or banner at a warp that shows both: its row still passes", [](Logger& logger){ + return every_single_miss(logger, ONE_SIGNAL_STEPS); + }}, .expectation = {}}, + {.input = {"any one fade with its hold unseen from 00.00 to 01.11: every row still passes", every_single_hold_miss}, .expectation = {}}, + {.input = {"01.02 to 01.05 at night, the Gate's dim floor", night_and_dim_floors}, .expectation = {}}, + {.input = {"01.03 Roark's first line 7 s after the A press", roark_speaks_late}, .expectation = {}}, + {.input = {"01.03 with Oreburgh's people wandering (the pokefan on 45, 37..39)", [](Logger& logger){ + return wanderers_move(logger, "01.03"); + }}, .expectation = {}}, + {.input = {"01.08 with Route 204's youngster wandering (12..14, 2)", [](Logger& logger){ + return wanderers_move(logger, "01.08"); + }}, .expectation = {}}, + {.input = {"01.04 Roark's badge speech: the fanfare's pause, then a scene", roark_badge_speech}, .expectation = {}}, + {.input = {"01.07 after the tag battle the grunts run off before anyone speaks", grunts_run_off_before_rowan}, .expectation = {}}, + {.input = {"00.03 Rowan's scene opens with no box and fades home", rowans_scene_opens_with_no_box}, .expectation = {}}, + {.input = {"00.03 Mom's scene ends with a closing fade: over once it is back up (lab-B 2026-11-09)", moms_scene_ends_with_a_fade}, .expectation = {}}, + {.input = {"00.02 the Starly battle's opening still plays after the starter (lab-B 2026-11-09)", starly_opening_after_the_starter}, .expectation = {}}, + {.input = {"00.03 out of the house from (6, 8), where Rowan's scene ends, and from a column west", home_from_each_scene_end}, .expectation = {}}, + {.input = {"00.03 the walk into Rowan's scene routes onto his row and stops on his trigger mid-run", rowans_scene_from_each_start}, .expectation = {}}, + {.input = {"00.03 the walk into Sandgem stops on Dawn's trigger mid-run", dawns_scene_mid_run}, .expectation = {}}, + {.input = {"00.04 Mom's call fires above the mat, on (6, 9): the walk ends in it, her hat scene plays it (lab-B 2026-11-09 17:29)", moms_call_above_the_mat}, .expectation = {}}, + {.input = {"00.04 the old walk round Mom to (6, 9) runs into her call: it hands it to her hat scene, not fights it (lab-B 2026-11-09 17:29)", old_walk_hands_moms_call_over}, .expectation = {}}, + {.input = {"00.04b the run into Sandgem stops two columns west: the walk still ends below the Center's door (lab-B 2026-11-09 20:09)", sandgem_entry_two_columns_west}, .expectation = {}}, + {.input = {"00.04 to the ledge column with a wild battle on each pass through Route 201's grass (lab-B 2026-11-09 16:14)", [](Logger& logger){ + return passes(ledge_walk_in_grass(logger, {})); + }}, .expectation = {}}, + // It failed there with "too many plans" until replans crossed the + // grass on legs to a wall (replan_costs(), 2026-11-09). + {.input = {"00.04 the old walk to the ledge column, west to row 5's wall through the grass, now passes", [](Logger& logger){ + return passes(ledge_walk_in_grass(logger, {"to_the_signs_row"})); + }}, .expectation = {}}, +}; + +void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_FAILURE_CASES){ + database.add(item); + } +} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h new file mode 100644 index 0000000000..b196c4baf9 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_SimFailureCases_Tests.h @@ -0,0 +1,27 @@ +/* BDSP AutoStory - Console failure cases on the story simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_SimFailureCases_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_SimFailureCases_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// Each failure console B showed in events and perception, run on the story +// simulation; the ones the program still fails are known failing. +void add_tests_AutoStory_SimFailureCases(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.cpp new file mode 100644 index 0000000000..9b795d8b73 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.cpp @@ -0,0 +1,248 @@ +/* BDSP AutoStory - Story actions Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_StorySim.h" +#include "PokemonBDSP_AutoStory_StoryActions_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +using namespace detail; + + +namespace{ + +using Pokemon::RunState; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; + + +// Every step the story runs: the table's, and each row's save at its start. +std::vector> story_steps(){ + std::vector> out; + for (const StoryCheckpoint& row : story_checkpoints()){ + for (const StoryStep& step : row.steps){ + out.emplace_back(row.id, step); + } + StoryStep save; + save.kind = StoryStepKind::SAVE; + save.name = "save"; + save.action = row.saves_in; + out.emplace_back(row.id, std::move(save)); + } + return out; +} + +// What ran a step before the table: the executors' own dispatch. An event +// named by the whole variant, whatever the kind; else the kind's method, +// which StoryWalkSteps does for the walking kinds, and the console (or +// the simulation's stand-in) for the others; else the base class's. +std::string old_dispatch(const StoryStep& step){ + const std::string kind = Pokemon::story_step_kind_name(step.kind); + if (story_events().contains(step.action)){ + return "event " + step.action; + } + switch (step.kind){ + case StoryStepKind::ROUTE: + case StoryStepKind::LEGS: + case StoryStepKind::STEP: + case StoryStepKind::TALK: + case StoryStepKind::MASH: + return "walk " + kind; + case StoryStepKind::NEW_GAME: + case StoryStepKind::OPTIONS: + case StoryStepKind::ANSWER: + case StoryStepKind::BATTLE: + case StoryStepKind::TRAIN: + case StoryStepKind::HEAL: + case StoryStepKind::SAVE: + return "console " + kind; + default: + return "executor " + kind; + } +} + +// The table's binding that names what it would run, as a failure. +StoryBoundActions naming_actions(){ + const auto named = [](StoryStepKind kind){ + return [kind](const StoryStep&, RunState&){ + return Pokemon::outcome_failed("console", Pokemon::story_step_kind_name(kind)); + }; + }; + return StoryBoundActions{ + .new_game = named(StoryStepKind::NEW_GAME), + .options = named(StoryStepKind::OPTIONS), + .answer = named(StoryStepKind::ANSWER), + .battle = named(StoryStepKind::BATTLE), + .train = named(StoryStepKind::TRAIN), + .heal = named(StoryStepKind::HEAL), + .save = named(StoryStepKind::SAVE), + .event = [](const std::string& name) -> Pokemon::StoryActionFunction{ + return [name](const StoryStep&, RunState&){ + return Pokemon::outcome_failed("event", name); + }; + }, + }; +} + +// What `table` runs for `step`, in old_dispatch()'s words. A walking row +// is not run: it would walk. +std::string table_dispatch(const Pokemon::StoryActionTable& table, const StoryStep& step){ + const Pokemon::StoryAction* action = table.find(step); + if (action == nullptr){ + return std::string("executor ") + Pokemon::story_step_kind_name(step.kind); + } + if (!action->needs_console){ + return std::string("walk ") + Pokemon::story_step_kind_name(step.kind); + } + RunState state; + const Pokemon::Outcome outcome = action->act(step, state); + return outcome.failure + " " + outcome.detail; +} + + +UnitTestResult test_every_step_has_an_action(Logger& logger){ + SimExecutor sim(logger); + size_t steps = 0; + for (const StoryCheckpoint& row : story_checkpoints()){ + const std::vector unbound = Pokemon::lint_story_checkpoint(row, sim.actions()); + if (!unbound.empty()){ + return unbound.front(); + } + steps += row.steps.size(); + } + logger.log(std::format("{} rows, {} steps, each with an action.", story_checkpoints().size(), steps)); + return true; +} + +UnitTestResult test_table_runs_what_the_old_dispatch_ran(Logger& logger){ + GridSim sim({}, {0, 0}, Pokemon::Direction::NORTH, false); + std::vector notes; + SimMisses misses; + const SimWorldKnobs knobs; + const std::string step_name; + SimStoryStepIO io(sim, notes, misses, knobs, step_name, []{ return false; }, [](const Pokemon::Pose&){}); + StoryWalkSteps walks(io); + const Pokemon::StoryActionTable table = story_action_table(walks, naming_actions()); + + std::set> seen; + for (const auto& [row, step] : story_steps()){ + if (!seen.emplace(step.kind, step.action).second){ + continue; + } + const std::string expected = old_dispatch(step); + const std::string actual = table_dispatch(table, step); + if (actual != expected){ + return std::format("{} {} ({} \"{}\"): the table runs \"{}\", the old dispatch ran \"{}\".", + row, step.name, Pokemon::story_step_kind_name(step.kind), step.action, actual, expected); + } + } + logger.log(std::format("{} (kind, action) pairs run as before.", seen.size())); + return true; +} + +UnitTestResult test_stubbed_steps_need_the_console(Logger& logger){ + SimExecutor sim(logger); + run_rows_on(sim, logger, {.from = "00.00", .to = "01.11"}); + logger.log("Steps the simulation does not play, by row:\n" + stub_report(sim.result())); + for (const auto& [row, step] : story_steps()){ + const Pokemon::StoryAction* action = sim.actions().find(step); + if (action != nullptr && action->needs_console){ + continue; + } + for (const SimRun::RowStart& start : sim.result().rows){ + if (start.row != row){ + continue; + } + for (const std::string& stubbed : start.stubbed){ + if (stubbed == step.name){ + return std::format("{} {}: stubbed, but the simulation plays its kind.", row, step.name); + } + } + } + } + if (!sim.result().error.empty()){ + return "The run failed: " + sim.result().error; + } + return true; +} + + + +struct AutoStoryStoryActionsInput{ + std::string name; + std::function body; +}; + +struct AutoStoryStoryActionsExpectation{ +}; + +struct AutoStoryStoryActionsCase{ + AutoStoryStoryActionsInput input; + AutoStoryStoryActionsExpectation expectation; +}; + +class Test_AutoStoryStoryActions : public UnitTest{ +public: + explicit Test_AutoStoryStoryActions(AutoStoryStoryActionsCase test_case) + : UnitTest("PokemonBDSP::AutoStory - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + AutoStoryStoryActionsCase m_case; +}; + +} // namespace + + +const AutoStoryStoryActionsCase AUTO_STORY_STORY_ACTIONS_CASES[] = { + { + .input = {"Story actions: every step of every row has an action", test_every_step_has_an_action}, + .expectation = {}, + }, + { + .input = {"Story actions: each (kind, action) runs what the executors' own dispatch ran", test_table_runs_what_the_old_dispatch_ran}, + .expectation = {}, + }, + { + .input = {"Story actions: the steps the sim stubs from 00.00 to 01.11 all need the console", test_stubbed_steps_need_the_console}, + .expectation = {}, + }, +}; + +void add_tests_AutoStory_StoryActions(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_STORY_ACTIONS_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.h new file mode 100644 index 0000000000..ee24d30c9a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StoryActions_Tests.h @@ -0,0 +1,28 @@ +/* BDSP AutoStory - Story actions Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryActions_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StoryActions_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// The story's action table (story_action_table()): every step of the +// story has an action, each runs what the executors' own dispatch ran +// before the table, and the steps the simulation stubs need the console. +void add_tests_AutoStory_StoryActions(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp new file mode 100644 index 0000000000..c3b4a66d99 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.cpp @@ -0,0 +1,972 @@ +/* BDSP AutoStory - Story simulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkResult.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkScreen.h" +#include "PokemonBDSP_AutoStory_StorySim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +using namespace detail; + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::GridPose; +using Pokemon::story_arg; +using Pokemon::Outcome; +using Pokemon::Pose; +using Pokemon::RunState; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + + +namespace detail{ +ImageStats sim_screen(double brightness, double stddev){ + return ImageStats(FloatPixel(brightness, brightness, brightness), FloatPixel(stddev, stddev, stddev), 1); +} + +std::vector sim_fade_frames(double floor, double fade, bool hold_seen){ + constexpr Milliseconds FRAME = 33ms; + // The fall and the rise: halfway, in brightness and in texture. + const ImageStats between = sim_screen((floor + fade) / 2, (SIM_FLOOR_STDDEV + SIM_FADE_STDDEV) / 2); + std::vector looks{sim_screen(floor, SIM_FLOOR_STDDEV), between}; + if (hold_seen){ + for (size_t i = 0; i < 3; i++){ + looks.push_back(sim_screen(fade, SIM_FADE_STDDEV)); + } + looks.push_back(between); + } + looks.push_back(sim_screen(floor, SIM_FLOOR_STDDEV)); + std::vector frames; + for (size_t i = 0; i < looks.size(); i++){ + frames.push_back({.time = WallClock() + FRAME * (int64_t)i, .middle = looks[i]}); + } + return frames; +} + +WarpFade sim_watch_fade(const WarpFadeRule& rule, double floor, double fade, bool hold_seen){ + WarpFadeWatch watch(rule, [](const Pokemon::TransitionSample&, const Pokemon::TransitionSample&){ + return Pokemon::SceneChange::DIFFERENT; + }); + for (const Pokemon::TransitionSample& frame : sim_fade_frames(floor, fade, hold_seen)){ + const WarpFade seen = watch.push(frame); + if (seen != WarpFade::NONE){ + return seen; + } + } + return WarpFade::NONE; +} + +SimBeat sim_line(std::string what){ + return {.what = std::move(what), .line = true}; +} +SimBeat sim_pause(std::string what, Milliseconds length, bool moving){ + return {.what = std::move(what), .length = length, .moving = moving}; +} +SimBeat sim_fade(std::string what, Milliseconds length, WarpFade fade){ + return {.what = std::move(what), .length = length, .overworld = true, .moving = false, .fade = fade}; +} + +std::string play_scene(const SimScene& scene, const TalkOverRule& rule){ + const Milliseconds press = TALK_OVER_HOLD + TALK_OVER_RELEASE; + TalkOver judge(rule); + const WallClock start = WallClock(); + WallClock now = start; + WallClock beat_start = start; + size_t beat = 0; + const auto at = [&]{ + return std::format("{} ms in, at beat {} of {}", std::chrono::duration_cast(now - start).count(), beat + 1, scene.size()); + }; + while (now - start < TALK_OVER_LIMIT){ + while (beat < scene.size() && !scene[beat].line && now - beat_start >= scene[beat].length){ + beat_start += scene[beat].length; + beat++; + } + Pokemon::ScreenEvents look{Pokemon::ScreenEvent::PLAYER_CAN_MOVE, Pokemon::ScreenEvent::SCREEN_STILL}; + if (beat < scene.size()){ + const SimBeat& shown = scene[beat]; + look = {}; + look.set(Pokemon::ScreenEvent::DIALOG_BOX, shown.line); + look.set(Pokemon::ScreenEvent::PLAYER_CAN_MOVE, shown.overworld); + look.set(Pokemon::ScreenEvent::SCREEN_STILL, !shown.moving); + look.merge(Pokemon::fade_events(shown.fade)); + } + switch (judge.look(look, now)){ + case SceneMove::DONE: + return beat < scene.size() ? std::format("judged over {} ({})", at(), scene[beat].what) : ""; + case SceneMove::BATTLE: + return "read a battle " + at(); + case SceneMove::NEXT: + case SceneMove::B: + // Either press closes a line; nothing else answers one. + if (beat < scene.size() && scene[beat].line){ + beat++; + beat_start = now + press; + } + break; + } + now += press; + } + return "never judged over: " + at() + ", " + judge.describe(); +} +} // namespace detail + +// Plays the step's scene knob through TalkOver if it has one. Without, a +// scene may take us to another map (Mom walks us out, 00.04): with a +// dialogue open the stub scene plays it. Otherwise only a door fades. +void SimStoryStepIO::settle(Button, const std::string& label, bool fade, const std::string&){ + m_misses.fading_in = false; + const auto scene = m_knobs.scenes.find(m_step); + if (scene != m_knobs.scenes.end()){ + m_misses.fade_unseen = false; + m_sim.end_dialogue(); + const std::string early = play_scene(scene->second, {.warp = fade}); + if (!early.empty()){ + m_route.note(label + ": talk-over " + early + ".", RouteNote::FAILURE); + } + return; + } + const bool scene_fades = m_sim.player().dialog && m_far_side(); + if (fade && ((!m_sim.player().warped && !scene_fades) || m_misses.fade_unseen)){ + m_route.note(label + ": no fade, so we are not where the step goes (map mismatch).", RouteNote::FAILURE); + } + m_misses.fade_unseen = false; + m_sim.end_dialogue(); +} + +SimStoryStepIO::FadeShown SimStoryStepIO::next_fade(){ + const size_t fade = m_misses.fades++; + const FadeShown shown = m_misses.fade == fade ? FadeShown::UNSEEN : m_misses.hold == fade ? FadeShown::HOLD_UNSEEN : FadeShown::SEEN; + m_misses.missed |= shown != FadeShown::SEEN; + return shown; +} + +WarpFade SimStoryStepIO::watched_fade(const WarpFadeRule& rule, double fade){ + const FadeShown shown = next_fade(); + return shown == FadeShown::UNSEEN ? WarpFade::NONE : sim_watch_fade(rule, floor_here(), fade, shown == FadeShown::SEEN); +} + +// A door's fade through the program's door watch: a hold missed shows at +// the scene after it. A fade missed whole, the run goes on holding and +// sees the far map's `banner` show after it, if it has one. +WarpSeen SimStoryStepIO::door_fade(const std::string& banner){ + const WarpFade fade = watched_fade(DOOR_FADE_RULE, SIM_DOOR_FADE); + if (fade != WarpFade::NONE){ + return {.fade = fade}; + } + m_misses.fade_unseen = true; + return {.banner = !banner.empty() && !banner_missed() ? banner : ""}; +} + +// A hold until something stops us. A door stops it at the fade, which +// fails the step; a fade missed lets the hold go on past the mouth (r81's +// timed walk south out of the Ravaged Path, onto Route 204's cliff). The +// walk's watchers take uniform frames only, so a fade whose hold they +// did not see is missed too. +void SimStoryStepIO::walk_until_stopped(Direction direction, size_t tiles, const std::string& label){ + m_sim.tap(direction, ROUTE_TURN_TAP, false); + Milliseconds limit = ROUTE_START_DELAY + 800ms + route_ms_per_tile(direction) * (int64_t)(2 * tiles); + SimMove move = m_sim.hold(direction, limit, SimPace::WALK); + if (move.stop == SimStop::WARP && next_fade() != FadeShown::SEEN && m_far_side()){ + limit -= std::min(limit, move.time); + move = m_sim.hold(direction, limit, SimPace::WALK); + } + if (move.stop == SimStop::DIALOG || move.stop == SimStop::WARP){ + m_route.note(label + ": " + std::string(sim_stop_name(move.stop)) + " instead of a stop.", RouteNote::FAILURE); + } +} + +// The D-pad, a tile at a time, until `map`'s banner reads; through a door +// the walk goes on beyond it (the fade eats no tiles of a hold). +bool SimStoryStepIO::run_until_map(Direction direction, Milliseconds limit, const std::string& map, const std::string&){ + const bool miss = banner_missed(); + size_t on = 0; + for (Milliseconds ran = 0ms; ran < limit; ran += ROUTE_RUN_MS_PER_TILE_ACROSS){ + SimMove move = m_sim.tap(direction, ROUTE_MS_PER_TILE_ACROSS, false); + const bool crossed = move.stop == SimStop::WARP && m_far_side(); + const bool stopped = !crossed && (move.distance == 0 || move.stop != SimStop::DONE); + on = on_map(map) ? on + 1 : 0; + if (on > 0 && (on > SIM_BANNER_TILES || stopped) && !miss){ + return true; + } + if (stopped){ + return false; + } + } + return false; +} + +double SimStoryStepIO::floor_here() const{ + for (const auto& [map, brightness] : m_knobs.floor){ + if (on_map(map)){ + return brightness; + } + } + return SIM_FLOOR; +} + +// D-pad taps, each looked at, until the fade or the banner (the console's +// ConsoleStoryStepIO::tap_to_banner()): none if the banner shows before +// the first. Each look stands still, so a banner on the far side reads at +// once. A fade the program's tap watch (TAP_FADE_RULE) sees ends the taps, +// its hold seen or not; with the fade missed whole the look still sees the +// banner. +std::optional SimStoryStepIO::tap_to_banner(Direction direction, const std::string& map, size_t max_taps){ + if (m_misses.through == m_misses.tap_steps++){ + m_misses.missed = true; + if (m_far_side() && m_misses.through_banner){ + return 0; + } + } + if (std::exchange(m_misses.banner_up, "") == map){ + return 0; + } + bool crossed = false; + for (size_t tap = 1; tap <= max_taps; tap++){ + const SimMove move = m_sim.tap(direction, 160ms, false); + if (move.stop == SimStop::DIALOG){ + return std::nullopt; + } + WarpFade fade = WarpFade::NONE; + if (move.stop == SimStop::WARP){ + const auto into = m_knobs.fade_into.find(map); + fade = watched_fade(TAP_FADE_RULE, into == m_knobs.fade_into.end() ? SIM_DOOR_FADE : into->second); + crossed = m_far_side(); + } + const bool banner = crossed && on_map(map) && !banner_missed(); + if (banner || fade != WarpFade::NONE){ + return tap; + } + } + return std::nullopt; +} + +WalkResult SimKnobRouteIO::walk_taps(Direction direction, size_t tiles, const std::string& label){ + const WalkResult result = GridSimRouteIO::walk_taps(direction, tiles, label); + if (result.stop != WalkStop::LIMIT || m_slid_steps.contains(m_step)){ + return result; + } + for (const SimSlide& item : m_knobs.slides){ + if (item.step == m_step && item.direction == direction){ + m_slid_steps.insert(m_step); + return slide_on(item, result); + } + } + return result; +} + +// The taps past the leg's end. Onto a warp the walk sees the fade as the +// program's fade_of() judges it, the walk's watchers' test: a fade ends +// it (TRANSITION), a white one too, as no battle follows it. The walk ends +// at the fade, before the banner shows (about 1.5 s after it), so it +// reads none. +WalkResult SimKnobRouteIO::slide_on(const SimSlide& slide, WalkResult result){ + m_misses.slid = true; + for (size_t tap = 0; tap < slide.tiles; tap++){ + const SimMove move = m_grid.tap(slide.direction, ROUTE_MS_PER_TILE_ACROSS, false); + if (move.stop != SimStop::WARP){ + note(std::format("[Sim] slid a tile on to {}.", to_string(m_grid.player().pos)), RouteNote::LOG); + continue; + } + note("[Sim] slid onto a warp to " + Pokemon::to_string(slide.far) + ".", RouteNote::LOG); + m_cross(slide.far); + m_misses.banner_up = slide.banner_up ? slide.far.map : ""; + const double brightness = slide.fade == SimFade::BLACK ? SIM_DOOR_FADE : slide.fade == SimFade::DIM ? SIM_DIM_FADE : SIM_WHITE_FADE; + result.warp.fade = fade_of(sim_screen(brightness, SIM_FADE_STDDEV)); + if (result.warp.fade != WarpFade::NONE){ + result.stop = WalkStop::TRANSITION; + } + return result; + } + return result; +} + +bool SimKnobRouteIO::dialog_within(Milliseconds wait, Color color){ + const auto late = m_knobs.first_line.find(m_step); + if (late != m_knobs.first_line.end() && late->second > wait){ + note(std::format("[Sim] {}: the first line comes after {} ms, past the {} ms wait.", m_step, late->second.count(), wait.count()), RouteNote::LOG); + return false; + } + return GridSimRouteIO::dialog_within(wait, color); +} + +// The story variables whose coord events the table walks onto, from the +// row (and step) the table's reasons give, with the maps' coord events +// (Diamond's zone events; Platinum's for the houses): Barry's doorstep and +// Mom's warning in 00.01, Barry's Route 201 warning, then its pull-back +// row 19 once he has warned us (r14, r16); the lake's entrance in 00.02; +// Rowan's stop and Dawn at Sandgem's edge in 00.03; Dawn's catching +// tutorial on Route 202 from 00.04's start, Mom's call once she has healed +// us; the Poketch president on Jubilife's row 40 in 00.05b; Barry on Route +// 203 in 01.01; the Gate's Hiker and Oreburgh's welcome in 01.02; Barry's +// bump in Oreburgh after Roark in 01.05; and Rowan in Jubilife in 01.07. +// Left out: the Twinleaf guitarist (spent upstairs), Platinum's rival +// steps around our bedroom's start, Dawn at Jubilife's steps (BDSP starts +// her below them: an event), and Floaroma's (10..12, 29) (Diamond only). +namespace detail{ +std::vector story_vars(){ + return { + {.var = "VAR_TWINLEAF_TOWN_RIVAL_TRIGGER_STATE", .value = 0, .row = "00.01", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 0, .row = "00.01", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 1, .row = "00.01", .after = "barry_warns_us"}, + {.var = "VAR_VERITY_LAKEFRONT_STATE", .value = 0, .row = "00.02", .after = ""}, + {.var = "VAR_FOLLOWER_RIVAL_STATE", .value = 2, .row = "00.03", .after = ""}, + {.var = "VAR_SANDGEM_TOWN_STATE", .value = 0, .row = "00.03", .after = ""}, + {.var = "VAR_ROUTE_202_STATE", .value = 0, .row = "00.04", .after = ""}, + {.var = "CONSOLE_MOMS_CALL", .value = 0, .row = "00.04", .after = "mom_heals_us"}, + {.var = "VAR_POKETCH_CAMPAIGN_STATE", .value = 1, .row = "00.05b", .after = ""}, + {.var = "VAR_ROUTE_203_RIVAL_STATE", .value = 0, .row = "01.01", .after = ""}, + {.var = "VAR_OREBURGH_GATE_1F_HIKER_STATE", .value = 1, .row = "01.02", .after = ""}, + {.var = "VAR_OREBURGH_CITY_STATE", .value = 0, .row = "01.02", .after = ""}, + {.var = "VAR_OREBURGH_CITY_STATE", .value = 2, .row = "01.05", .after = ""}, + {.var = "VAR_JUBILIFE_CITY_STATE", .value = 3, .row = "01.07", .after = ""}, + }; +} + +namespace{ + +// The maps' coord events (story_coord_events()) whose variable holds. +std::optional var_state(const CoordEvent& event){ + for (const VarState& state : story_vars()){ + if (state.var == event.var && state.value == event.value){ + return state; + } + } + return std::nullopt; +} + +// A coord event the console showed on other tiles than its map's. +struct ConsoleTrigger{ + std::string map; + std::string name; + std::vector tiles; +}; +std::vector console_triggers(){ + return { + // Mom's call after her heal fires on (6, 9), above the mat: a walk + // west along row 9 stopped in it there with all 4 taps moved + // (lab-B 2026-11-09 17:29), and the step south from (6, 9) after + // it went out of the door, where the same step on 2026-11-04 12:20, + // pressed inside her scene, moved nobody. The map has the mat (6, 10) + // (r45, r46: her line came after that step was pressed). + // Verify runs 1-3 (lab-B 2026-11-09 18:19, 18:30, 18:41): from (7, 9) + // west, her call stopped us after at most 1 tile, on (6, 9) each time. + {.map = "PlayerHouse1F", .name = "moms_call", .tiles = {{6, 9}}}, + }; +} + +RowTrigger row_trigger(const std::string& map, const CoordEvent& event, const VarState& state){ + RowTrigger out{ + .row = state.row, .after = state.after, .map = map, + .trigger = {.name = event.name, .tiles = event.tiles}, .var = event.var, + }; + for (const ConsoleTrigger& seen : console_triggers()){ + if (seen.map == map && seen.name == event.name){ + out.trigger.tiles = seen.tiles; + } + } + return out; +} + +} // namespace + +std::vector story_triggers(){ + std::vector triggers; + for (const auto& [map, json] : bdsp_map_json()){ + for (const CoordEvent& event : story_coord_events(map)){ + const std::optional state = var_state(event); + if (state){ + triggers.push_back(row_trigger(map, event, *state)); + } + } + } + return triggers; +} +} // namespace detail + +namespace{ + +// Someone the maps do not have, on `tile` of `map`, talked to or walked round: +// from row `row` on, until row `until_row`'s step `until` has run if it is set. +struct SimPerson{ + std::string name; + std::string map; + TilePos tile; + std::string row; + std::string until_row = {}; + std::string until = {}; +}; +std::vector sim_people(){ + return { + // Mom stands a row above the decomp's (7, 8) from 00.04 on (r43). + {.name = "mom", .map = "PlayerHouse1F", .tile = {7, 7}, .row = "00.04"}, + // Barry in the Gym's door, from the welcome (lab-B 2026-11-08) to his lines (r101, r104). + {.name = "barry", .map = "OreburghCity", .tile = {26, 21}, .row = "01.02b", .until_row = "01.02b", .until = "barrys_lines"}, + }; +} + +// A house's stairs, entered by a step `side` from the map's "stairs" +// point into what the map draws as a wall (the table's 00.01: r8 and r9 +// for ours, r11 for Barry's). +struct SimStairs{ + std::string map; + Direction side; +}; +std::vector sim_stairs(){ + return { + {.map = "PlayerHouse2F", .side = Direction::EAST}, + {.map = "RivalHouse1F", .side = Direction::EAST}, + {.map = "RivalHouse2F", .side = Direction::WEST}, + }; +} + +} // namespace + +// The world the player walks on for `map`: the planner's, with what the +// console showed that the maps lack. Nothing for a room with no map. +const StoryWorld* SimExecutor::sim_world(const std::string& map) const{ + const StoryWorld* world = story_plan_world(map, map); + std::vector here; + std::string who; + for (const SimPerson& person : sim_people()){ + const bool now = m_row >= person.row && (person.until.empty() || m_row < person.until_row || + (m_row == person.until_row && !m_ran.contains(person.until))); + if (world != nullptr && now && story_plan_world(person.map, person.map) == world){ + here.push_back(person); + who += person.name + ";"; + } + } + if (here.empty()){ + return world; + } + std::unique_ptr& peopled = m_peopled[{world, who}]; + if (!peopled){ + peopled = std::make_unique(*world); + for (const SimPerson& person : here){ + peopled->block(story_to_world(*world, person.map, person.tile)); + } + } + return peopled.get(); +} + +SimWorld SimExecutor::setup(const StoryWorld* world) const{ + // B runs once the shoes' scene has given them: the scene ends at home. + SimWorld out{.world = world, .trainers = row_trainers(*world, m_row), .can_run = m_walks.can_run()}; + for (const SimStairs& stairs : sim_stairs()){ + if (sim_world(stairs.map) == world){ + out.doors.push_back(story_to_world(*world, stairs.map, map_point(stairs.map, "stairs").next(stairs.side))); + } + } + for (const RowTrigger& armed : m_armed){ + if (sim_world(armed.map) != world){ + continue; + } + SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; + for (const TilePos& pos : armed.trigger.tiles){ + trigger.tiles.push_back(story_to_world(*world, armed.map, pos)); + } + out.triggers.push_back(std::move(trigger)); + } + out.wanderers = wanderers(*world); + return out; +} + +namespace{ +bool on_world(const StoryWorld& world, const std::string& map){ + try{ + story_to_world(world, map, {0, 0}); + return true; + }catch (const InternalProgramError&){ + return false; + } +} +} // namespace + +// Everyone with a wander box on `world`'s maps, walking it from their tile +// (SimWorldKnobs::wander_seed), each with their own seed and start time. +std::vector SimExecutor::wanderers(const StoryWorld& world) const{ + std::vector out; + if (!m_knobs.wander_seed){ + return out; + } + for (const auto& [map, json] : bdsp_map_json()){ + if (!on_world(world, map)){ + continue; + } + for (const auto& object : story_map(map).objects){ + if (!object.wander){ + continue; + } + const uint64_t seed = *m_knobs.wander_seed * 1000003 + out.size() * 7919 + (uint64_t)(object.x * 31 + object.y); + const TilePos low = story_to_world(world, map, {object.wander->x0, object.wander->y0}); + const TilePos high = story_to_world(world, map, {object.wander->x1, object.wander->y1}); + out.push_back({ + .name = object.name, + .box = {.x0 = low.x, .y0 = low.y, .x1 = high.x, .y1 = high.y}, + .pos = story_to_world(world, map, {object.x, object.y}), + .seed = seed, + .step_interval = Milliseconds(2000), + .elapsed = Milliseconds(0), + .time_offset = Milliseconds((int64_t)(seed % 2000)), + }); + } + } + return out; +} + +// Arms the triggers of this row that start after `after`. A variable holds +// one value: the triggers armed for its value before are disarmed (Route +// 201's row 19 pulls back only after Barry's warning, not in 00.03, where +// the variable has moved on). +void SimExecutor::arm(const std::string& after){ + std::vector now; + for (const RowTrigger& trigger : story_triggers()){ + if (trigger.row == m_row && trigger.after == after){ + now.push_back(trigger); + } + } + for (const RowTrigger& trigger : now){ + std::erase_if(m_armed, [&](const RowTrigger& old){ + return old.var == trigger.var; + }); + } + m_armed.insert(m_armed.end(), now.begin(), now.end()); + const size_t armed = now.size(); + const SimPlayer& player = m_sim.player(); + if (armed > 0 && m_placed && on_grid(player.pos) && !player.dialog){ + m_sim.place(setup(&m_sim.world()), nearest_tile(player.pos), player.facing); + } +} + +// Puts the player on `pose`, on the world `on` if given, unless they stand +// on one of its tiles already. Returns whether the pose is on a map the +// simulation has. +bool SimExecutor::sync(const Pose& pose, const StoryWorld* on){ + const std::vector tiles = Pokemon::tiles_of(pose); + const StoryWorld* world = on != nullptr ? on : pose.map.empty() ? nullptr : sim_world(pose.map); + if (world == nullptr || tiles.empty()){ + return false; + } + // The program thinks we are on `pose`; we walk on from where the slide left us. + if ((m_astray || m_misplaced) && m_placed){ + return true; + } + const SimPlayer& player = m_sim.player(); + const std::optional local = !m_placed || &m_sim.world() != world + ? std::nullopt : story_to_local(*world, pose.map, nearest_tile(player.pos)); + if (local && on_grid(player.pos) && std::find(tiles.begin(), tiles.end(), *local) != tiles.end()){ + return true; + } + m_sim.place(setup(world), story_to_world(*world, pose.map, tiles.front()), Pokemon::facing_of(pose)); + m_placed = true; + return true; +} + +void SimExecutor::start_scene_at_end(const StoryStep& step){ + std::optional end; + if (step.kind == StoryStepKind::ROUTE && step.args.contains("target")){ + end = Pokemon::pose_of(story_arg(step.args, "target")); + }else if (step.pose_after){ + end = Pokemon::pose_of(*step.pose_after); + } + if (!end){ + return; + } + SimTrigger trigger{.name = "early scene after " + step.name, .tiles = {}}; + for (const TilePos& tile : Pokemon::tiles_of(*end)){ + try{ + trigger.tiles.push_back(story_to_world(m_sim.world(), end->map, tile)); + }catch (const InternalProgramError&){} + } + // It is the scene of the trigger next to it, which then does not fire + // again (00.05b's president, a row up). + const auto next_to = [&](const TilePos& tile){ + return std::ranges::any_of(trigger.tiles, [&](const TilePos& early){ + return std::abs(early.x - tile.x) + std::abs(early.y - tile.y) == 1; + }); + }; + for (const SimTrigger& other : sim_triggers(m_sim)){ + if (std::ranges::any_of(other.tiles, next_to)){ + trigger.spends.push_back(other.name); + } + } + m_logger.log(std::format("[{}] {}: the next scene starts on its end, {}.", m_row, step.name, Pokemon::to_string(*end))); + sim_add_trigger(m_sim, std::move(trigger)); +} + +void SimExecutor::land(const std::string& step){ + const auto lands = m_knobs.lands.find(step); + if (lands == m_knobs.lands.end()){ + return; + } + m_misplaced = false; + const SimPlayer& player = m_sim.player(); + const Pose& pose = lands->second; + if (sync(pose)){ + m_misplaced = true; + m_logger.log(std::format("[{}] {}: the player lands on {}, off the table's pose.", m_row, step, to_string(player.pos))); + } +} + +// Through a door or a cave mouth onto the step's far side, the player's +// facing kept: a hold goes on from there. +bool SimExecutor::cross(){ + return m_far && cross_to(*m_far); +} +bool SimExecutor::cross_to(const Pose& far){ + const StoryWorld* world = sim_world(far.map); + const std::vector tiles = Pokemon::tiles_of(far); + if (world == nullptr || tiles.empty()){ + return false; + } + m_sim.place(setup(world), story_to_world(*world, far.map, tiles.front()), std::nullopt); + return true; +} + +// Why the player does not stand on one of `pose`'s tiles, or "" if they +// do or the simulation cannot tell (no map, or not placed yet). +std::string SimExecutor::off_pose(const Pose& pose) const{ + const std::vector tiles = Pokemon::tiles_of(pose); + if (!m_placed || tiles.empty() || sim_world(pose.map) == nullptr){ + return ""; + } + const SimPlayer& player = m_sim.player(); + const TilePos at = nearest_tile(player.pos); + // In world tiles: a pose a leg worked out from the map it started on + // may lie past that map's edge, on the next map (Twinleaf's exit). + // story_to_world() throws for a map not on the player's world. + try{ + const auto there = [&](const TilePos& tile){ return story_to_world(m_sim.world(), pose.map, tile) == at; }; + if (on_grid(player.pos) && std::ranges::any_of(tiles, there)){ + return ""; + } + }catch (const InternalProgramError&){} + return std::format("ended at {} ({}), not on {}.", to_string(player.pos), describe(m_sim.world(), at), Pokemon::to_string(pose)); +} + +// The program's run into the Center: past its door, the inside shows, a missed fade or not. +Outcome SimExecutor::heal(RunState& state, const StoryStep& step){ + if (!sync(state.pose)){ + return Pokemon::outcome_ok(); + } + run_into_center(m_io, m_walks.can_run(), [this]{ + m_misses.fade_unseen = false; + return m_sim.player().warped.has_value(); + }, [&]{ + throw GridSimFailure{step.name + ": no door north of " + to_string(m_sim.player().pos)}; + }, step.name); + if (m_misses.fading_in){ + return Pokemon::outcome_failed("heal", step.name + ": walked to the nurse while the Center was still fading in."); + } + return Pokemon::outcome_ok(); +} + +// The battle is not played. The speeches after it are, when the knobs +// script them, as the console's battle ends: confirm_battle_overworld()'s +// talk-over. +Outcome SimExecutor::battle(RunState&, const StoryStep& step){ + const auto scene = m_knobs.scenes.find(step.name); + if (scene != m_knobs.scenes.end()){ + const std::string early = play_scene(scene->second, {}); + if (!early.empty()){ + return Pokemon::outcome_failed("talk_over", step.name + ": " + early); + } + } + return stub(); +} + +// Why a walking step did not end where the table says, or "". A step +// through a door the simulation did not cross is not checked: the sim's +// maps have no warps' destinations. +std::string SimExecutor::check(const StoryStep& step, const Outcome& outcome){ + const bool walks = step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || step.kind == StoryStepKind::STEP; + const std::optional expected = step.pose_after ? std::optional(Pokemon::pose_of(*step.pose_after)) : outcome.pose; + if (!walks || !m_placed){ + return ""; + } + if (m_astray){ + m_result.unchecked.push_back(m_row + " " + step.name + " (slid on)"); + return ""; + } + if (!expected || Pokemon::tiles_of(*expected).empty()){ + m_result.unchecked.push_back(m_row + " " + step.name); + return ""; + } + const SimPlayer& player = m_sim.player(); + if (player.warped && !story_to_local(m_sim.world(), expected->map, nearest_tile(player.pos))){ + return ""; + } + return off_pose(*expected); +} + +Outcome SimExecutor::stub(){ + if (!m_result.rows.empty()){ + m_result.rows.back().stubbed.push_back(m_step); + } + m_sim.end_dialogue(); + return Pokemon::outcome_ok(); +} + +// The steps that need the console: stubbed, but for the Center's door and +// the speeches after a battle. +StoryBoundActions SimExecutor::sim_actions(){ + const auto stubbed = [this](const StoryStep&, RunState&){ + return stub(); + }; + return StoryBoundActions{ + .new_game = stubbed, + .options = stubbed, + .answer = stubbed, + .battle = [this](const StoryStep& step, RunState& state){ + return battle(state, step); + }, + .train = stubbed, + .heal = [this](const StoryStep& step, RunState& state){ + return heal(state, step); + }, + .save = stubbed, + .event = [stubbed](const std::string&) -> Pokemon::StoryActionFunction{ + return stubbed; + }, + }; +} + +// The look at a battle's opening that shows its battle: past the three +// looks of a door's fade (StoryInterrupts::max_looks), 1.8 s at BDSP's. +constexpr size_t OPENING_LOOKS = 6; + +Pokemon::ScreenLook SimExecutor::look(bool fresh){ + const WallClock start = WallClock() + std::chrono::hours(1); + Pokemon::ScreenLook out; + out.log.record({Pokemon::ScreenEvent::PLAYER_CAN_MOVE}, start); + if (std::exchange(m_dialog_rose, false)){ + out.log.record({Pokemon::ScreenEvent::DIALOG_BOX, Pokemon::ScreenEvent::PLAYER_CAN_MOVE}, start + 33ms); + } + if (m_battle_opening){ + out.log.record({Pokemon::ScreenEvent::FADE_WHITE}, start + 33ms); + m_opening_looks = fresh ? 1 : m_opening_looks + 1; + if (m_opening_looks >= OPENING_LOOKS){ + out.log.record({Pokemon::ScreenEvent::BATTLE_STARTED}, start + BETWEEN_STEPS_LOOK - 33ms); + } + } + out.window = {.start = start, .end = start + BETWEEN_STEPS_LOOK}; + return out; +} + +// A dialog or a warp closes what is up and logs it: the simulation shows +// only the dialogs it pops up. A battle ends its opening only: a scene the +// walk before ran into goes on after it. +StoryInterruptActions SimExecutor::sim_interrupt_actions(){ + const auto cleared = [this](std::string_view what){ + return [this, what](const Pokemon::InterruptVerdict&, RunState&){ + m_logger.log(std::format("[{}] {}: {} cleared before it.", m_row, m_step, what)); + m_dialog_up = false; + m_sim.end_dialogue(); + return Pokemon::outcome_ok(); + }; + }; + const auto battled = [this](std::string_view what){ + return [this, what](const Pokemon::InterruptVerdict&, RunState&){ + m_logger.log(std::format("[{}] {}: {} cleared before it.", m_row, m_step, what)); + m_battle_opening = false; + return Pokemon::outcome_ok(); + }; + }; + return StoryInterruptActions{ + .wild = battled("a wild battle"), + .trainer = battled("a trainer's battle"), + .dialog = cleared("a dialog"), + .warp = cleared("a warp"), + }; +} + +Outcome SimExecutor::run_action(const StoryStep& step, RunState& state){ + if (m_dialog_up){ + if (!presses_through_text(step.kind)){ + return Pokemon::outcome_failed("dialog", step.name + ": a dialog that popped up before it is still up"); + } + m_dialog_up = false; + } + return Pokemon::TableExecutor::run_action(step, state); +} + +Outcome SimExecutor::run_step(const StoryStep& step, RunState& state){ + if (!m_start_mismatch.empty()){ + return Pokemon::outcome_failed("sim_mismatch", "the row before " + std::exchange(m_start_mismatch, "")); + } + m_far = step.pose_after ? std::optional(Pokemon::pose_of(*step.pose_after)) : std::nullopt; + // A scene goes on from where the step before left us. A route walks + // on the world it plans on (Jubilife alone has no Route 204 north of it). + // An event of a walking kind (talk_to_wanderer) is the console's. + const Pokemon::StoryAction* action = m_table.find(step); + const bool walks = (step.kind == StoryStepKind::ROUTE || step.kind == StoryStepKind::LEGS || + step.kind == StoryStepKind::STEP || step.kind == StoryStepKind::TALK) && + action != nullptr && !action->needs_console; + const GridPose* target_ptr = step.args.contains("target") ? &story_arg(step.args, "target") : nullptr; + const StoryWorld* on = step.kind == StoryStepKind::ROUTE && target_ptr && !state.pose.map.empty() + ? story_plan_world(state.pose.map, target_ptr->map) : nullptr; + // A world of one map is sim_world()'s, with its people. + if (on != nullptr && on == story_plan_world(state.pose.map, state.pose.map)){ + on = nullptr; + } + if (walks && !sync(state.pose, on)){ + m_logger.log(std::format("[{}] {}: no map for {}; passed over.", m_row, step.name, Pokemon::to_string(state.pose))); + m_passed_over = true; + return Pokemon::outcome_ok(); + } + if (walks && m_knobs.scene_at_walk_end && m_knobs.scene_at_walk_end(m_row, step.name)){ + start_scene_at_end(step); + } + return Pokemon::TableExecutor::run(step, state); +} + +void SimExecutor::show_before(const StoryStep& step){ + if (m_knobs.dialog_before && m_knobs.dialog_before(m_row, step.name)){ + m_dialog_up = m_dialog_rose = true; + m_logger.log(std::format("[{}] {}: a dialog pops up before it.", m_row, step.name)); + } + m_battle_opening = m_knobs.battle_opening_before && m_knobs.battle_opening_before(m_row, step.name); + if (m_battle_opening){ + m_logger.log(std::format("[{}] {}: a battle's opening is still playing before it.", m_row, step.name)); + } +} + +Outcome SimExecutor::run(const StoryStep& step, RunState& state){ + Outcome outcome; + m_passed_over = false; + m_step = step.name; + sim_forget_warp(m_sim); + show_before(step); + try{ + outcome = run_step(step, state); + }catch (const GridSimFailure& e){ + outcome = Pokemon::outcome_failed("sim_failure", e.message); + } + m_battle_opening = false; + m_astray |= std::exchange(m_misses.slid, false); + const std::string mismatch = outcome.succeeded() && !m_passed_over ? check(step, outcome) : ""; + if (!mismatch.empty()){ + outcome = Pokemon::outcome_failed("sim_mismatch", step.name + ": " + mismatch); + } + // What the simulation does not play (scenes, events, battles) ends + // where the table says it does. + if (outcome.succeeded() && step.pose_after){ + m_astray = false; + m_misplaced = false; + sync(Pokemon::pose_of(*step.pose_after)); + } + if (outcome.succeeded()){ + land(step.name); + } + m_logger.log(std::format("[{}] {}: {}, the player at {}.", m_row, step.name, Pokemon::to_string(outcome), to_string(m_sim.player().pos))); + if (std::exchange(m_misses.missed, false) && m_result.missed_step.empty()){ + m_result.missed_step = m_row + " " + step.name; + } + if (!outcome.succeeded() && m_result.error.empty()){ + // The walker's last notes, to see why. + for (size_t i = m_notes.size() - std::min(m_notes.size(), 40); i < m_notes.size(); i++){ + m_logger.log(std::format("[{}] note: {}", m_row, m_notes[i])); + } + m_result.error = m_row + " " + Pokemon::to_string(outcome); + m_result.failed_step = m_row + " " + step.name; + } + const std::vector& fought = m_sim.player().scenes_fought; + for (; m_scenes_fought < fought.size(); m_scenes_fought++){ + m_logger.log(std::format("[{}] {}: the walk fought {}'s dialogue as a trainer's.", m_row, step.name, fought[m_scenes_fought])); + m_result.scenes_fought.push_back(std::format("{} {}: {}", m_row, step.name, fought[m_scenes_fought])); + } + m_result.world = m_placed ? &m_sim.world() : nullptr; + m_result.end = nearest_tile(m_sim.player().pos); + m_ran.insert(step.name); + arm(step.name); + return outcome; +} + +// Runs `range` of `rows` (the table unless given) on `executor`, stopping +// at the first failure. +Pokemon::SegmentReport run_rows_on( + SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, + const std::vector& rows +){ + std::set saved; + Pokemon::Segment segment = make_story_segment(rows, executor, saved); + Pokemon::SegmentPolicy policy; + policy.attempts_per_checkpoint = 1; + Pokemon::SegmentHooks hooks; + hooks.reload = [](RunState&){ return Pokemon::outcome_ok(); }; + hooks.log = [&logger](const std::string& line){ logger.log(line); }; + RunState state; + return Pokemon::run_segment(range, policy, segment, hooks, state); +} + +// Runs `range` of the table on the simulation, stopping at the first failure. +UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range){ + SimExecutor executor(logger); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, range); + for (const std::string& step : executor.result().unchecked){ + logger.log("No end to check after " + step + "."); + } + if (!report.completed){ + return std::format("stopped at {} {}: {}", report.failed_checkpoint, report.failed_event, executor.result().error); + } + return true; +} + +namespace detail{ +// The table with row `row`'s step of `step`'s name replaced by `step`. +std::vector table_with(const std::string& row, const StoryStep& step){ + std::vector rows = story_checkpoints(); + for (StoryCheckpoint& checkpoint : rows){ + for (StoryStep& old : checkpoint.steps){ + if (checkpoint.id == row && old.name == step.name){ + old = step; + return rows; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No step " + step.name + " in " + row); +} + +bool ends_on(const SimRun& run, const Pose& pose){ + const std::vector tiles = Pokemon::tiles_of(pose); + const std::optional local = run.world ? story_to_local(*run.world, pose.map, run.end) : std::nullopt; + return local && std::find(tiles.begin(), tiles.end(), *local) != tiles.end(); +} +std::string end_of(const SimRun& run){ + return run.world ? describe(*run.world, run.end) : "nowhere"; +} +std::string stub_report(const SimRun& run){ + std::string out; + for (const SimRun::RowStart& row : run.rows){ + out += std::format("{}: {} stubbed", row.row, row.stubbed.size()); + for (size_t i = 0; i < row.stubbed.size(); i++){ + out += (i == 0 ? ": " : ", ") + row.stubbed[i]; + } + out += "\n"; + } + return out; +} +} // namespace detail + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h new file mode 100644 index 0000000000..d3b01e85de --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim.h @@ -0,0 +1,574 @@ +/* BDSP AutoStory - Story simulation + * + * From: https://github.com/PokemonAutomation/ + * + * The story table's rows run as the program runs them (the segment + * runner, make_story_segment()), with the program's own walking steps + * (StoryWalkSteps) on the grid simulation; see StorySim_Tests.cpp for + * what is simulated and what is stubbed. Moved out of the tests so the + * console failure cases (SimFailureCases_Tests) run on the same executor. + * +// code-health: allow header_symbols -- story simulation executor, scenario runners and mock IO + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StorySim_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StorySim_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "Pokemon/AutoStory/Pokemon_StoryStepExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_TalkOver.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryActions.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryInterrupts.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkResult.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_WalkScreen.h" +#include "PokemonBDSP_AutoStory_GridSim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Which detections the simulation misses on purpose (#162): the `fade`th +// door fade (run_into_door(), from 0) or the `banner`th map banner +// (run_until_map()) of the run goes unseen, though the player did go +// through. The console missed both (r75, r81). The `hold`th fade (counted +// with `fade`'s) shows its fall and the scene after but not its hold: a +// short fade's hold between two frames. The `dark`th door run reads +// dark detail::SIM_FALSE_DARK in, short of the door, as lab-B's did on 2026-11-08. +// The `through`th tap step (tap_to_banner(), from 0) starts on its far side, +// its banner gone unless `through_banner`: the walk before it slid onto the +// warp (lab-B 2026-11-08). The counts and flags below are the run's: how +// many fades and banners it looked for, whether a miss happened since the +// executor last looked, whether a missed fade is still unseen, whether a +// walk slid on (SimSlide) since the executor last looked, and the map whose +// banner a slide left up for the next step. +struct SimMisses{ + std::optional fade; + std::optional banner; + std::optional hold = {}; + std::optional dark = {}; + std::optional through = {}; + bool through_banner = false; + size_t tap_steps = 0; + size_t fades = 0; + size_t banners = 0; + size_t doors = 0; + bool missed = false; + bool fade_unseen = false; + // A door's fade showed and nothing has settled since: on the console + // the inside is still fading in, and a walk then goes nowhere (lab-B + // 2026-11-10, 00.04b heal_sandgem: "nurse not reached"). + bool fading_in = false; + bool slid = false; + std::string banner_up = {}; +}; + +// How a warp's fade looks on the screen (#268's design note); the +// program's fade_of() judges it, as the walk's watchers do. +enum class SimFade{ + // A door's: near black (SIM_DOOR_FADE). + BLACK, + // A cave mouth's: dim, not black (SIM_DIM_FADE). The walk's old strict + // black watcher (rgb sum 100) missed it and the walk went on (the + // Oreburgh Gate, lab-B 2026-11-08 16:03). + DIM, + // A cave exit's white. The walk's old encounter-flash watcher read it + // as a wild battle. + WHITE, +}; + +// An open leg that runs on past its end: the walk taps of the step `step` +// toward `direction` go `tiles` further, once per step. Onto a warp, the +// player lands on `far` (the sim's maps have no warps' destinations), the +// walk sees the fade as `fade` looks, and the far map's banner is still up +// for the next step (`banner_up`) or gone (01.05, lab-B 2026-11-08 15:31). +struct SimSlide{ + std::string step; + Pokemon::Direction direction = Pokemon::Direction::WEST; + size_t tiles = 1; + Pokemon::Pose far = {}; + SimFade fade = SimFade::DIM; + bool banner_up = false; +}; + +namespace detail{ +// One beat of a scripted scene: a line, up until a press, or `length` of +// screen with no box, `overworld` or not (a battle's end, a fade), +// `moving` (someone walking, the camera panning) or still, faded as `fade`. +struct SimBeat{ + std::string what; + bool line = false; + Milliseconds length = Milliseconds(0); + bool overworld = true; + bool moving = false; + WarpFade fade = WarpFade::NONE; +}; +// A line, up until a press. +SimBeat sim_line(std::string what); +// `length` of overworld with no box, someone moving or not. +SimBeat sim_pause(std::string what, Milliseconds length, bool moving); +// `length` of a fade, as BDSP's eyes see it: no box, so the overworld, +// and still (a black frame matches the one before). +SimBeat sim_fade(std::string what, Milliseconds length, WarpFade fade = WarpFade::BLACK); +// A talk or a scene as the screen shows it, beat by beat; the quiet +// overworld after the last beat. +using SimScene = std::vector; +// Plays `scene` against the program's TalkOver with `rule`, a look per +// press, as talk_over() takes them: "" if it is judged over after the last +// beat, else when it was judged over early, or that it never was. +std::string play_scene(const SimScene& scene, const TalkOverRule& rule); +} // namespace detail + +// What the console showed that the plain simulation leaves out, each off +// unless set. All of it is deterministic: wanderers walk from `wander_seed`. +struct SimWorldKnobs{ + std::vector slides = {}; + // The mean brightness (0 to 255) of a map's floor, by JSON map name, and + // of the fade into a map; a tap step judges its fade from these with the + // program's fade_of(), a floor textured, a fade uniform (SIM_FLOOR_STDDEV, + // SIM_FADE_STDDEV). Unset: 104 (Oreburgh's street by day) and 7 (a + // door's black). + std::map floor = {}; + std::map fade_into = {}; + // People with a wander box on their map walk it, a step tried every 2 s. + std::optional wander_seed = std::nullopt; + // How long after the A press a talk's first line shows, by step name. + std::map first_line = {}; + // The scene a step's talk-over plays, by step name: a scene's or a + // door's settle(), or the speeches after a battle step's battle. + std::map scenes = {}; + // Whether a dialog pops up right before row `row`'s step `step`: + // someone walks up and talks between two steps. Until it is pressed + // through, it stops a step that walks or talks, as on the console. + std::function dialog_before = nullptr; + // Whether a battle's opening is still playing when row `row`'s step + // `step` starts: the encounter's white, no battle yet (00.02's Starly + // battle right after the starter is picked, lab-B 2026-11-09). + std::function battle_opening_before = nullptr; + // Whether the executor clears what came up between steps + // (story_interrupts()), as the console does; off, as before it did. + bool clear_interrupts = true; + // Where a step really leaves the player, by step name, when that is + // not the table's pose_after or the walk's end: the program goes on + // from the table's pose, the player from here (00.03's scene a row + // low, lab-B 2026-11-09; 00.04b's run into Sandgem two columns west, + // lab-B 2026-11-09 20:09). + std::map lands = {}; + // Wild battles in tall grass on every pass (SimGrassBattles); none unset. + SimGrassBattles grass = {}; + // Whether the scene after row `row`'s walk `step` starts early, on the + // walk's last tiles (its target): its trigger lies on the way, so the + // walk runs into it (00.04's Mom's call on (6, 9), lab-B 2026-11-09 17:29). + std::function scene_at_walk_end = nullptr; +}; + +namespace detail{ + +// The walker's RouteIO on the story simulation, with SimWorldKnobs' slides +// and late first lines. `step` names the step running now; `cross` puts +// the player on a pose past a warp. +class SimKnobRouteIO : public GridSimRouteIO{ +public: + SimKnobRouteIO( + GridSim& sim, std::vector& notes, SimMisses& misses, const SimWorldKnobs& knobs, + const std::string& step, std::function cross + ) + : GridSimRouteIO(sim, notes, {}, {}, knobs.grass) + , m_grid(sim) + , m_misses(misses) + , m_knobs(knobs) + , m_step(step) + , m_cross(std::move(cross)) + {} + + virtual WalkResult walk_taps(Pokemon::Direction direction, size_t tiles, const std::string& label) override; + virtual bool dialog_within(Milliseconds wait, Color color) override; + +private: + WalkResult slide_on(const SimSlide& slide, WalkResult result); + + GridSim& m_grid; + SimMisses& m_misses; + const SimWorldKnobs& m_knobs; + const std::string& m_step; + std::function m_cross; + std::set m_slid_steps; +}; +} // namespace detail + +namespace detail{ + +// How many tiles a held walk goes on into a map before its location +// banner reads: "it shows a tile or a few past the border" (the table's +// route_201_by_the_path(), measured on the console). Standing still, it +// reads at once. Through a cave mouth the fade comes first, and a hold +// whose fade went unseen goes on the same way (r75, r81). +constexpr size_t SIM_BANNER_TILES = 3; +// How far into a door run SimMisses::dark reads dark, short of the door. +constexpr Milliseconds SIM_FALSE_DARK = Milliseconds(1800); +// Brightness (0 to 255) of a floor where SimWorldKnobs does not say: +// Oreburgh's street by day (r74). +constexpr double SIM_FLOOR = 104; +// Brightness of a fade where SimWorldKnobs does not say: a door's black (by hand: 7). +constexpr double SIM_DOOR_FADE = 7; +// Brightness of a cave mouth's dim fade (45 to 64 measured). +constexpr double SIM_DIM_FADE = 55; +// Brightness of a cave exit's white fade. +constexpr double SIM_WHITE_FADE = 250; +// The spread (stddev a channel) of a fade: uniform. A model, not measured +// on the console. +constexpr double SIM_FADE_STDDEV = 1; +// The spread of a floor, which the game draws with texture. A model too. +constexpr double SIM_FLOOR_STDDEV = 20; +// The screen's middle as fade_of() reads it: `brightness` a channel, `stddev` a channel. +ImageStats sim_screen(double brightness, double stddev); +// The frames a warp's fade shows, 33 ms apart (the console's 30 fps): the +// floor (`floor`, textured), the fall, the hold of `fade` (uniform) and the +// rise, and the floor on the far side. Without `hold_seen` only the fall +// shows between the floors: a short fade's hold fell between two frames. +std::vector sim_fade_frames(double floor, double fade, bool hold_seen); +// The fade the program's WarpFadeWatch with `rule` sees in those frames; +// each scene after a fall is another (the far side's). +WarpFade sim_watch_fade(const WarpFadeRule& rule, double floor, double fade, bool hold_seen); +} // namespace detail + +// What a run on the simulation did. +struct SimRun{ + // The first failure, as "row outcome", or "". + std::string error; + // The rows and steps where an injected miss happened and where the run + // first failed, as "row step": "" if none. + std::string missed_step; + std::string failed_step; + // Walking steps that end where nothing says, as "row step". + std::vector unchecked; + // Each row run, with the fades and banners looked for before it, and + // its steps the simulation did not play (stub()), in order. + struct RowStart{ + std::string row; + size_t fades; + size_t banners; + std::vector stubbed = {}; + }; + std::vector rows; + // Where the player stood after the last step, if placed. + const StoryWorld* world = nullptr; + Pokemon::TilePos end; + // Scenes a walk took for a trainer's and pressed through, as + // "row step: scene" (the console's unknown-trainer handler, lab-B + // 2026-11-09 17:29: Mom's call, then her scene's fade missed). + std::vector scenes_fought = {}; +}; + +// StoryStepIO on the simulation. A walk through a door or a cave mouth +// stops on its tile, as the console stops at the fade; a hold that misses +// the fade carries on, onto `far_side()` (the step's pose_after: the +// sim's maps have no warps' destinations) and on along it. +class SimStoryStepIO : public StoryStepIO{ +public: + SimStoryStepIO( + GridSim& sim, std::vector& notes, SimMisses& misses, const SimWorldKnobs& knobs, + const std::string& step, std::function far_side, std::function cross + ) + : m_sim(sim) + , m_route(sim, notes, misses, knobs, step, std::move(cross)) + , m_misses(misses) + , m_knobs(knobs) + , m_far_side(std::move(far_side)) + , m_step(step) + {} + + virtual RouteIO& route() override{ + return m_route; + } + // A scene's dialogue fought as a trainer's is pressed through under the + // walk, not its own step: noted (sim_fight()). + virtual void fight(const std::string&) override{ + detail::sim_fight(m_sim); + } + virtual void walk_until_stopped(Pokemon::Direction direction, size_t tiles, const std::string& label) override; + virtual bool run_until_map(Pokemon::Direction direction, Milliseconds limit, const std::string& map, const std::string&) override; + // A door's fade stops the run; with the fade missed, the run goes on + // holding and sees the far map's `banner` show after it, if it has one + // (story_arrival_banner(): the sim's maps have no banners of their own). + virtual WarpSeen run_into_door(Pokemon::Direction direction, bool run, Milliseconds timeout = Milliseconds(12000), + Milliseconds dark_from = Milliseconds(0), const std::string& banner = "") override{ + const SimPace pace = run ? SimPace::RUN : SimPace::WALK; + if (false_dark() && dark_from <= detail::SIM_FALSE_DARK && detail::SIM_FALSE_DARK < timeout){ + m_sim.hold(direction, detail::SIM_FALSE_DARK, pace); + return {.fade = WarpFade::BLACK}; + } + if (m_sim.hold(direction, timeout, pace).stop != SimStop::WARP){ + return {}; + } + const WarpSeen seen = door_fade(banner); + m_misses.fading_in = seen.any(); + return seen; + } + // A fade missed on the way in stays missed: it was over before settle() + // looked, which then fails as it does on the console after 120 s. The + // run before looked for the banner (run_into_door()), so settle() sees + // none here. With a scene in SimWorldKnobs::scenes, the program's + // TalkOver plays it instead. + virtual void settle(Button, const std::string& label, bool fade, const std::string&) override; + virtual std::optional tap_to_banner(Pokemon::Direction direction, const std::string& map, size_t max_taps) override; + +private: + // How the run shows its next fade (SimMisses): whole, its hold unseen, + // or not at all. + enum class FadeShown{ + SEEN, + HOLD_UNSEEN, + UNSEEN, + }; + FadeShown next_fade(); + // The next fade, of brightness `fade` from the floor here, as the + // program's watch with `rule` sees it. + WarpFade watched_fade(const WarpFadeRule& rule, double fade); + // What a door run that reached its warp saw (run_into_door()). + WarpSeen door_fade(const std::string& banner); + // Whether this door run reads dark short of the door, or the run + // misses this banner (SimMisses). + bool false_dark(){ + const bool dark = m_misses.dark == m_misses.doors++; + m_misses.missed |= dark; + return dark; + } + bool banner_missed(){ + const bool miss = m_misses.banner == m_misses.banners++; + m_misses.missed |= miss; + return miss; + } + bool on_map(const std::string& map) const{ + return story_to_local(m_sim.world(), map, nearest_tile(m_sim.player().pos)).has_value(); + } + // The brightness of the floor the player stands on (SimWorldKnobs::floor). + double floor_here() const; + + GridSim& m_sim; + detail::SimKnobRouteIO m_route; + SimMisses& m_misses; + const SimWorldKnobs& m_knobs; + std::function m_far_side; + const std::string& m_step; +}; + +namespace detail{ + +// A scene's trigger the simulation fires from row `row` on, once the step +// `after` has run ("" from the row's start), on `map`'s `tiles`, while its +// story variable `var` holds the value it waits for. +struct RowTrigger{ + std::string row; + std::string after; + std::string map; + SimTrigger trigger; + std::string var = {}; +}; + +// When a story variable holds the value its coord events wait for: from +// row `row` on, once the step `after` has run ("" from the row's start). +struct VarState{ + std::string var; + int value; + std::string row; + std::string after; +}; + +// The story variables whose coord events the table walks onto, and from +// which row and step each holds (the definition says why each). +std::vector story_vars(); +// The maps' coord events whose story variable holds, as triggers. +std::vector story_triggers(); +} // namespace detail + +// The program's walking steps on the simulation, the rest stubbed: the +// story's action table (story_action_table()), its rows that need the +// console bound to the stand-ins below. +class SimExecutor : public Pokemon::TableExecutor{ +public: + // The table and the guard are members, built after the base: it only + // keeps references to them until a step runs. + explicit SimExecutor(Logger& logger, SimMisses misses = {}, SimWorldKnobs knobs = {}) + : Pokemon::TableExecutor(m_table, m_guard) + , m_logger(logger) + , m_misses(misses) + , m_knobs(std::move(knobs)) + , m_sim({}, {0, 0}, Pokemon::Direction::NORTH, false) + , m_io(m_sim, m_notes, m_misses, m_knobs, m_step, [this]{ return cross(); }, [this](const Pokemon::Pose& far){ cross_to(far); }) + , m_walks(m_io) + , m_table(story_action_table(m_walks, sim_actions())) + , m_interrupts(story_interrupts([this](bool fresh){ return look(fresh); }, sim_interrupt_actions())) + { + if (m_knobs.clear_interrupts){ + set_interrupts(&m_interrupts); + } + } + + const SimMisses& misses() const{ + return m_misses; + } + const SimRun& result() const{ + return m_result; + } + // Every line the walks wrote, the route walker's and the leg records + // ("[Leg] ...") among them. + const std::vector& notes() const{ + return m_notes; + } + // The story's actions as the simulation binds them. + const Pokemon::StoryActionTable& actions() const{ + return m_table; + } + virtual void begin_attempt(const Pokemon::StoryCheckpoint& data) override{ + m_row = data.id; + m_start_mismatch = data.start ? off_pose(Pokemon::pose_of(*data.start)) : ""; + m_ran.clear(); + m_astray = false; + m_result.rows.push_back({.row = data.id, .fades = m_misses.fades, .banners = m_misses.banners}); + m_walks.begin_attempt(data.id, data.steps); + arm(""); + } + virtual Pokemon::Outcome run(const Pokemon::StoryStep& step, Pokemon::RunState& state) override; + +protected: + // A dialog that popped up and is still up stops a step that walks or + // talks; a step that presses through text closes it. + virtual Pokemon::Outcome run_action(const Pokemon::StoryStep& step, Pokemon::RunState& state) override; + virtual Pokemon::Outcome heal(Pokemon::RunState& state, const Pokemon::StoryStep& step); + virtual Pokemon::Outcome new_game(Pokemon::RunState&, const Pokemon::StoryStep&){ return stub(); } + virtual Pokemon::Outcome options(Pokemon::RunState&, const Pokemon::StoryStep&){ return stub(); } + virtual Pokemon::Outcome answer(Pokemon::RunState&, const Pokemon::StoryStep&){ return stub(); } + virtual Pokemon::Outcome battle(Pokemon::RunState& state, const Pokemon::StoryStep& step); + virtual Pokemon::Outcome train(Pokemon::RunState&, const Pokemon::StoryStep&){ return stub(); } + virtual Pokemon::Outcome shop(Pokemon::RunState&, const Pokemon::StoryStep&){ return stub(); } + virtual Pokemon::Outcome save(Pokemon::RunState&, const Pokemon::StoryStep&){ return stub(); } + virtual Pokemon::Outcome game(Pokemon::RunState&, const Pokemon::StoryStep&){ return stub(); } + +private: + // A failed step fails the run as it threw: the simulation has no save + // to reload. + class SimStepGuard : public Pokemon::StepGuard{ + public: + virtual bool stops_on_failure(const Pokemon::StoryStep&) const override{ + return true; + } + }; + + // A step the simulation does not play: its dialogue opened and closed. + Pokemon::Outcome stub(); + StoryBoundActions sim_actions(); + // The screen between steps: the dialog that popped up, if one did; a + // battle's opening, its battle on the OPENING_LOOKS-th look. `fresh` + // starts a new look. + Pokemon::ScreenLook look(bool fresh); + // What the knobs put on the screen before `step`: a dialog that pops + // up, a battle's opening still playing. + void show_before(const Pokemon::StoryStep& step); + StoryInterruptActions sim_interrupt_actions(); + const StoryWorld* sim_world(const std::string& map) const; + SimWorld setup(const StoryWorld* world) const; + void arm(const std::string& after); + bool sync(const Pokemon::Pose& pose, const StoryWorld* on = nullptr); + // Puts a trigger on walk `step`'s last tiles (SimWorldKnobs::scene_at_walk_end). + void start_scene_at_end(const Pokemon::StoryStep& step); + // Puts the player where SimWorldKnobs::lands says `step` leaves them, if it says. + void land(const std::string& step); + bool cross(); + bool cross_to(const Pokemon::Pose& far); + std::vector wanderers(const StoryWorld& world) const; + std::string off_pose(const Pokemon::Pose& pose) const; + std::string check(const Pokemon::StoryStep& step, const Pokemon::Outcome& outcome); + Pokemon::Outcome run_step(const Pokemon::StoryStep& step, Pokemon::RunState& state); + + Logger& m_logger; + std::vector m_notes; + SimMisses m_misses; + SimWorldKnobs m_knobs; + // The step running now. + std::string m_step; + GridSim m_sim; + SimStoryStepIO m_io; + StoryWalkSteps m_walks; + SimStepGuard m_guard; + Pokemon::StoryActionTable m_table; + Pokemon::StoryInterrupts m_interrupts; + // The scenes fought so far that SimRun::scenes_fought has. + size_t m_scenes_fought = 0; + // A dialog popped up (SimWorldKnobs::dialog_before) and is still up; + // it rose since the last look. + bool m_dialog_up = false; + bool m_dialog_rose = false; + // A battle's opening is playing before this step + // (SimWorldKnobs::battle_opening_before). + bool m_battle_opening = false; + // Looks at the opening so far, from the fresh one. + size_t m_opening_looks = 0; + // The planner's worlds with sim_people() on them, by world and who. + mutable std::map, std::unique_ptr> m_peopled; + // The steps of this row that have run. + std::set m_ran; + std::string m_row; + std::vector m_armed; + // Where the step running now ends, if it says: a door's far side. + std::optional m_far; + // Why the player is not on this row's start, or "". + std::string m_start_mismatch; + // Whether the player has been put on a map yet. + bool m_placed = false; + // Whether the step running now is on a room with no map. + bool m_passed_over = false; + // Whether a walk slid on (SimSlide), so the player is not where the + // program thinks, until a step's pose_after puts them right. + bool m_astray = false; + // Whether a step left the player off its pose_after (SimWorldKnobs::lands), + // so the walks go on from there, checked, until a step's pose_after + // puts them right. + bool m_misplaced = false; + SimRun m_result; +}; + +// Runs `range` of `rows` (the table unless given) on `executor`, stopping +// at the first failure. +Pokemon::SegmentReport run_rows_on( + SimExecutor& executor, Logger& logger, const Pokemon::SegmentRange& range, + const std::vector& rows = story_checkpoints() +); +// Runs `range` of the table on the simulation, stopping at the first failure. +UnitTestResult run_rows(Logger& logger, const Pokemon::SegmentRange& range); +namespace detail{ + +// The table with row `row`'s step of `step`'s name replaced by `step`. +std::vector table_with(const std::string& row, const Pokemon::StoryStep& step); +// Whether the run ended on one of `pose`'s tiles. +bool ends_on(const SimRun& run, const Pokemon::Pose& pose); +// Where the run ended, described; "nowhere" if never placed. +std::string end_of(const SimRun& run); +// Each row's steps the simulation did not play, a line a row: +// "01.03: 2 stubbed: save, gym_until_roark_beaten". +std::string stub_report(const SimRun& run); +} // namespace detail + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp new file mode 100644 index 0000000000..56af9971a4 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.cpp @@ -0,0 +1,393 @@ +/* BDSP AutoStory Story Sim Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Rows of the story table run as the program runs them (the segment + * runner, make_story_segment()), with the program's own walking steps + * (StoryWalkSteps: ROUTE, LEGS, STEP, TALK, MASH) on the grid simulation. + * After each walking step the simulated player must stand, on the grid, + * on a tile the table gives; a step through a door must have warped. + * + * Events, battles, shops and saves are stubs: a dialogue they open is + * closed, and the table's pose_after puts the player where they end. A + * heal checks that a walk north from where we stand enters a door. A scene + * starts when the player steps onto one of the maps' coord events while + * its story variable holds (story_vars()). Rooms with no + * map (the Trainers' School) are passed over. Each row must start where + * the row before left the player. + * + * A tap or hold through a door or cave mouth stops on its tile, as the + * console stops at the fade; a hold that does not see the fade goes on + * onto the step's pose_after and on along it, and a location banner reads + * only a few tiles into its map (SIM_BANNER_TILES). The exit tests run + * r75's and r81's old open-ended walks that way. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_StorySegments.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_CoordEvents.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WalkRules.h" +#include "PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_LegTrace_Tests.h" +#include "PokemonBDSP_AutoStory_OldStorySteps.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_RouteWalk.h" +#include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Resources.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_StorySim.h" +#include "PokemonBDSP_AutoStory_StorySim_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +using namespace detail; + +namespace{ + +using namespace std::chrono_literals; +using Pokemon::Direction; +using Pokemon::Outcome; +using Pokemon::Pose; +using Pokemon::RunState; +using Pokemon::StoryStep; +using Pokemon::StoryStepKind; +using Pokemon::TilePos; + +UnitTestResult run_exit_test(Logger& logger, const std::string& row_id, const StoryStep& old_step, const SimMisses& misses, const Pose& overshoot){ + SimExecutor executor(logger, misses); + const std::vector rows = table_with(row_id, old_step); + run_rows_on(executor, logger, {.from = row_id, .to = row_id}, rows); + const SimRun& run = executor.result(); + logger.log(std::format("The old {}: {}, ended on {}.", old_step.name, run.error, end_of(run))); + if (run.failed_step != row_id + " " + old_step.name || !ends_on(run, overshoot)){ + return std::format("the old {} should end on {} and fail there; it ended on {}: {}", + old_step.name, Pokemon::to_string(overshoot), end_of(run), run.error.empty() ? "no failure" : run.error); + } + SimExecutor clean(logger); + if (!run_rows_on(clean, logger, {.from = row_id, .to = row_id}).completed){ + return "the table's row fails without misses: " + clean.result().error; + } + std::vector runs; + for (size_t i = 0; i < clean.misses().fades; i++){ + runs.push_back({.fade = i, .banner = std::nullopt}); + } + for (size_t i = 0; i < clean.misses().banners; i++){ + runs.push_back({.fade = std::nullopt, .banner = i}); + } + for (const SimMisses& m : runs){ + SimExecutor sim(logger, m); + run_rows_on(sim, logger, {.from = row_id, .to = row_id}); + if (ends_on(sim.result(), overshoot)){ + return std::format("the table's {} ended on {} with a miss in {}.", old_step.name, end_of(sim.result()), + sim.result().missed_step); + } + } + return true; +} + +UnitTestResult test_coord_events(Logger&){ + for (const auto& [map, json] : bdsp_map_json()){ + const StoryWorld* world = story_plan_world(map, map); + for (const CoordEvent& event : world == nullptr ? std::vector{} : story_coord_events(map)){ + const auto open = [&](const TilePos& pos){ + const TilePos tile = story_to_world(*world, map, pos); + return standable(*world, tile) || world->tile(tile) == Pokemon::TileKind::DOOR; + }; + if (!std::ranges::any_of(event.tiles, open)){ + return std::format("{} {}: no tile is open ground or a door.", map, event.name); + } + } + } + const size_t armed = story_triggers().size(); + return armed == story_vars().size() ? UnitTestResult(true) + : UnitTestResult(std::format("Expected {} coord events armed by the story's variables, found {}.", story_vars().size(), armed)); +} + +std::string miss(Logger& logger, const SimRun& clean, bool fade, size_t index){ + size_t k = 0; + while (k + 1 < clean.rows.size() && (fade ? clean.rows[k + 1].fades : clean.rows[k + 1].banners) <= index){ + k++; + } + const SimRun::RowStart& start = clean.rows[k]; + SimMisses misses; + (fade ? misses.fade : misses.banner) = index - (fade ? start.fades : start.banners); + SimExecutor executor(logger, misses); + const Pokemon::SegmentReport report = run_rows_on(executor, logger, + {.from = start.row, .to = clean.rows[std::min(k + 1, clean.rows.size() - 1)].row}); + const SimRun& run = executor.result(); + const std::string what = std::format("{} {}", fade ? "fade" : "banner", index); + logger.log(std::format("Missed {} in {}: {}.", what, run.missed_step, + report.completed ? "got over it" : "stopped in " + run.failed_step + ": " + run.error)); + if (report.completed || run.failed_step == run.missed_step){ + return ""; + } + return std::format("{} missed in {}, failed later in {}: {}", what, run.missed_step, run.failed_step, run.error); +} + +UnitTestResult test_story_sim_misses(Logger& logger){ + Pokemon::SegmentRange range{.from = "00.00", .to = "01.11"}; + SimExecutor clean(logger); + if (!run_rows_on(clean, logger, range).completed){ + return "the run fails without misses: " + clean.result().error; + } + logger.log(std::format("{} fades and {} banners to miss.", clean.misses().fades, clean.misses().banners)); + std::vector unseen; + for (size_t i = 0; i < clean.misses().fades + clean.misses().banners; i++){ + const std::string line = miss(logger, clean.result(), i < clean.misses().fades, i < clean.misses().fades ? i : i - clean.misses().fades); + if (!line.empty()){ + unseen.push_back(line); + } + } + std::string out = "Misses that went unseen:"; + for (const std::string& line : unseen){ + out += "\n " + line; + } + return unseen.empty() ? UnitTestResult(true) : UnitTestResult(out); +} + +// Someone talks to the player before every step (SimWorldKnobs:: +// dialog_before): cleared between steps, the whole table still passes; +// left up, as before the executor looked, the first walk fails on it. +UnitTestResult test_dialog_between_steps(Logger& logger){ + const Pokemon::SegmentRange range{.from = "00.00", .to = "01.11"}; + const auto always = [](const std::string&, const std::string&){ + return true; + }; + SimExecutor cleared(logger, {}, {.dialog_before = always}); + if (!run_rows_on(cleared, logger, range).completed){ + return "A dialog before every step, cleared: " + cleared.result().error; + } + SimExecutor left(logger, {}, {.dialog_before = always, .clear_interrupts = false}); + run_rows_on(left, logger, range); + if (left.result().error.find(" dialog: ") == std::string::npos){ + return "Expected a dialog left up to stop a walk, got: " + left.result().error; + } + return true; +} + +UnitTestResult test_story_sim_whole_table(Logger& logger){ + return run_rows(logger, {.from = "00.00", .to = "01.11"}); +} + +UnitTestResult test_story_sim_each_row(Logger& logger){ + for (const StoryCheckpoint& row : story_checkpoints()){ + const auto res = run_rows(logger, {.from = row.id, .to = row.id}); + if (res.result != UnitTestResult::PASSED){ + return std::format("Row {} failed: {}", row.id, res.message); + } + } + return true; +} + +UnitTestResult test_exit_gate(Logger& logger){ + return run_exit_test(logger, "01.05", r75_old_gate_exit(), SimMisses{}, r75_pond_pocket()); +} + +UnitTestResult test_exit_ravaged_path(Logger& logger){ + return run_exit_test(logger, "01.09", r81_old_cave_exit(), SimMisses{.fade = 0, .banner = std::nullopt}, r81_below_the_mouth()); +} + +// lab-B 2026-11-08 15:31 to 15:54: 01.05's walk to the tile beside the +// Oreburgh Gate's mouth slid onto the warp, and the tap step after it began +// inside the Gate. With its banner up, the step ends there with no tap and +// no fade (the clean run's fade into the Gate is not seen); with it gone, +// it fails a few taps on, not across the Gate. +UnitTestResult test_tap_through_already(Logger& logger, bool banner){ + const std::vector rows = table_with("01.05", old_tap_into_the_gate()); + SimExecutor clean(logger); + run_rows_on(clean, logger, {.from = "01.05", .to = "01.05"}, rows); + SimExecutor through(logger, {.fade = {}, .banner = {}, .through = 1, .through_banner = banner}); + run_rows_on(through, logger, {.from = "01.05", .to = "01.05"}, rows); + const SimRun& run = through.result(); + const std::optional at = run.world ? story_to_local(*run.world, "OreburghGate", run.end) : std::nullopt; + const bool passed = banner + ? run.error.empty() && through.misses().fades + 1 == clean.misses().fades + : run.failed_step == "01.05 into_oreburgh_gate" && at && at->y == 22 && at->x >= 21; + return passed ? UnitTestResult(true) : UnitTestResult(std::format("failed in '{}' on {} after {} fades (clean {}): {}", + run.failed_step, end_of(run), through.misses().fades, clean.misses().fades, run.error.empty() ? "no failure" : run.error)); +} + +UnitTestResult test_story_sim_step_failure(Logger& logger, const std::string& row, const StoryStep& old_step, const std::string& expected_failed_step, const std::string& expected_error){ + SimExecutor executor(logger); + const std::vector rows = table_with(row, old_step); + run_rows_on(executor, logger, {.from = row, .to = row}, rows); + const SimRun& run = executor.result(); + if (run.failed_step != expected_failed_step || run.error.find(expected_error) == std::string::npos){ + return std::format("expected old {} to fail at '{}' with '{}', but got failed_step='{}', error='{}'.", + old_step.name, expected_failed_step, expected_error, run.failed_step, run.error); + } + return true; +} + +// lab-B 2026-11-08: 01.03's run into Oreburgh's Center saw no fade and went +// on to the nurse's counter. The heal must find it is inside and go on. +UnitTestResult test_heal_fade_unseen(Logger& logger){ + SimExecutor clean(logger); + run_rows_on(clean, logger, {.from = "01.03", .to = "01.03"}); + for (size_t i = 0; i < clean.misses().fades; i++){ + SimExecutor sim(logger, {.fade = i, .banner = {}}); + run_rows_on(sim, logger, {.from = "01.03", .to = "01.03"}); + const SimRun& run = sim.result(); + if (run.missed_step == "01.03 heal_oreburgh"){ + return run.error.empty() ? UnitTestResult(true) : UnitTestResult(std::format("failed in '{}': {}", run.failed_step, run.error)); + } + } + return "no fade in 01.03 heal_oreburgh to miss: the heal never ran into its door."; +} + +// The sim's frames of a warp's fade through the program's own watches +// (sim_watch_fade()): a door's black, a cave mouth's dim fade and a cave +// exit's white, each with its hold seen and unseen. Only on a floor as +// dark as the fall (a street at night, 88) is a fade whose hold went unseen +// still missed: no frame shows the scene before it. +UnitTestResult test_sim_fade_frames(Logger&){ + struct FadeCase{ + std::string_view name; + bool door; + double floor; + double fade; + bool hold_seen; + WarpFade seen; + }; + const std::vector cases{ + {"a door's black", true, SIM_FLOOR, SIM_DOOR_FADE, true, WarpFade::BLACK}, + {"a door's black, its hold unseen", true, SIM_FLOOR, SIM_DOOR_FADE, false, WarpFade::BLACK}, + {"a tap into a door's black", false, SIM_FLOOR, SIM_DOOR_FADE, true, WarpFade::BLACK}, + {"a tap into a door's black, its hold unseen", false, SIM_FLOOR, SIM_DOOR_FADE, false, WarpFade::BLACK}, + {"a tap into a cave mouth's dim fade", false, SIM_FLOOR, SIM_DIM_FADE, true, WarpFade::BLACK}, + {"a tap into a cave mouth's dim fade, its hold unseen", false, SIM_FLOOR, SIM_DIM_FADE, false, WarpFade::BLACK}, + {"a tap into a cave exit's white", false, SIM_FLOOR, SIM_WHITE_FADE, true, WarpFade::WHITE}, + {"a tap into a cave exit's white, its hold unseen", false, SIM_FLOOR, SIM_WHITE_FADE, false, WarpFade::WHITE}, + {"a door's black from the Gate's dim floor (46), its hold unseen", true, 46, SIM_DOOR_FADE, false, WarpFade::BLACK}, + {"a tap from a street at night (88)", false, 88, SIM_DOOR_FADE, true, WarpFade::BLACK}, + {"a tap from a street at night (88), its hold unseen", false, 88, SIM_DOOR_FADE, false, WarpFade::NONE}, + }; + for (const FadeCase& item : cases){ + const WarpFade seen = sim_watch_fade(item.door ? DOOR_FADE_RULE : TAP_FADE_RULE, item.floor, item.fade, item.hold_seen); + if (seen != item.seen){ + return std::format("{}: saw {}, expected {}.", item.name, warp_fade_name(seen), warp_fade_name(item.seen)); + } + } + return true; +} + +struct AutoStoryStorySimInput{ + std::string name; + std::function body; +}; + +struct AutoStoryStorySimExpectation{ +}; + +struct AutoStoryStorySimCase{ + AutoStoryStorySimInput input; + AutoStoryStorySimExpectation expectation; +}; + +class Test_AutoStoryStorySim : public UnitTest{ +public: + explicit Test_AutoStoryStorySim(AutoStoryStorySimCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Story sim: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.input.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + AutoStoryStorySimCase m_case; +}; + +} // namespace + +const AutoStoryStorySimCase AUTO_STORY_STORY_SIM_CASES[] = { + {.input = {"the maps' coord events are on open ground or doors", test_coord_events}, .expectation = {}}, + {.input = {"detector misses from 00.00 to 01.11", test_story_sim_misses}, .expectation = {}}, + {.input = {"a warp's fade on the sim's frames, through the door's and the taps' watches", test_sim_fade_frames}, .expectation = {}}, + {.input = {"00.00 to 01.11: the whole table, from the new game to Floaroma", test_story_sim_whole_table}, .expectation = {}}, + {.input = {"each row from 00.00 to 01.11 in isolation", test_story_sim_each_row}, .expectation = {}}, + {.input = {"a dialog pops up before every step from 00.00 to 01.11", test_dialog_between_steps}, .expectation = {}}, + {.input = {"01.02b, Barry's lines, then the Center past his doorstep (lab-B, 2026-11-08)", [](Logger& logger){ + return run_rows(logger, {.from = "01.02b", .to = "01.02b"}); + }}, .expectation = {}}, + {.input = {"r75, out of the Oreburgh Gate", test_exit_gate}, .expectation = {}}, + {.input = {"r81, out of the Ravaged Path", test_exit_ravaged_path}, .expectation = {}}, + {.input = {"01.05, a tap step begun through the Gate's mouth, its banner up (lab-B, 2026-11-08)", [](Logger& logger){ + return test_tap_through_already(logger, true); + }}, .expectation = {}}, + {.input = {"01.05, a tap step begun through the Gate's mouth, its banner gone (lab-B, 2026-11-08)", [](Logger& logger){ + return test_tap_through_already(logger, false); + }}, .expectation = {}}, + { + .input = {"01.03, a dark frame 1.8 s down the mine's entrance hall is not its mouth (lab-B, 2026-11-08)", [](Logger& logger){ + SimExecutor executor(logger, {.fade = {}, .banner = {}, .dark = 1}); + run_rows_on(executor, logger, {.from = "01.03", .to = "01.03"}); + const SimRun& run = executor.result(); + return run.missed_step == "01.03 into_the_coal_room" && run.error.empty() ? UnitTestResult(true) + : UnitTestResult(std::format("dark in '{}', failed in '{}': {}", run.missed_step, run.failed_step, run.error)); + }}, + .expectation = {}, + }, + { + .input = {"01.03, the Center's fade unseen, the heal goes on from the counter (lab-B, 2026-11-08)", test_heal_fade_unseen}, + .expectation = {}, + }, + { + .input = {"00.04b, the walk to the nurse waits out the Center's fade-in (lab-B, 2026-11-10)", [](Logger& logger){ + return run_rows(logger, {.from = "00.04b", .to = "00.04b"}); + }}, + .expectation = {}, + }, + { + .input = {"01.03, counted 19 taps south leaves player in hall", [](Logger& logger){ + return test_story_sim_step_failure(logger, "01.03", old_mine_hall_19("into_the_coal_room", Direction::SOUTH), "01.03 south_to_the_rock", "warp instead of a stop."); + }}, + .expectation = {}, + }, + { + .input = {"01.03, counted 19 taps north leaves player in hall", [](Logger& logger){ + return test_story_sim_step_failure(logger, "01.03", old_mine_hall_19("out_of_the_mine", Direction::NORTH), "01.03 north_to_the_centers_wall", "map_mismatch"); + }}, + .expectation = {}, + }, + { + .input = {"01.03, cut corner through coal room crate at col 29", [](Logger& logger){ + return test_story_sim_step_failure(logger, "01.03", old_coal_room_crate_cut(), "01.03 to_roarks_corner", "short_leg: south 2 moved 1"); + }}, + .expectation = {}, + }, +}; + +void add_tests_AutoStory_StorySim(UnitTestDatabase& database){ + for (const auto& item : AUTO_STORY_STORY_SIM_CASES){ + database.add(item); + } + add_tests_AutoStoryResources(database); + add_tests_AutoStory_LegTrace(database); +} + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h new file mode 100644 index 0000000000..bc1ed57d3a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySim_Tests.h @@ -0,0 +1,28 @@ +/* BDSP AutoStory Story Sim Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StorySim_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StorySim_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// The story table's rows run by the program's own walking steps +// (StoryWalkSteps) on the grid simulation: each walk must end where the +// table says the player is. +void add_tests_AutoStory_StorySim(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index 8991e40511..0470926be7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" @@ -31,8 +32,10 @@ #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WalkRules.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_WallRecovery.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" #include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_StoryLanguage.h" #include "PokemonBDSP_AutoStory_StorySimulation_Tests.h" @@ -74,11 +77,13 @@ bool contains(const std::vector& tiles, const TilePos& pos){ return std::find(tiles.begin(), tiles.end(), pos) != tiles.end(); } -// Where a step ends, or why it does not plan. +// Where a step ends, or why it does not plan. A "measured" step ends on +// one of `at`'s tiles and the program knows which (`measured`). struct Walked{ std::optional at; std::string error; std::string plan; + bool measured = false; std::vector golden = {}; }; @@ -107,6 +112,23 @@ std::string detour_error(const StoryWorld& world, const std::vector& st } +// The golden test's lines for one planned ROUTE: a header, then each leg +// with the tiles it may end on. +void add_golden_lines( + const StoryWorld& world, const Pose& from, const Pose& goal, const StoryStep& step, + const std::vector& plan, std::vector& golden +){ + golden.push_back(std::format("{} costs={} from{} to{}", step.name, step.action.empty() ? "default" : step.action, + describe(from.map, Pokemon::tiles_of(from)), describe(goal.map, Pokemon::tiles_of(goal)))); + for (const PlannedLeg& leg : plan){ + std::string line = std::format(" {} ->", to_string(leg.leg)); + for (const TilePos& pos : leg.after){ + line += std::format(" {}", describe(world, pos)); + } + golden.push_back(line); + } +} + // A ROUTE step from `from`, planned as StoryExecutor::walk_to() walks it. Walked plan_route(const Pose& from, const StoryStep& step){ const GridPose& target = story_arg(step.args, "target"); @@ -125,7 +147,14 @@ Walked plan_route(const Pose& from, const StoryStep& step){ targets.push_back(story_to_world(*world, goal.map, pos)); } const std::function at_goal = [&](const TilePos& pos){ return contains(targets, pos); }; - const auto plan = plan_robust_route(*world, start, at_goal, *costs); + // As walk_route() plans: from a wall when the start is one of a few + // tiles, then with the default costs if the step's find nothing. From + // 01.03's two start tiles a search over both found no plan within its + // budget once routes kept off the hiker's zone. + std::optional> plan = plan_recovered_route(*world, start, at_goal, *costs); + if (!plan){ + plan = plan_recovered_route(*world, start, at_goal, RobustPlanCosts()); + } if (!plan){ return {std::nullopt, step.name + ": no plan from" + describe(from.map, Pokemon::tiles_of(from)) + ".", ""}; } @@ -134,15 +163,7 @@ Walked plan_route(const Pose& from, const StoryStep& step){ for (const PlannedLeg& leg : *plan){ walked.plan += " " + to_string(leg.leg); } - walked.golden.push_back(std::format("{} costs={} from{} to{}", step.name, step.action.empty() ? "default" : step.action, - describe(from.map, Pokemon::tiles_of(from)), describe(goal.map, Pokemon::tiles_of(goal)))); - for (const PlannedLeg& leg : *plan){ - std::string line = std::format(" {} ->", to_string(leg.leg)); - for (const TilePos& pos : leg.after){ - line += std::format(" {}", describe(*world, pos)); - } - walked.golden.push_back(line); - } + add_golden_lines(*world, from, goal, step, *plan, walked.golden); const std::string detour = detour_error(*world, start, at_goal, *plan); if (!detour.empty()){ return {std::nullopt, step.name + ": " + detour, walked.plan}; @@ -158,6 +179,27 @@ Walked plan_route(const Pose& from, const StoryStep& step){ return walked; } +// A ROUTE step after a "measured" one: the program plans from the one +// tile it measured, so each tile of `from` must plan on its own. +Walked plan_route_from_each(const Pose& from, const StoryStep& step){ + Walked walked; + std::vector ends; + for (const TilePos& pos : Pokemon::tiles_of(from)){ + const Walked one = plan_route(Pokemon::tile_pose(from.map, {pos}, Pokemon::facing_of(from)), step); + if (!one.error.empty() || !one.at){ + return one; + } + walked.plan += (walked.plan.empty() ? "" : "; ") + one.plan; + for (const TilePos& end : Pokemon::tiles_of(*one.at)){ + if (!contains(ends, end)){ + ends.push_back(end); + } + } + walked.at = Pokemon::tile_pose(one.at->map, ends, Pokemon::facing_of(*one.at)); + } + return walked; +} + // `leg` of `step` from `pos`: adds where it ends to `next` (and a tile // short where the step allows it). Returns why it is blocked, or "". std::string walk_leg_from( @@ -185,6 +227,14 @@ Walked walk_legs(const Pose& from, const StoryStep& step){ if (step.action == "to_wall"){ return {std::nullopt, "", ""}; } + // A run until a map's banner ends where the banner reads. + if (step.action == "to_map"){ + return {step.pose_after ? std::optional(Pokemon::pose_of(*step.pose_after)) : std::nullopt, "", ""}; + } + if (step.action == "measured"){ + const std::optional ends = measured_ends(from, step); + return {ends, ends ? "" : step.name + ": no world holds " + from.map + ".", "", true}; + } const StoryWorld* world = story_plan_world(from.map, from.map); if (world == nullptr){ return {std::nullopt, step.name + ": no world holds " + from.map + ".", ""}; @@ -282,8 +332,12 @@ class FakeGame : public Pokemon::StoryStepExecutor{ return moved(plan_route(state.pose, step), "no_plan"); } Outcome legs(RunState& state, const StoryStep& step){ - return moved(walk_legs(state.pose, step), "blocked"); - } + Walked walked = walk_legs(state.pose, step); + // The fake player stands on the first tile a measured step may end on. + if (walked.measured && walked.at && !Pokemon::tiles_of(*walked.at).empty()){ + walked.at = Pokemon::tile_pose(walked.at->map, {Pokemon::tiles_of(*walked.at).front()}, Pokemon::facing_of(*walked.at)); + } + return moved(walked, "blocked"); } Outcome step(RunState& state, const StoryStep& step){ return moved(step_on(state.pose, step), "blocked"); } @@ -493,6 +547,7 @@ UnitTestResult test_gives_up_after_attempts(Logger&){ // the player, by the same planning and walking the fake run does. UnitTestResult test_poses_chain(Logger&){ std::optional at; + bool measured = false; std::string last; for (const StoryCheckpoint& row : story_checkpoints()){ if (row.start){ @@ -513,12 +568,15 @@ UnitTestResult test_poses_chain(Logger&){ if (!at && step.action != "to_wall" && step.action != "jubilife_stairs"){ return row.id + " " + step.name + ": walks from an unknown pose."; } - const Walked walked = !at ? Walked{} : step.kind == StoryStepKind::ROUTE ? plan_route(*at, step) + const bool known = std::exchange(measured, false); + const Walked walked = !at ? Walked{} : step.kind == StoryStepKind::ROUTE + ? (known ? plan_route_from_each(*at, step) : plan_route(*at, step)) : step.kind == StoryStepKind::LEGS ? walk_legs(*at, step) : step_on(*at, step); if (!walked.error.empty()){ return row.id + " " + walked.error; } at = walked.at; + measured = walked.measured; }else if (step.kind == StoryStepKind::GAME || step.kind == StoryStepKind::SHOP || step.kind == StoryStepKind::MASH){ // A scene or an event: where it ends is the table's to say. at.reset(); @@ -636,7 +694,32 @@ class Test_StorySimulation : public UnitTest{ } // namespace +// Execute the authored mine resource through the actual table and shared engine. +UnitTestResult test_authored_mine(Logger&){ + Simulation sim; + const auto report = sim.run({.from = "01.03", .to = "01.03"}); + if (!report.completed || sim.begun() != std::vector{"01.03"} + || sim.count("save in 01.03") != 1 || sim.count("card for 01.03: Oreburgh City") != 1 + || sim.count("01.03/heal_oreburgh") != 1 || sim.count("01.03/roark") != 1){ + return "Expected the JSON-authored mine checkpoint to save once, talk to Roark, heal and finish:" + joined(sim.trace) + joined(sim.lines); + } + return true; +} + +UnitTestResult test_authored_mine_stops(Logger&){ + Simulation sim; + sim.game.failures["01.03/out_of_the_mine"] = {.failure = "unconfirmed_transition", .times = 3}; + const auto report = sim.run({.from = "01.03", .to = "01.03"}); + if (report.completed || report.reloads != 2 || report.failed_event != "out_of_the_mine" + || sim.count("01.03/heal_oreburgh") != 0){ + return "Expected failed mine transition to exhaust retries before healing:" + joined(sim.trace) + joined(sim.lines); + } + return true; +} + const AutoStoryStorySimulationCase AUTO_STORY_STORY_SIMULATION_CASES[] = { + {.input = {.name = "01.03 authored mine executes through the real table", .body = test_authored_mine}, .expectation = {}}, + {.input = {.name = "01.03 unconfirmed mine exit stops before healing", .body = test_authored_mine_stops}, .expectation = {}}, { .input = {"00.00 to Floaroma, in order, each row saved first, English and Japanese", test_whole_table}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp new file mode 100644 index 0000000000..c3bee443bd --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.cpp @@ -0,0 +1,357 @@ +/* BDSP AutoStory Grid Simulation - Wild Battles on Wall Legs Tests + * + * From: https://github.com/PokemonAutomation/ + * + * A wild battle on a leg to a wall, walked by the route walker on the grid + * simulation: however the escape ends the battle, the leg must still end at + * the wall with the battle counted. And a run into a scene (00.03's into + * Sandgem), a wild battle on it or not: the scene stops the run wherever it + * starts, and with no scene the run stops at its cap and the step fails. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/AutoStory/Pokemon_TilePose.h" +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_Maps.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_PlanCosts.h" +#include "PokemonBDSP/Programs/AutoStory/Data/PokemonBDSP_AutoStory_RoutePlanner.h" +#include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_PlannedRoute.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryPlaces.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryStepIO.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h" +#include "PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryWalkSteps.h" +#include "PokemonBDSP_AutoStory_GridSim.h" +#include "PokemonBDSP_AutoStory_StorySim.h" +#include "PokemonBDSP_AutoStory_WallBattleSim_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +using namespace detail; + + +namespace{ + +using Pokemon::Direction; +using Pokemon::GridPose; +using Pokemon::story_arg; +using Pokemon::StoryStep; +using Pokemon::TilePos; + + +struct WallBattleInput{ + std::string name; + SimWildBattle battle; +}; +struct WallBattleExpectation{ + // How the simulation notes the battle ended. + std::string ended; +}; +struct WallBattleCase{ + WallBattleInput input; + WallBattleExpectation expectation; +}; + +StoryWorld make_world(const std::vector& rows){ + Pokemon::MapData map; + map.name = "Test"; + map.tiles = Pokemon::Grid{(int)rows[0].size(), (int)rows.size(), {}}; + for (const std::string& row : rows){ + for (char glyph : row){ + map.tiles.cells.push_back(*Pokemon::tile_from_glyph(glyph)); + } + } + StoryWorld world; + world.add("Test", map, {0, 0}); + return world; +} + +// The corridor's one leg, east to its end wall, walked with `battle` on +// the way; the walk's notes, or why it did not end at the wall. +struct WallBattleWalk{ + std::vector notes; + std::string error; +}; +WallBattleWalk walk_wall_battle(const std::string& leg, const SimWildBattle& battle){ + StoryWorld world = make_world({ + "########################", + "#......................#", + "########################", + }); + const TilePos start{1, 1}; + const TilePos target{22, 1}; + GridSim sim({.world = &world}, start, Direction::EAST, true); + WallBattleWalk walk; + GridSimRouteIO sim_io(sim, walk.notes, {}, {{.label = leg, .direction = Direction::EAST, .battle = battle}}); + RouteTrainers trainers{{}, [](const std::string&){}}; + try{ + walk_route(sim_io, world, {start}, trainers, { + .goal = [&](const TilePos& pos){ return pos == target; }, + .label = "wall leg battle", + .avoid = {}, + .costs = *story_route_costs("town"), + .speed = MoveSpeed::RUN, + }); + }catch (const GridSimFailure& f){ + walk.error = "failed: " + f.message; + return walk; + } + if (nearest_tile(sim.player().pos) != target){ + walk.error = "ended at " + to_string(sim.player().pos) + ", not at the wall."; + } + return walk; +} + +class Test_WallBattleSim : public UnitTest{ +public: + explicit Test_WallBattleSim(WallBattleCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Grid sim: a wild battle on a wall leg: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const std::string leg = "wall leg battle: " + to_string(TileLeg{.direction = Direction::EAST, .tiles = 21, .ends_at_wall = true, .held = false}); + const WallBattleWalk walk = walk_wall_battle(leg, m_case.input.battle); + if (!walk.error.empty()){ + return walk.error; + } + const std::string ended = std::format("[Sim] {}: wild battle {}.", leg, m_case.expectation.ended); + if (std::find(walk.notes.begin(), walk.notes.end(), ended) == walk.notes.end()){ + std::string notes; + for (const std::string& line : walk.notes){ + notes += "\n " + line; + } + return std::format("expected the note \"{}\"; the walk noted:{}", ended, notes); + } + return true; + } + +private: + WallBattleCase m_case; +}; + +const WallBattleCase WALL_BATTLE_SIM_CASES[] = { + {.input = {.name = "the first Run works", .battle = {.run_refusals = 0}}, .expectation = {.ended = "run from"}}, + {.input = {.name = "two refusals, then the third Run works", .battle = {.run_refusals = 2}}, .expectation = {.ended = "run from"}}, + // console B, BDSP 01.03 run 2026-11-07: Onix's Bind in Oreburgh Mine + // refused nine Runs in 60 s and escape_wild_battle() gave up. + {.input = {.name = "bound: every Run refused", .battle = {.run_refusals = 20}}, .expectation = {.ended = "fought to its end"}}, +}; + + +// The route walker's IO alone, for a ROUTE step: anything else the step +// asks of the console fails the walk. +class RouteOnlyStepIO : public StoryStepIO{ +public: + explicit RouteOnlyStepIO(GridSimRouteIO& route) + : m_route(route) + {} + + virtual RouteIO& route() override{ + return m_route; + } + virtual void fight(const std::string& trainer) override{ + unsupported("a fight with " + trainer); + } + virtual void walk_until_stopped(Direction, size_t, const std::string& label) override{ + unsupported(label + ": a walk until stopped"); + } + virtual bool run_until_map(Direction, Milliseconds, const std::string& map, const std::string&) override{ + unsupported("a run onto " + map); + return false; + } + virtual WarpSeen run_into_door(Direction, bool, Milliseconds, Milliseconds, const std::string&) override{ + unsupported("a run into a door"); + return {}; + } + virtual std::optional tap_to_banner(Direction, const std::string& map, size_t) override{ + unsupported("taps to " + map + "'s banner"); + return std::nullopt; + } + virtual void settle(Button, const std::string& label, bool, const std::string&) override{ + unsupported(label + "'s settle"); + } + +private: + void unsupported(const std::string& what){ + m_route.note(what + " is not simulated here.", RouteNote::FAILURE); + } + + GridSimRouteIO& m_route; +}; + +// Dawn's scene on `world`, in its tiles: the coord events of Sandgem that +// 00.03 arms (its trigger column (4, 10..15), decomp). +std::vector dawns_triggers(const StoryWorld& world){ + std::vector out; + for (const RowTrigger& armed : story_triggers()){ + if (armed.row != "00.03" || armed.map != "SandgemTown"){ + continue; + } + SimTrigger trigger{.name = armed.trigger.name, .tiles = {}}; + for (const TilePos& pos : armed.trigger.tiles){ + trigger.tiles.push_back(story_to_world(world, armed.map, pos)); + } + out.push_back(std::move(trigger)); + } + if (out.empty()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "00.03 arms no coord event in Sandgem."); + } + return out; +} + +// The table's 00.03 into_dawns_scene. +const StoryStep& into_dawns_scene(){ + for (const StoryCheckpoint& checkpoint : story_checkpoints()){ + for (const StoryStep& step : checkpoint.steps){ + if (checkpoint.id == "00.03" && step.name == "into_dawns_scene" && + step.args.contains("target") && + step.args.contains("legs") && + story_arg>(step.args, "legs").size() == 1){ + return step; + } + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "00.03 has no ROUTE into_dawns_scene with a run."); +} + +struct SceneRunInput{ + std::string name; + // Dawn's scene is armed. + bool dawn = false; + // A wild battle interrupts the run. + bool battle = false; +}; +struct SceneRunExpectation{ + // The step ends in Dawn's scene; else it fails as "no_dialogue". + bool in_scene = false; +}; +struct SceneRunCase{ + SceneRunInput input; + SceneRunExpectation expectation; +}; + +// How 00.03's into_dawns_scene went: its outcome, where it left the player, +// how many tiles east of the route's end, whether a dialogue is open, +// whether a wild battle was run from, and the failure the program would +// have stopped on instead of failing the step. +struct SceneRun{ + Pokemon::Outcome outcome; + TilePos end; + int run_tiles = 0; + bool dialog = false; + bool ran_from_battle = false; + std::string program_failure; +}; +// 00.03's into_dawns_scene from the house's doorstep, where the step before +// it leaves us, at the run's pace (Mom gave the shoes in 00.03): the route +// to Route 201's east edge, then the run east into Sandgem. +SceneRun run_into_dawns_scene(const SceneRunInput& input){ + const StoryStep& step = into_dawns_scene(); + const Pokemon::Pose start = Pokemon::tile_pose("TwinleafTown", {map_point("TwinleafTown", "house_doorstep")}, Direction::SOUTH); + const GridPose& target = story_arg(step.args, "target"); + const StoryWorld& world = *story_plan_world(start.map, target.map); + SimWorld sim_world{.world = &world, .trainers = story_trainers(world), .can_run = true}; + if (input.dawn){ + sim_world.triggers = dawns_triggers(world); + } + GridSim sim(sim_world, story_to_world(world, start.map, Pokemon::tiles_of(start).front()), Direction::SOUTH, true); + std::vector notes; + std::vector encounters; + if (input.battle){ + encounters.push_back({.label = "into dawns scene", .direction = Direction::EAST, .battle = {}}); + } + GridSimRouteIO route_io(sim, notes, {}, std::move(encounters)); + RouteOnlyStepIO io(route_io); + StoryWalkSteps walk(io); + // A row after the shoes' row runs, as 00.03 does once Mom gave them. + walk.begin_attempt("00.04"); + Pokemon::RunState state{.pose = start, .flags = {}}; + SceneRun out; + try{ + out.outcome = walk.route(state, step); + }catch (const GridSimFailure& e){ + out.program_failure = e.message; + } + out.end = nearest_tile(sim.player().pos); + out.run_tiles = out.end.x - story_to_world(world, target.map, target.tiles.front()).x; + out.dialog = sim.player().dialog; + out.ran_from_battle = std::find(notes.begin(), notes.end(), "[Sim] into dawns scene: wild battle run from.") != notes.end(); + return out; +} + +// Why `run` is not what `test_case` expects, or "". +std::string scene_run_error(const SceneRunCase& test_case, const SceneRun& run){ + const StoryWorld& world = *story_plan_world("Route201", "SandgemTown"); + const std::optional sandgem = story_to_local(world, "SandgemTown", run.end); + const int cap = story_arg>(into_dawns_scene().args, "legs").front().tiles; + // The cap is timed at the slowest run; the sim runs faster, this far. + const int most = (int)((route_limit_for_tiles(MoveSpeed::RUN, cap) - ROUTE_START_DELAY) / route_ms_per_tile(Direction::EAST, MoveSpeed::RUN)); + if (!run.program_failure.empty()){ + return "the program failed instead of the step: " + run.program_failure; + } + if (test_case.input.battle != run.ran_from_battle){ + return std::format("expected {} wild battle on the run.", test_case.input.battle ? "a" : "no"); + } + if (run.run_tiles < 0 || run.run_tiles > most){ + return std::format("the run went {} tiles past the route's end, outside its cap of {} ({} at the sim's pace).", run.run_tiles, cap, most); + } + if (test_case.expectation.in_scene && (!run.outcome.succeeded() || !run.dialog || !sandgem || sandgem->x != 4)){ + return std::format("\"{}\", ended at {}, not in Dawn's scene on Sandgem's column 4.", Pokemon::to_string(run.outcome), describe(world, run.end)); + } + if (!test_case.expectation.in_scene && run.outcome.failure != "no_dialogue"){ + return std::format("expected the step to fail as no_dialogue; \"{}\".", Pokemon::to_string(run.outcome)); + } + return ""; +} + +class Test_SceneRunSim : public UnitTest{ +public: + explicit Test_SceneRunSim(SceneRunCase test_case) + : UnitTest("PokemonBDSP::AutoStory - Grid sim: 00.03's run into Sandgem: " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + const SceneRun run = run_into_dawns_scene(m_case.input); + logger.log(std::format("{}: \"{}\", ended {} tiles on.", m_case.input.name, Pokemon::to_string(run.outcome), run.run_tiles)); + const std::string error = scene_run_error(m_case, run); + return error.empty() ? UnitTestResult(true) : UnitTestResult(error); + } + +private: + SceneRunCase m_case; +}; + +const SceneRunCase SCENE_RUN_SIM_CASES[] = { + {.input = {.name = "Dawn's scene stops it mid-run", .dawn = true, .battle = false}, .expectation = {.in_scene = true}}, + {.input = {.name = "Dawn's scene stops it after a wild battle on the run", .dawn = true, .battle = true}, .expectation = {.in_scene = true}}, + {.input = {.name = "no scene: the step fails at the cap", .dawn = false, .battle = false}, .expectation = {.in_scene = false}}, + {.input = {.name = "a wild battle and no scene: the step fails at the cap", .dawn = false, .battle = true}, .expectation = {.in_scene = false}}, +}; + +} // namespace + + +void add_tests_AutoStory_WallBattleSim(UnitTestDatabase& database){ + for (const WallBattleCase& item : WALL_BATTLE_SIM_CASES){ + database.add(item); + } + for (const SceneRunCase& item : SCENE_RUN_SIM_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h new file mode 100644 index 0000000000..864d05a021 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/PokemonBDSP_AutoStory_WallBattleSim_Tests.h @@ -0,0 +1,29 @@ +/* BDSP AutoStory Grid Simulation - Wild Battles on Wall Legs Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_WallBattleSim_Tests_H +#define PokemonAutomation_PokemonBDSP_AutoStory_WallBattleSim_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// A wild battle on a leg to a wall, on the grid simulation: run from, or +// fought when the game refuses the escape, the leg still ends at the wall. +// And 00.03's run into Sandgem: Dawn's scene stops it, a wild battle on the +// way or not; with no scene, the step fails at the run's cap. +void add_tests_AutoStory_WallBattleSim(UnitTestDatabase& database); + + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/leg_trace_00.04.golden.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/leg_trace_00.04.golden.json new file mode 100644 index 0000000000..768074a022 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Simulation/leg_trace_00.04.golden.json @@ -0,0 +1,39 @@ +{ + "about": "Leg records of BDSP AutoStory row 00.04 run on the grid simulation (Simulation/PokemonBDSP_AutoStory_LegTrace_Tests.cpp). Rewrite with PA_UPDATE_LEG_TRACE=1.", + "legs": [ + {"checkpoint":"00.04","chunks":3,"dir":"east","end":[["Sandgem Town",29,11],["Sandgem Town",29,12]],"end_kind":"wall","event":"onto_the_path","interrupts":[],"known":"wall","leg":1,"ms":1350,"planned_end":[["Sandgem Town",29,11],["Sandgem Town",29,12]],"tiles":3}, + {"checkpoint":"00.04","chunks":0,"dir":"north","end":[["Sandgem Town",29,11]],"end_kind":"wall","event":"onto_the_path","interrupts":[],"known":"wall","leg":2,"ms":1050,"planned_end":[["Sandgem Town",29,11]],"tiles":1}, + {"checkpoint":"00.04","chunks":1,"dir":"south","end":[["Sandgem Town",29,12]],"end_kind":"open","event":"onto_the_path","interrupts":[],"known":"dead_reckoned","leg":3,"moved":1,"ms":800,"planned_end":[["Sandgem Town",29,12]],"tiles":1}, + {"checkpoint":"00.04","chunks":1,"dir":"north","end":[["Route 201",57,4],["Route 201",58,4],["Route 201",59,4],["Route 201",60,4],["Route 201",61,4],["Route 201",62,4],["Route 201",63,4]],"end_kind":"tile","event":"to_the_signs_row","interrupts":[],"known":"counted","leg":1,"moved":1,"ms":800,"planned_end":[["Route 201",57,4],["Route 201",58,4],["Route 201",59,4],["Route 201",60,4],["Route 201",61,4],["Route 201",62,4],["Route 201",63,4]],"tiles":1}, + {"checkpoint":"00.04","chunks":4,"dir":"west","end":[["Route 201",56,4]],"end_kind":"wall","event":"to_ledge_column","interrupts":[],"known":"wall","leg":1,"ms":1450,"planned_end":[["Route 201",56,4]],"tiles":7}, + {"checkpoint":"00.04","chunks":1,"dir":"south","end":[["Route 201",56,5]],"end_kind":"open","event":"to_ledge_column","interrupts":[],"known":"dead_reckoned","leg":2,"moved":1,"ms":800,"planned_end":[["Route 201",56,5]],"tiles":1}, + {"checkpoint":"00.04","chunks":1,"dir":"west","end":[["Route 201",55,5]],"end_kind":"open","event":"to_ledge_column","interrupts":[],"known":"dead_reckoned","leg":3,"moved":1,"ms":800,"planned_end":[["Route 201",55,5]],"tiles":1}, + {"checkpoint":"00.04","chunks":8,"dir":"south","end":[["Route 201",55,13]],"end_kind":"tile","event":"over_the_ledge","interrupts":[],"known":"counted","leg":1,"moved":8,"ms":6400,"planned_end":[["Route 201",55,13]],"tiles":8}, + {"checkpoint":"00.04","chunks":16,"dir":"west","end":[["Route 201",39,14]],"end_kind":"open","event":"along_route_201_road","interrupts":[],"known":"dead_reckoned","leg":1,"moved":16,"ms":12800,"planned_end":[["Route 201",39,14]],"tiles":16}, + {"checkpoint":"00.04","chunks":3,"dir":"north","end":[["Route 201",39,11]],"end_kind":"open","event":"along_route_201_road","interrupts":[],"known":"dead_reckoned","leg":2,"moved":3,"ms":2400,"planned_end":[["Route 201",39,11]],"tiles":3}, + {"checkpoint":"00.04","chunks":24,"dir":"west","end":[["Route 201",15,11]],"end_kind":"open","event":"along_route_201_road","interrupts":[],"known":"dead_reckoned","leg":3,"moved":24,"ms":19200,"planned_end":[["Route 201",15,11]],"tiles":24}, + {"checkpoint":"00.04","chunks":2,"dir":"south","end":[["Route 201",15,14]],"end_kind":"open","event":"along_route_201_road","interrupts":[],"known":"dead_reckoned","leg":4,"moved":2,"ms":1600,"planned_end":[["Route 201",15,14]],"tiles":2}, + {"checkpoint":"00.04","chunks":37,"dir":"south","end":[["Twinleaf Town",15,26]],"end_kind":"wall","event":"into_twinleaf","interrupts":[],"known":"wall","leg":1,"ms":6600,"planned_end":[["Twinleaf Town",15,26]],"tiles":37}, + {"checkpoint":"00.04","chunks":4,"dir":"north","end":[["Twinleaf Town",15,22]],"end_kind":"open","event":"into_twinleaf","interrupts":[],"known":"dead_reckoned","leg":2,"moved":4,"ms":3200,"planned_end":[["Twinleaf Town",15,22]],"tiles":4}, + {"checkpoint":"00.04","chunks":5,"dir":"east","end":[["Twinleaf Town",20,22]],"end_kind":"open","event":"to_moms_doorstep","interrupts":[],"known":"dead_reckoned","leg":1,"moved":5,"ms":4000,"planned_end":[["Twinleaf Town",20,22]],"tiles":5}, + {"checkpoint":"00.04","chunks":1,"dir":"north","end":[["PlayerHouse1F",6,8]],"end_kind":"open","event":"beside_mom","interrupts":[],"known":"dead_reckoned","leg":1,"moved":1,"ms":800,"planned_end":[["PlayerHouse1F",6,8]],"tiles":1}, + {"checkpoint":"00.04","chunks":0,"dir":"north","end":[],"end_kind":"wall","event":"into_the_east_corner","interrupts":[],"known":"wall","leg":1,"ms":0,"planned_end":[],"tiles":4}, + {"checkpoint":"00.04","chunks":0,"dir":"east","end":[],"end_kind":"wall","event":"into_the_east_corner","interrupts":[],"known":"wall","leg":2,"ms":0,"planned_end":[],"tiles":6}, + {"checkpoint":"00.04","chunks":0,"dir":"south","end":[],"end_kind":"wall","event":"into_the_east_corner","interrupts":[],"known":"wall","leg":3,"ms":0,"planned_end":[],"tiles":4}, + {"checkpoint":"00.04","chunks":1,"dir":"west","end":[["PlayerHouse1F",10,8]],"end_kind":"open","event":"into_moms_call","interrupts":[],"known":"dead_reckoned","leg":1,"moved":1,"ms":800,"planned_end":[["PlayerHouse1F",10,8]],"tiles":1}, + {"checkpoint":"00.04","chunks":1,"dir":"south","end":[["PlayerHouse1F",10,9]],"end_kind":"open","event":"into_moms_call","interrupts":[],"known":"dead_reckoned","leg":2,"moved":1,"ms":800,"planned_end":[["PlayerHouse1F",10,9]],"tiles":1}, + {"checkpoint":"00.04","chunks":4,"dir":"west","end":[],"end_kind":"wall","event":"into_moms_call","interrupts":["scene"],"known":"dialogue","leg":3,"ms":650,"note":"scene","planned_end":[["PlayerHouse1F",6,9]],"tiles":4}, + {"checkpoint":"00.04","chunks":0,"dir":"west","end":[],"end_kind":"wall","event":"to_twinleafs_west_wall","interrupts":[],"known":"wall","leg":1,"ms":0,"planned_end":[],"tiles":16}, + {"checkpoint":"00.04","chunks":18,"dir":"north","end":[["Twinleaf Town",6,4]],"end_kind":"wall","event":"short_of_the_catch_tutorial","interrupts":[],"known":"wall","leg":1,"ms":3750,"planned_end":[["Twinleaf Town",6,4]],"tiles":19}, + {"checkpoint":"00.04","chunks":8,"dir":"east","end":[["Twinleaf Town",14,4]],"end_kind":"open","event":"short_of_the_catch_tutorial","interrupts":[],"known":"dead_reckoned","leg":2,"moved":8,"ms":6400,"planned_end":[["Twinleaf Town",14,4]],"tiles":8}, + {"checkpoint":"00.04","chunks":16,"dir":"north","end":[["Route 201",14,13]],"end_kind":"wall","event":"short_of_the_catch_tutorial","interrupts":[],"known":"wall","leg":3,"ms":3450,"planned_end":[["Route 201",14,13]],"tiles":16}, + {"checkpoint":"00.04","chunks":43,"dir":"east","end":[["Route 201",57,13]],"end_kind":"wall","event":"short_of_the_catch_tutorial","interrupts":[],"known":"wall","leg":4,"ms":5350,"planned_end":[["Route 201",57,13]],"tiles":43}, + {"checkpoint":"00.04","chunks":7,"dir":"west","end":[["Route 201",50,13]],"end_kind":"open","event":"short_of_the_catch_tutorial","interrupts":[],"known":"dead_reckoned","leg":5,"moved":7,"ms":5600,"planned_end":[["Route 201",50,13]],"tiles":7}, + {"checkpoint":"00.04","chunks":7,"dir":"north","end":[["Route 201",50,6]],"end_kind":"open","event":"short_of_the_catch_tutorial","interrupts":[],"known":"dead_reckoned","leg":6,"moved":7,"ms":5600,"planned_end":[["Route 201",50,6]],"tiles":7}, + {"checkpoint":"00.04","chunks":43,"dir":"east","end":[["Sandgem Town",29,13]],"end_kind":"wall","event":"short_of_the_catch_tutorial","interrupts":[],"known":"wall","leg":7,"ms":5350,"planned_end":[["Sandgem Town",29,13]],"tiles":43}, + {"checkpoint":"00.04","chunks":5,"dir":"west","end":[["Sandgem Town",24,13]],"end_kind":"open","event":"short_of_the_catch_tutorial","interrupts":[],"known":"dead_reckoned","leg":8,"moved":5,"ms":4000,"planned_end":[["Sandgem Town",24,13]],"tiles":5}, + {"checkpoint":"00.04","chunks":21,"dir":"north","end":[["Route 202",25,24]],"end_kind":"wall","event":"short_of_the_catch_tutorial","interrupts":[],"known":"wall","leg":9,"ms":4200,"planned_end":[["Route 202",25,24]],"tiles":21}, + {"checkpoint":"00.04","chunks":3,"dir":"west","end":[["Route 202",22,24]],"end_kind":"wall","event":"short_of_the_catch_tutorial","interrupts":[],"known":"wall","leg":10,"ms":1350,"planned_end":[["Route 202",22,24]],"tiles":3}, + {"checkpoint":"00.04","chunks":3,"dir":"south","end":[["Route 202",22,27]],"end_kind":"open","event":"short_of_the_catch_tutorial","interrupts":[],"known":"dead_reckoned","leg":11,"moved":3,"ms":2400,"planned_end":[["Route 202",22,27]],"tiles":3} + ] +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/README.md b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/README.md new file mode 100644 index 0000000000..cf77edffe0 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/README.md @@ -0,0 +1,16 @@ +# BDSP authored checkpoint pilot + +`bdsp-mine-01.03.plan.json` is the authoritative definition of the mine/Roark checkpoint. `oreburgh_mine_to_roark()` loads it into the existing story table. Edit this file here when changing the route; PokemonSimulation consumes an explicitly pinned Arduino revision for independent analysis. Its checked-in pilot plan is a frozen regression snapshot, not a second authoring source. + +The shared `pokesim-authored-checkpoint/1` envelope contains `checkpoint.id`, `title`, `start`, `events` in that order. BDSP validates `execution.on_failure` and `execution.saves_in`. The common envelope and resource lookup live in `Pokemon/AutoStory/Pokemon_AuthoredCheckpointJson.*`. Bookkeeping defaults and game executors are unchanged. + +## Validation and iteration + +1. Native registered tests run the actual JSON-backed table through the existing engine/fake game, including retry exhaustion before healing. Data tests check parsing, table wiring, event IDs/order, policy/card values, and map-derived Center/Roark anchors. The table-wiring comparison is not an independent check against the removed C++ authoring list. +2. Linux CI pins a simulator revision reachable from its main branch and replays **this checkout's JSON** against nine independent scenario expectations. There is no byte-equality requirement against a second plan. A route change may still require revising a scenario expectation when its expected behavior intentionally changes; such failures are meaningful regression feedback, not a requirement to mirror JSON or repin simulator code for every edit. + +A lab route edit therefore touches the Arduino plan and applicable tests/evidence. The next build re-embeds it automatically. CMake rejects malformed JSON syntax before launching the app; native tests perform full reader/policy validation. Run tests before deploying: CMake's syntax preflight alone cannot validate all semantics. The shared formatter writes authored JSON; Git normalization rules are unchanged. Whitespace and line-ending changes do not affect replay results. C++ retains the repository CRLF convention. + +Coordinates remain literal data tied to the pinned map. The map-anchor test catches drift in the Center exit and Roark approach; it does not validate every tile or replace map review. See [the checkpoint evidence](bdsp-mine-01.03.md) for the warp columns, counted hall movement, wall choices and unresolved observations. + +The native fake uses declared scene/door fallbacks and is not a detector/timing oracle. Python uses scripted transition/dialogue/scene/heal evidence and NPC-clearance windows. Missing warp links, native planner-cost parity, queued movement and live recovery remain gaps. Python's diagnostic policy is stop/no-save; the native program retains its start-save/reload policy. No map correction, console, profile or save is part of this authoring migration. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.01.plan.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.01.plan.json index bca1f4918c..e6fd8afa09 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.01.plan.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.01.plan.json @@ -38,20 +38,20 @@ { "args": { "fight_wild": false, - "target": { - "facing": "east", - "map": "PlayerHouse2F", - "tiles": [ - [ - 8, - 4 - ] - ] - } + "legs": [ + { + "direction": "north", + "tiles": 1 + }, + { + "direction": "east", + "tiles": 1 + } + ] }, "id": "onto_the_flute_tile", - "kind": "route", - "why": "onto the top of the stairs' mat (8, 4), past the flute's tile" + "kind": "legs", + "why": "up onto (7, 4), then east onto the top of the stairs' mat (8, 4)" }, { "args": { @@ -110,29 +110,6 @@ "kind": "route", "why": "past Mom at (7, 8) to above the door" }, - { - "args": { - "direction": "south" - }, - "id": "mom_warning", - "kind": "step", - "why": "the door's tile (6, 10): Mom's warning (coord event, VAR_PLAYER_HOUSE_STATE 1)" - }, - { - "declared_after": { - "facing": "south", - "map": "PlayerHouse1F", - "tiles": [ - [ - 6, - 10 - ] - ] - }, - "id": "mom_warns_us", - "kind": "scene", - "why": "\"don't go into the tall grass\"" - }, { "args": { "direction": "south" @@ -149,7 +126,7 @@ }, "id": "out_of_the_house", "kind": "step", - "why": "out of the door" + "why": "onto the door's tile (6, 10), and out" }, { "args": { @@ -209,24 +186,6 @@ "kind": "scene", "why": "his second lines (Butters waited for two)" }, - { - "args": { - "fight_wild": false, - "target": { - "facing": "north", - "map": "TwinleafTown", - "tiles": [ - [ - 9, - 12 - ] - ] - } - }, - "id": "back_onto_barrys_doorstep", - "kind": "route", - "why": "back to his doorstep (9, 12); its trigger is spent" - }, { "args": { "direction": "north" @@ -243,7 +202,7 @@ }, "id": "into_barrys_house", "kind": "step", - "why": "his door" + "why": "past (9, 12) into his door" }, { "args": { @@ -313,20 +272,91 @@ { "args": { "fight_wild": false, - "target": { - "facing": "west", - "map": "RivalHouse2F", - "tiles": [ - [ - 3, - 4 - ] + "legs": [ + { + "direction": "east", + "tiles": 1 + } + ] + }, + "declared_after": { + "facing": "north", + "map": "RivalHouse2F", + "tiles": [ + [ + 3, + 4 + ], + [ + 4, + 4 + ], + [ + 5, + 4 + ], + [ + 3, + 5 + ], + [ + 4, + 5 + ], + [ + 5, + 5 + ], + [ + 3, + 6 + ], + [ + 4, + 6 + ], + [ + 5, + 6 ] - } + ] }, - "id": "above_barrys_stairs", - "kind": "route", - "why": "back to the top of the stairs' mat" + "id": "off_barrys_west_wall", + "kind": "legs", + "why": "a tap east, clear of the west wall" + }, + { + "action": "to_wall", + "args": { + "fight_wild": false, + "legs": [ + { + "direction": "north", + "tiles": 3 + } + ] + }, + "declared_after": { + "facing": "north", + "map": "RivalHouse2F", + "tiles": [ + [ + 3, + 4 + ], + [ + 4, + 4 + ], + [ + 5, + 4 + ] + ] + }, + "id": "up_to_barrys_back_wall", + "kind": "legs", + "why": "north to the room's back wall" }, { "args": { @@ -343,7 +373,7 @@ }, "id": "down_barrys_stairs", "kind": "step", - "why": "onto the stairs" + "why": "west along row 4 onto the stairs" }, { "args": { @@ -384,20 +414,30 @@ { "args": { "fight_wild": false, - "target": { - "facing": "north", - "map": "Route201", - "tiles": [ - [ - 15, - 19 - ] + "legs": [ + { + "direction": "east", + "tiles": 6 + }, + { + "direction": "north", + "tiles": 18 + } + ] + }, + "declared_after": { + "facing": "north", + "map": "Route201", + "tiles": [ + [ + 15, + 19 ] - } + ] }, "id": "below_barrys_warning", - "kind": "route", - "why": "below the trigger, up Twinleaf's exit to Route 201 (15, 19)" + "kind": "legs", + "why": "along row 12, then up Twinleaf's exit to Route 201 (15, 19)" }, { "args": { @@ -424,20 +464,20 @@ { "args": { "fight_wild": false, - "target": { - "facing": "west", - "map": "Route201", - "tiles": [ - [ - 12, - 17 - ] - ] - } + "legs": [ + { + "direction": "west", + "tiles": 1 + }, + { + "direction": "north", + "tiles": 2 + } + ] }, "id": "away_from_barry", - "kind": "route", - "why": "to (12, 17): row 18 west of the path is trees, the dirt goes on along row 17" + "kind": "legs", + "why": "to (14, 16): row 18 west of the path is trees (r16) and (13, 17) is the 201 sign (probe-r201-sign), so clear both onto row 16" }, { "args": { diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.03.plan.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.03.plan.json index 4309d2658c..07f057f20a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.03.plan.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.03.plan.json @@ -1,41 +1,35 @@ -{ +{ "checkpoint": { "events": [ { + "action": "into_scene", "args": { "fight_wild": false, + "legs": [ + { + "direction": "east", + "tiles": 22 + } + ], "target": { - "facing": "east", - "map": "Route201", + "map": "VerityLakefront", "tiles": [ [ - 4, - 14 + 17, + 21 ] ] } }, - "id": "short_of_rowan", + "id": "into_rowans_scene", "kind": "route", - "why": "back east onto Route 201's lower level" - }, - { - "args": { - "direction": "east" - }, - "id": "rowans_stop", - "kind": "step", - "why": "the trigger (5, 14..16)" + "why": "south to the Lakefront's wall, then east onto Route 201 until Rowan's scene starts: 20 tiles, 22 at most" }, { "declared_after": { "facing": "east", "map": "PlayerHouse1F", "tiles": [ - [ - 5, - 8 - ], [ 6, 8 @@ -47,44 +41,15 @@ "why": "Rowan and Dawn come back; Barry, then home for the Running Shoes" }, { + "action": "or_legs", "args": { - "fight_wild": false, - "target": { - "facing": "west", - "map": "PlayerHouse1F", - "tiles": [ - [ - 4, - 8 - ] - ] - } - }, - "id": "by_the_counter", - "kind": "route", - "why": "west against the table's corner (3, 8)" - }, - { - "args": { - "fight_wild": false, - "target": { - "facing": "south", - "map": "PlayerHouse1F", - "tiles": [ - [ - 6, - 9 - ] - ] - } - }, - "id": "above_the_door_again", - "kind": "route", - "why": "to above the door" - }, - { - "args": { - "direction": "south" + "direction": "south", + "legs": [ + { + "direction": "east", + "tiles": 1 + } + ] }, "declared_after": { "facing": "south", @@ -98,11 +63,18 @@ }, "id": "out_of_the_house_again", "kind": "step", - "why": "onto the door's tile (6, 10), and out" + "why": "south onto the door's tile (6, 10), and out; from column 5, east onto the mat first" }, { + "action": "into_scene", "args": { "fight_wild": false, + "legs": [ + { + "direction": "east", + "tiles": 8 + } + ], "target": { "facing": "east", "map": "Route201", @@ -114,26 +86,12 @@ ] } }, - "id": "short_of_dawn", + "id": "into_dawns_scene", "kind": "route", - "why": "Twinleaf, then east along Route 201 to its east edge" - }, - { - "action": "to_dialogue", - "args": { - "fight_wild": false, - "legs": [ - { - "direction": "east", - "tiles": 8 - } - ] - }, - "id": "into_sandgem", - "kind": "legs", - "why": "east into Sandgem until Dawn's scene starts" + "why": "Twinleaf, then east along Route 201 to its edge and on into Sandgem until Dawn's scene starts" }, { + "action": "a", "declared_after": { "facing": "north", "map": "RowansLab", @@ -167,7 +125,7 @@ }, "execution": { "on_failure": "reload_and_retry", - "saves_in": "Verity Lakefront" + "saves_in": "Twinleaf Town" }, "format": "pokesim-authored-checkpoint/1", "game": "bdsp", diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.04.plan.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.04.plan.json index 13f5fdb661..64013e707e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.04.plan.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.04.plan.json @@ -108,38 +108,152 @@ "why": "run west along the path until Route 201's banner" }, { + "args": { + "fight_wild": false, + "legs": [ + { + "direction": "north", + "tiles": 1 + } + ] + }, + "declared_after": { + "facing": "north", + "map": "Route201", + "tiles": [ + [ + 57, + 4 + ], + [ + 58, + 4 + ], + [ + 59, + 4 + ], + [ + 60, + 4 + ], + [ + 61, + 4 + ], + [ + 62, + 4 + ], + [ + 63, + 4 + ] + ] + }, + "id": "to_the_signs_row", + "kind": "legs", + "why": "a tap north onto the border sign's row" + }, + { + "action": "line", "args": { "fight_wild": false, "target": { - "facing": "north", - "map": "TwinleafTown", + "facing": "west", + "map": "Route201", "tiles": [ [ - 20, - 22 - ], - [ - 20, - 23 - ], + 55, + 5 + ] + ] + } + }, + "id": "to_ledge_column", + "kind": "route", + "why": "west to the border sign, a row south, west to ledge column 55" + }, + { + "args": { + "fight_wild": false, + "legs": [ + { + "direction": "south", + "tiles": 8 + } + ] + }, + "declared_after": { + "facing": "south", + "map": "Route201", + "tiles": [ + [ + 55, + 14 + ] + ] + }, + "id": "over_the_ledge", + "kind": "legs", + "why": "south over the ledge to the lower road" + }, + { + "action": "line", + "args": { + "fight_wild": false, + "target": { + "facing": "west", + "map": "Route201", + "tiles": [ [ - 20, - 24 - ], + 15, + 14 + ] + ] + } + }, + "id": "along_route_201_road", + "kind": "route", + "why": "west along Route 201's road to the Twinleaf path" + }, + { + "action": "line", + "args": { + "fight_wild": false, + "target": { + "facing": "south", + "map": "TwinleafTown", + "tiles": [ [ - 20, - 25 - ], + 15, + 22 + ] + ] + } + }, + "id": "into_twinleaf", + "kind": "route", + "why": "south down column 15 into Twinleaf Town" + }, + { + "action": "line", + "args": { + "fight_wild": false, + "target": { + "facing": "north", + "map": "TwinleafTown", + "tiles": [ [ 20, - 26 + 22 ] ] } }, - "id": "home", + "id": "to_moms_doorstep", "kind": "route", - "why": "west along Route 201 to Twinleaf, running from wild battles" + "why": "east to Mom's house doorstep" }, { "args": { @@ -168,14 +282,14 @@ "tiles": [ [ 6, - 7 + 8 ] ] } }, "id": "beside_mom", "kind": "route", - "why": "west of Mom at (7, 7)" + "why": "west of Mom at (7, 8)" }, { "id": "mom", @@ -184,11 +298,11 @@ }, { "declared_after": { - "facing": "east", + "facing": "south", "map": "PlayerHouse1F", "tiles": [ [ - 6, + 7, 7 ] ] @@ -198,52 +312,100 @@ "why": "Mom heals us; Barry's mom gives us his parcel" }, { + "action": "to_wall", + "args": { + "fight_wild": false, + "legs": [ + { + "direction": "north", + "tiles": 4 + }, + { + "direction": "east", + "tiles": 6 + }, + { + "direction": "south", + "tiles": 4 + } + ] + }, + "declared_after": { + "facing": "south", + "map": "PlayerHouse1F", + "tiles": [ + [ + 11, + 8 + ] + ] + }, + "id": "into_the_east_corner", + "kind": "legs", + "why": "north, east and south to the walls, into the room's east corner" + }, + { + "action": "trigger", "args": { "fight_wild": false, "target": { - "facing": "south", + "facing": "west", "map": "PlayerHouse1F", "tiles": [ [ - 5, + 6, 9 ] ] } }, - "id": "around_mom", + "id": "into_moms_call", "kind": "route", - "why": "around Mom at (6, 8), to beside the door's column" + "why": "round Mom and west along row 9 until her call stops us on (6, 9)" + }, + { + "declared_after": { + "facing": "east", + "map": "TwinleafTown", + "tiles": [ + [ + 19, + 22 + ] + ] + }, + "id": "moms_hat", + "kind": "scene", + "why": "Mom's hat; she walks out with us" }, { - "action": "to_dialogue", + "action": "to_wall", "args": { "fight_wild": false, "legs": [ { - "direction": "east", - "tiles": 1 + "direction": "west", + "tiles": 16 } ] }, - "id": "to_moms_call", - "kind": "legs", - "why": "east above the door until Mom calls" - }, - { "declared_after": { - "facing": "east", + "facing": "west", "map": "TwinleafTown", "tiles": [ [ - 19, + 6, 22 + ], + [ + 6, + 23 ] ] }, - "id": "moms_hat", - "kind": "scene", - "why": "Mom's hat; she walks out with us" + "id": "to_twinleafs_west_wall", + "kind": "legs", + "why": "west along the row to the town's west wall" }, { "args": { diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.04b.plan.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.04b.plan.json index 58d57b54c9..769e54834e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.04b.plan.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.04b.plan.json @@ -118,23 +118,55 @@ "why": "south down the road to above the Mart" }, { - "action": "town", + "action": "to_wall", "args": { "fight_wild": false, - "target": { - "facing": "north", - "map": "SandgemTown", - "tiles": [ - [ - 17, - 11 - ] + "legs": [ + { + "direction": "west", + "tiles": 12 + }, + { + "direction": "south", + "tiles": 6 + } + ] + }, + "declared_after": { + "facing": "south", + "map": "SandgemTown", + "tiles": [ + [ + 20, + 9 ] - } + ] + }, + "id": "above_center_sign", + "kind": "legs", + "why": "west to the road's west wall, then south onto the Center's sign" + }, + { + "args": { + "fight_wild": false, + "legs": [ + { + "direction": "east", + "tiles": 1 + }, + { + "direction": "south", + "tiles": 2 + }, + { + "direction": "west", + "tiles": 4 + } + ] }, "id": "below_center_door", - "kind": "route", - "why": "below the Center's door" + "kind": "legs", + "why": "taps round the sign to below the Center's door" }, { "declared_after": { diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.04c.plan.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.04c.plan.json index 24634070ff..80ca68d8cf 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.04c.plan.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.04c.plan.json @@ -43,7 +43,7 @@ ] ] }, - "title": "Potions, back to Route 202's save spot" + "title": "Poke Mart lady for Potions, back to Route 202's save spot" }, "execution": { "on_failure": "reload_and_retry", diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.05c.plan.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.05c.plan.json index b22437315b..cc4053cbae 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.05c.plan.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-00.05c.plan.json @@ -2,37 +2,75 @@ "checkpoint": { "events": [ { - "action": "town", + "action": "line", "args": { "fight_wild": false, "target": { - "facing": "north", + "facing": "south", "map": "JubilifeCity", "tiles": [ [ - 46, - 36 + 15, + 22 + ] + ] + } + }, + "id": "to_main_boulevard", + "kind": "route", + "why": "south to the main boulevard" + }, + { + "action": "line", + "args": { + "fight_wild": false, + "target": { + "facing": "south", + "map": "JubilifeCity", + "tiles": [ + [ + 45, + 22 + ] + ] + } + }, + "id": "along_main_boulevard", + "kind": "route", + "why": "east along the main boulevard" + }, + { + "action": "line", + "args": { + "fight_wild": false, + "target": { + "facing": "east", + "map": "JubilifeCity", + "tiles": [ + [ + 45, + 35 ] ] } }, - "id": "below_the_president", + "id": "beside_the_president", "kind": "route", - "why": "east along the long road, down the main road" + "why": "south down column 45 to the Poketch president" }, { "id": "president", "kind": "talk", - "why": "the Poketch Company's president at (46, 35)" + "why": "the Poketch Company's president at (46, 36)" }, { "declared_after": { - "facing": "north", + "facing": "east", "map": "JubilifeCity", "tiles": [ [ - 46, - 36 + 45, + 35 ] ] }, @@ -41,7 +79,7 @@ "why": "the coupons for the Poketch; he walks off north" }, { - "action": "town", + "action": "line", "args": { "fight_wild": false, "target": { diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.02.plan.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.02.plan.json index b5eee72e0f..fdcd1d665f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.02.plan.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.02.plan.json @@ -137,7 +137,7 @@ "map": "OreburghGate", "tiles": [ [ - 27, + 26, 22 ] ] @@ -145,7 +145,7 @@ }, "id": "by_the_east_mouth", "kind": "route", - "why": "east past Picnicker Diana's column (24), fighting her" + "why": "east past Picnicker Diana's column (24), fighting her, to two short of the mouth" }, { "action": "to_banner", @@ -198,37 +198,18 @@ }, { "declared_after": { + "facing": "east", "map": "OreburghCity", "tiles": [ [ - 43, - 21 - ], - [ - 44, - 21 - ], - [ - 45, - 21 - ], - [ - 43, - 22 - ], - [ - 44, - 22 - ], - [ - 45, - 22 + 23, + 23 ] ] }, "id": "oreburgh_welcome", "kind": "scene", - "why": "the man's lines, the walk to the Center, and Barry's" + "why": "the man's lines, the walk to the Gym, and Barry's" } ], "id": "01.02", diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.02b.plan.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.02b.plan.json new file mode 100644 index 0000000000..b3589df130 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.02b.plan.json @@ -0,0 +1,117 @@ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "bdsp", + "checkpoint": { + "id": "01.02b", + "title": "Oreburgh Center heal", + "start": { + "map": "OreburghCity", + "facing": "east", + "tiles": [ + [ + 23, + 23 + ] + ] + }, + "events": [ + { + "id": "below_barry", + "kind": "legs", + "args": { + "legs": [ + { + "direction": "south", + "tiles": 1 + }, + { + "direction": "east", + "tiles": 3 + }, + { + "direction": "north", + "tiles": 2 + } + ], + "fight_wild": false + }, + "declared_after": { + "map": "OreburghCity", + "facing": "north", + "tiles": [ + [ + 26, + 22 + ] + ] + }, + "why": "south 1 around the guide, east 3 to Barry's column, north 2 to below Barry" + }, + { + "id": "barry", + "kind": "talk", + "why": "Barry in the Gym's door" + }, + { + "id": "barrys_lines", + "kind": "scene", + "declared_after": { + "map": "OreburghCity", + "facing": "north", + "tiles": [ + [ + 26, + 22 + ] + ] + }, + "why": "Roark has gone to the mine" + }, + { + "id": "below_the_centers_door", + "kind": "route", + "action": "town", + "args": { + "target": { + "map": "OreburghCity", + "facing": "north", + "tiles": [ + [ + 47, + 21 + ] + ] + }, + "fight_wild": false + }, + "why": "east along the street to below the Center's door" + }, + { + "id": "heal_oreburgh_first", + "kind": "heal", + "declared_after": { + "map": "OreburghCity", + "facing": "south", + "tiles": [ + [ + 47, + 21 + ], + [ + 46, + 21 + ] + ] + }, + "why": "the nurse; out onto the doorstep, where 01.03 starts" + } + ] + }, + "execution": { + "on_failure": "reload_and_retry", + "saves_in": "Oreburgh City" + }, + "metadata": { + "phase": "reproduction" + } +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.05.plan.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.05.plan.json index 99db77974b..2cecfbb005 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.05.plan.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.05.plan.json @@ -67,25 +67,49 @@ "why": "Barry runs into us, talks of Eterna, and leaves (assumed: the push)" }, { + "action": "to_wall", "args": { "fight_wild": false, - "target": { - "facing": "west", - "map": "OreburghCity", - "tiles": [ - [ - 2, - 13 - ] + "legs": [ + { + "direction": "south", + "tiles": 6 + }, + { + "direction": "west", + "tiles": 6 + } + ] + }, + "declared_after": { + "facing": "west", + "map": "OreburghCity", + "tiles": [ + [ + 2, + 17 ] - } + ] }, - "id": "by_the_gate", - "kind": "route", - "why": "west to the Gate's warp tile (2, 13)" + "id": "below_the_gates_mouth", + "kind": "legs", + "why": "south to row 17's wall, then west to column 2's" + }, + { + "args": { + "fight_wild": false, + "legs": [ + { + "direction": "north", + "tiles": 4 + } + ] + }, + "id": "to_the_gates_row", + "kind": "legs", + "why": "taps up column 2 to the mouth's row 13" }, { - "action": "to_banner", "args": { "direction": "west" }, @@ -115,7 +139,7 @@ "map": "OreburghGate", "tiles": [ [ - 4, + 5, 22 ] ] @@ -123,7 +147,7 @@ }, "id": "through_the_gate", "kind": "route", - "why": "west along row 22 to the warp tile by the west mouth (3, 22)" + "why": "west along row 22 to two tiles short of the west mouth's warp (3, 22)" }, { "action": "to_banner", diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.06.plan.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.06.plan.json index 7bbe63308f..84772dbd9d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.06.plan.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.06.plan.json @@ -1,6 +1,25 @@ { "checkpoint": { "events": [ + { + "action": "town", + "args": { + "fight_wild": false, + "target": { + "facing": "north", + "map": "JubilifeCity", + "tiles": [ + [ + 41, + 8 + ] + ] + } + }, + "id": "up_jubilifes_road", + "kind": "route", + "why": "down Route 203 (its ledges only south), west along it into Jubilife's street, north up the road's west column" + }, { "action": "town", "args": { @@ -18,7 +37,7 @@ }, "id": "below_rowans_trigger", "kind": "route", - "why": "down Route 203 (its ledges only south), west along it into Jubilife's street, north up the road" + "why": "east along row 8 to the sign's wall" } ], "id": "01.06", diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.10.plan.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.10.plan.json index fc47208040..7db99462ea 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.10.plan.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.10.plan.json @@ -110,41 +110,37 @@ "why": "a corner of the human's line" }, { - "action": "line", + "action": "to_map", "args": { "fight_wild": false, - "target": { - "map": "Route204North", - "tiles": [ - [ - 11, - 5 - ] - ] - } + "legs": [ + { + "direction": "north", + "tiles": 17 + } + ] }, - "id": "line_7", - "kind": "route", - "why": "a corner of the human's line" - }, - { - "action": "line", - "args": { - "fight_wild": false, - "target": { - "facing": "north", - "map": "FloaromaTown", - "tiles": [ - [ - 11, - 29 - ] + "declared_after": { + "facing": "north", + "map": "FloaromaTown", + "tiles": [ + [ + 11, + 27 + ], + [ + 11, + 28 + ], + [ + 11, + 29 ] - } + ] }, "id": "into_floaroma", - "kind": "route", - "why": "north up column 11 into Floaroma" + "kind": "legs", + "why": "run north until Floaroma's banner; on after a wild battle" }, { "id": "save_here", diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.11.plan.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.11.plan.json index dafdf2a436..422787dd0f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.11.plan.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-01.11.plan.json @@ -2,22 +2,51 @@ "checkpoint": { "events": [ { + "action": "to_wall", "args": { "fight_wild": false, - "target": { - "facing": "west", - "map": "FloaromaTown", - "tiles": [ - [ - 3, - 29 - ] + "legs": [ + { + "direction": "west", + "tiles": 13 + } + ] + }, + "declared_after": { + "facing": "west", + "map": "FloaromaTown", + "tiles": [ + [ + 0, + 27 + ], + [ + 0, + 28 + ], + [ + 0, + 29 ] - } + ] + }, + "id": "west_to_the_field_edge", + "kind": "legs", + "why": "until the field's edge stops us" + }, + { + "args": { + "fight_wild": false, + "legs": [ + { + "direction": "east", + "tiles": 4 + } + ] }, - "id": "west_along_the_field", - "kind": "route", - "why": "west along row 29" + "id": "below_her_column", + "kind": "legs", + "why": "4 taps east to her column (westedge batch 2026-11-08)" }, { "action": "to_wall", @@ -67,16 +96,12 @@ { "args": { "fight_wild": false, - "target": { - "facing": "west", - "map": "FloaromaTown", - "tiles": [ - [ - 3, - 26 - ] - ] - } + "legs": [ + { + "direction": "west", + "tiles": 1 + } + ] }, "declared_after": { "facing": "north", @@ -89,7 +114,7 @@ ] }, "id": "below_the_old_man", - "kind": "route", + "kind": "legs", "why": "a tile west" }, { @@ -123,6 +148,14 @@ "facing": "north", "map": "FloaromaTown", "tiles": [ + [ + 11, + 27 + ], + [ + 11, + 28 + ], [ 11, 29 diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-mine-01.03.md b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-mine-01.03.md new file mode 100644 index 0000000000..9237f7a965 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-mine-01.03.md @@ -0,0 +1,41 @@ +# Mine/Roark checkpoint: route evidence + +This sidecar preserves the reasoning that previously accompanied the C++ row. The JSON defines current actions; these observations explain why they were chosen. They are historical evidence, not new console verification. Entry assumes the preceding Barry conversation and Center heal have completed. + +## Entry and Center alignment + +The Center door is `(47,20)`, so its approach is `(47,21)` facing north. The published `pokemon_center_doorstep` is `(46,21)`: a route there hit the wall west of the door and healing found no door (lab-B, 2026-11-07 20:18). Both `(47,21)` and `(46,21)` facing south remain exit alternatives. Earlier Gym alignment runs r217d/r218d inferred column 46 from twenty west taps; they did not independently establish where those taps began. + +`above_the_mine` goes to `(46,57)` facing south, two tiles short of the warp row so an open walk cannot slide onto it (01.05, lab-B 2026-11-08). The city's five warp tiles `(44..48,59)` map into the hall at `(11,1),(11,1),(12,1),(13,1),(13,1)`. Thus column 46 enters B1F at `(12,1)`. The mine hall is Diamond's B1F; the coal room below is the room with Roark. Diamond zone-event sources were narc_0044/narc_0197; Platinum's event files provide the corresponding warp layout, used as evidence for BDSP's retained DP layout. + +## Into the coal room + +`into_the_mine` and `into_the_coal_room` cross the cave mouths. Hall movement uses counted taps rather than an open hold toward a fade: a wild battle on a hold can be mistaken for the transition. Warp entry itself is expected on the subsequent step. These are executor assumptions that still need detector/interruption coverage. + +The hall's coal-room mouth is `(11..13,21)`; column 12 enters the coal room at `(15,2)`. `south_to_the_rock` clips the corridor rock before the grouped inbound legs. The script's anchor is `(15,9)` facing south; the rock was described at `(15,11)`. + +## Roark approach and talk + +`to_roarks_corner` groups all nine inbound legs through `(20,28)` facing west, rather than ending recovery at an open intermediate tile. Lab-B, 2026-11-08 11:55: recovery replanned only to `(15,16)`, a subsequent south-five leg overshot a row, and later taps ran under Roark's rocks. Grouping through a corner allows a replanned path to finish with wall clips. The offline interrupted-leg case deliberately stops with uncertainty; it does not prove live recovery/rejoin. + +`beside_roarks_rock` clips the room's south wall to `(20,29)`, then `below_roark` moves west two to `(18,29)` facing north. Lab-B, 2026-11-07: an open counted south-three leg moved only two, motivating the wall anchor. Roark's map point is `(18,28)`; native tests check the authored below-Roark pose against that map point. + +`roark` initiates the conversation. Barry's earlier message that Roark went to the mine is a prerequisite: Roark ignored A without it in r101/r104. `roark_smashes_the_rock` represents the lines, Rock Smash east of him, and his departure east, consistent with Platinum's mine B2F script. The declared return pose is an executor fallback, not an observed receipt proving the scene completed. + +## Back through the hall + +`below_the_coal_rooms_warp` contains the ten outbound legs: east around the crate, north along column 29, west across row 17, then up the corridor to `(15,2)` facing north. Entering `(15,1)` returns to the hall at `(12,21)`, not `(11,21)`. + +`up_to_the_hall` and `out_of_the_mine` continue up column 12. The hall's `(12,1)` exit leads to city `(46,59)`. The city belief also permits `(46,58)` if movement continued past the fade. Lab-B, 2026-11-08 09:46, 10:39 and 12:03: the exit was east of the sign `(45,56)` and northward movement did not stop there. At 13:50, a north tap and east wall hold matched the map only from column 46. + +## Return to the nurse + +`north_to_the_centers_wall` clips the wall at `(46,20)` from either exit tile: 37 tiles from row 58 or 38 from row 59. The Hiker wanders through columns 46..48 and rows 25..27; the live walker must wait or recover safely, and the offline model uses an explicit synthetic clearance window. + +This column avoids the street east of the mine. At 13:50, an east hold from `(48,57)` moved zero although the map showed `(49,57)` open; later movement went astray. That discrepancy remains unresolved and is not grounds to change terrain silently. + +`east_below_the_centers_door` moves one tile east to `(47,21)` facing north. `heal_oreburgh` enters, heals and exits to the two-tile doorstep belief. The next Gym checkpoint starts there. The checkpoint keeps save-at-start/reload-and-retry guarded by the Oreburgh City save card. + +## Updating this route + +Edit the authoritative JSON, update relevant native/scenario expectations, and preserve new run evidence here. A changed map pin requires anchor review. A claimed transition or recovery fix needs an independent observation/regression case; do not turn `declared_after` into proof of success. The initial migration was checked against the pre-migration row and the reported successful lab-B sequence of 2026-11-08 14:17–14:23; later changes must record their own evidence. diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-mine-01.03.plan.json b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-mine-01.03.plan.json index 5d873530a3..184f335520 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-mine-01.03.plan.json +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/StoryData/bdsp-mine-01.03.plan.json @@ -1,55 +1,24 @@ -{ +{ + "format": "pokesim-authored-checkpoint/1", + "game": "bdsp", "checkpoint": { + "id": "01.03", + "title": "Oreburgh Mine to Roark", + "start": { + "facing": "south", + "map": "OreburghCity", + "tiles": [ + [ + 47, + 21 + ], + [ + 46, + 21 + ] + ] + }, "events": [ - { - "action": "town", - "args": { - "fight_wild": false, - "target": { - "facing": "north", - "map": "OreburghCity", - "tiles": [ - [ - 47, - 21 - ] - ] - } - }, - "declared_after": { - "facing": "north", - "map": "OreburghCity", - "tiles": [ - [ - 47, - 21 - ] - ] - }, - "id": "below_the_centers_door", - "kind": "route", - "why": "below the Center's door" - }, - { - "id": "barry", - "kind": "talk", - "why": "Barry in the Center's door" - }, - { - "declared_after": { - "facing": "north", - "map": "OreburghCity", - "tiles": [ - [ - 47, - 21 - ] - ] - }, - "id": "barrys_lines", - "kind": "scene", - "why": "Roark has gone to the mine" - }, { "action": "town", "args": { @@ -60,14 +29,14 @@ "tiles": [ [ 46, - 58 + 57 ] ] } }, "id": "above_the_mine", "kind": "route", - "why": "down the door's column to above the mine's warp tiles" + "why": "down the door's column to two above the mine's warp tiles (44..48, 59)" }, { "args": { @@ -88,40 +57,103 @@ "why": "the warp tile (46, 59)" }, { + "args": { + "direction": "south" + }, + "declared_after": { + "facing": "south", + "map": "OreburghMine", + "tiles": [ + [ + 15, + 2 + ] + ] + }, + "id": "into_the_coal_room", + "kind": "step", + "why": "down the entrance hall through the cave mouth" + }, + { + "action": "to_wall", "args": { "fight_wild": false, "legs": [ { "direction": "south", - "tiles": 19 + "tiles": 8 } ] }, - "id": "down_the_hall", + "declared_after": { + "facing": "south", + "map": "OreburghMine", + "tiles": [ + [ + 15, + 9 + ] + ] + }, + "id": "south_to_the_rock", "kind": "legs", - "why": "down column 12 of the entrance hall" + "why": "south against the corridor rock (15, 11)" }, { "args": { - "direction": "south" + "fight_wild": false, + "legs": [ + { + "direction": "east", + "tiles": 1 + }, + { + "direction": "south", + "tiles": 2 + }, + { + "direction": "west", + "tiles": 1 + }, + { + "direction": "south", + "tiles": 5 + }, + { + "direction": "east", + "tiles": 14 + }, + { + "direction": "south", + "tiles": 10 + }, + { + "direction": "west", + "tiles": 2 + }, + { + "direction": "south", + "tiles": 2 + }, + { + "direction": "west", + "tiles": 7 + } + ] }, "declared_after": { - "facing": "south", + "facing": "west", "map": "OreburghMine", "tiles": [ [ - 15, - 2 - ], - [ - 15, - 1 + 20, + 28 ] ] }, - "id": "into_the_coal_room", - "kind": "step", - "why": "the hall's warp tiles (11..13, 21)" + "id": "to_roarks_corner", + "kind": "legs", + "why": "east around the rock, across the room, down column 29, west to Roark's rock" }, { "action": "to_wall", @@ -130,7 +162,7 @@ "legs": [ { "direction": "south", - "tiles": 9 + "tiles": 1 } ] }, @@ -139,32 +171,38 @@ "map": "OreburghMine", "tiles": [ [ - 15, - 9 + 20, + 29 ] ] }, - "id": "down_to_the_boulder", + "id": "beside_roarks_rock", "kind": "legs", - "why": "down the corridor to the boulder (15, 10)" + "why": "south against the room's wall" }, { "args": { "fight_wild": false, - "target": { - "facing": "north", - "map": "OreburghMine", - "tiles": [ - [ - 18, - 29 - ] + "legs": [ + { + "direction": "west", + "tiles": 2 + } + ] + }, + "declared_after": { + "facing": "north", + "map": "OreburghMine", + "tiles": [ + [ + 18, + 29 ] - } + ] }, "id": "below_roark", - "kind": "route", - "why": "down the corridor and the room's east side, west along the bottom row" + "kind": "legs", + "why": "west 2 to below Roark" }, { "id": "roark", @@ -189,20 +227,62 @@ { "args": { "fight_wild": false, - "target": { - "facing": "north", - "map": "OreburghMine", - "tiles": [ - [ - 15, - 2 - ] + "legs": [ + { + "direction": "east", + "tiles": 9 + }, + { + "direction": "north", + "tiles": 3 + }, + { + "direction": "east", + "tiles": 2 + }, + { + "direction": "north", + "tiles": 10 + }, + { + "direction": "west", + "tiles": 14 + }, + { + "direction": "north", + "tiles": 5 + }, + { + "direction": "east", + "tiles": 1 + }, + { + "direction": "north", + "tiles": 2 + }, + { + "direction": "west", + "tiles": 1 + }, + { + "direction": "north", + "tiles": 7 + } + ] + }, + "declared_after": { + "facing": "north", + "map": "OreburghMine", + "tiles": [ + [ + 15, + 2 ] - } + ] }, "id": "below_the_coal_rooms_warp", - "kind": "route", - "why": "back up the corridor" + "kind": "legs", + "why": "east around crate, up column 29, west across row 17, and up corridor to warp doorstep" }, { "args": { @@ -213,7 +293,7 @@ "map": "OreburghMineB1F", "tiles": [ [ - 11, + 12, 21 ] ] @@ -222,20 +302,6 @@ "kind": "step", "why": "the warp tile (15, 1)" }, - { - "args": { - "fight_wild": false, - "legs": [ - { - "direction": "north", - "tiles": 19 - } - ] - }, - "id": "up_the_hall", - "kind": "legs", - "why": "up column 11 of the entrance hall" - }, { "args": { "direction": "north" @@ -245,27 +311,27 @@ "map": "OreburghCity", "tiles": [ [ - 45, + 46, 59 ], [ - 45, + 46, 58 ] ] }, "id": "out_of_the_mine", "kind": "step", - "why": "the hall's warp tiles (11..13, 1)" + "why": "up the entrance hall and out to the city" }, { - "action": "to_wall", + "action": "counted_wall", "args": { "fight_wild": false, "legs": [ { "direction": "north", - "tiles": 3 + "tiles": 37 } ] }, @@ -274,33 +340,38 @@ "map": "OreburghCity", "tiles": [ [ - 45, - 57 + 46, + 21 ] ] }, - "id": "up_to_the_mines_sign", + "id": "north_to_the_centers_wall", "kind": "legs", - "why": "north against the mine's sign (45, 56)" + "why": "north up column 46 to the wall west of the Center's door" }, { - "action": "town", "args": { "fight_wild": false, - "target": { - "facing": "north", - "map": "OreburghCity", - "tiles": [ - [ - 47, - 21 - ] + "legs": [ + { + "direction": "east", + "tiles": 1 + } + ] + }, + "declared_after": { + "facing": "north", + "map": "OreburghCity", + "tiles": [ + [ + 47, + 21 ] - } + ] }, - "id": "below_the_centers_door_again", - "kind": "route", - "why": "up to below the Center's door" + "id": "east_below_the_centers_door", + "kind": "legs", + "why": "a tap east below the door" }, { "declared_after": { @@ -321,45 +392,12 @@ "kind": "heal", "why": "the nurse; out onto the doorstep, where 01.04 starts" } - ], - "id": "01.03", - "start": { - "map": "OreburghCity", - "tiles": [ - [ - 43, - 21 - ], - [ - 44, - 21 - ], - [ - 45, - 21 - ], - [ - 43, - 22 - ], - [ - 44, - 22 - ], - [ - 45, - 22 - ] - ] - }, - "title": "Oreburgh Mine to Roark" + ] }, "execution": { "on_failure": "reload_and_retry", "saves_in": "Oreburgh City" }, - "format": "pokesim-authored-checkpoint/1", - "game": "bdsp", "metadata": { "phase": "reproduction" } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegTraceIO.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegTraceIO.cpp new file mode 100644 index 0000000000..de3701e65c --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_LegTraceIO.cpp @@ -0,0 +1,123 @@ +/* BDSP AutoStory - Leg Trace IO + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "PokemonBDSP_AutoStory_LegTraceIO.h" +#include "PokemonBDSP_AutoStory_WalkResult.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using Pokemon::LegEndKind; +using Pokemon::LegEndKnown; +using Pokemon::LegInterrupt; + + +Pokemon::LegTracer legs_to_log(RouteIO& io){ + return Pokemon::LegTracer([&io](const std::string& line){ io.note(line, RouteNote::LOG); }); +} + +void LegTraceRouteIO::walked(const WalkResult& result){ + m_tracer.walked({.chunks = result.moved_chunks, .walked_ms = result.walked.count(), .wild_battles = result.wild_battles}); +} + +WalkResult LegTraceRouteIO::walk_to_wall(const RouteWallWalk& walk){ + const WalkResult result = m_inner.walk_to_wall(walk); + walked(result); + return result; +} + +WalkResult LegTraceRouteIO::walk_taps(Pokemon::Direction direction, size_t tiles, const std::string& label){ + const WalkResult result = m_inner.walk_taps(direction, tiles, label); + m_tracer.walked({.chunks = result.moved_chunks, .walked_ms = result.walked.count(), + .wild_battles = result.wild_battles, .tapped = result.moved_chunks}); + return result; +} + +void LegTraceRouteIO::note(const std::string& text, RouteNote kind){ + if (kind == RouteNote::FAILURE){ + // A failure does not return: the leg ends here, unknown. + m_tracer.end_event(); + m_inner.note(text, kind); + return; + } + m_inner.note(text, kind); + read_route_line(text); +} + +namespace{ + +// The text between `after` and `before` in `text`, both searched from the +// end; empty if either is missing. +std::string_view between_last(std::string_view text, std::string_view after, std::string_view before){ + const size_t end = text.rfind(before); + if (end == std::string_view::npos){ + return {}; + } + const size_t begin = text.rfind(after, end); + if (begin == std::string_view::npos){ + return {}; + } + return text.substr(begin + after.size(), end - begin - after.size()); +} + +} // namespace + +// The planned route walker's lines (PokemonBDSP_AutoStory_PlannedRoute.cpp, +// Pokemon_RouteLog.h): +// Leg 1/2: east 15 (to wall) to Route 202 (23, 25) +// [Route]