diff --git a/.github/workflows/cpp-ci-serial-programs-base.yml b/.github/workflows/cpp-ci-serial-programs-base.yml index 8eefdf4f37..85f9fe8847 100644 --- a/.github/workflows/cpp-ci-serial-programs-base.yml +++ b/.github/workflows/cpp-ci-serial-programs-base.yml @@ -109,7 +109,7 @@ jobs: - name: Prepare approved FRLG map resources id: map-resources - uses: dayfine/PokemonSimulation/integrations/arduino-source/verify-map-packs@d3eea1b5c04180f8b60eb98b0d65f70aca6b1abb + uses: dayfine/PokemonSimulation/integrations/arduino-source/verify-map-packs@1cacf81b2377ec1413317d905ad5415f6fe8dad5 with: layout: resources operation: prepare diff --git a/SerialPrograms/Source/CommonFramework/Main.cpp b/SerialPrograms/Source/CommonFramework/Main.cpp index c493f48b54..ef6742e2eb 100644 --- a/SerialPrograms/Source/CommonFramework/Main.cpp +++ b/SerialPrograms/Source/CommonFramework/Main.cpp @@ -220,9 +220,12 @@ int run_program(int argc, char *argv[]){ GlobalThreadPools::qt_event_threadpool(); bool augment_test_color_distortions = false; + std::string test_substring; + bool test_substring_missing_value = false; for (size_t i = 0; i < argc; i++){ constexpr const char* force_run_tests = "--command-line-test-mode"; constexpr const char* distort_test_images = "--augment-color-distortions"; + constexpr const char* filter_tests_substring = "--test-substring"; if (strcmp(argv[i], force_run_tests) == 0){ GlobalSettings::instance().COMMAND_LINE_TEST_MODE = true; @@ -230,10 +233,21 @@ int run_program(int argc, char *argv[]){ if (strcmp(argv[i], distort_test_images) == 0){ augment_test_color_distortions = true; } + if (strcmp(argv[i], filter_tests_substring) == 0){ + if (i + 1 < argc){ + test_substring = argv[++i]; + }else{ + test_substring_missing_value = true; + } + } + } + if (test_substring_missing_value){ + global_logger_command_line().log("--test-substring requires a value", COLOR_RED); + return 1; } if (GlobalSettings::instance().COMMAND_LINE_TEST_MODE){ - return run_command_line_tests(augment_test_color_distortions); + return run_command_line_tests(augment_test_color_distortions, test_substring); } // Check whether the hardware is powerful enough to run this program. diff --git a/SerialPrograms/Source/CommonTools/ScreenMachine/ScreenMachine.cpp b/SerialPrograms/Source/CommonTools/ScreenMachine/ScreenMachine.cpp index a60a4e0fa5..587d740ec8 100644 --- a/SerialPrograms/Source/CommonTools/ScreenMachine/ScreenMachine.cpp +++ b/SerialPrograms/Source/CommonTools/ScreenMachine/ScreenMachine.cpp @@ -30,6 +30,43 @@ const ScreenState* classify(const std::vector& states, const ImageV } // namespace +std::string_view screen_event_name(ScreenEvent event){ + switch (event){ + case ScreenEvent::FADE_BLACK: return "fade_black"; + case ScreenEvent::FADE_WHITE: return "fade_white"; + case ScreenEvent::TEXT_BOX: return "text_box"; + case ScreenEvent::BATTLE: return "battle"; + case ScreenEvent::CAN_MOVE: return "can_move"; + case ScreenEvent::STILL: return "still"; + case ScreenEvent::CHOICE_BOX: return "choice_box"; + case ScreenEvent::INTERACT_PROMPT: return "interact_prompt"; + } + return "unknown"; +} + +std::string describe(const ScreenEvents& events, std::string_view separator){ + constexpr ScreenEvent ALL[] = { + ScreenEvent::FADE_BLACK, ScreenEvent::FADE_WHITE, ScreenEvent::TEXT_BOX, + ScreenEvent::BATTLE, ScreenEvent::CAN_MOVE, ScreenEvent::STILL, + ScreenEvent::CHOICE_BOX, ScreenEvent::INTERACT_PROMPT, + }; + std::string text; + for (ScreenEvent event : ALL){ + if (events.has(event)){ + text += text.empty() ? "" : separator; + text += screen_event_name(event); + } + } + return text.empty() ? std::string("nothing") : text; +} + +bool same_screen(const VideoSnapshot& a, const VideoSnapshot& b){ + if (!a || !b || a->width() != b->width() || a->height() != b->height()){ + return false; + } + return ImageMatch::pixel_RMSD(a, b) < 2.0; +} + const ScreenState* match_screen_state(const std::vector& states, const ScreenObservation& observation){ for (const ScreenState& state : states){ if (state.matches_observation && state.matches_observation(observation)){ @@ -100,9 +137,7 @@ std::optional ScreenMachineChecks::unchanged_problem(const ScreenSt } std::optional ScreenMachineChecks::problem(const ScreenState& state, VideoSnapshot frame, WallClock when){ - const bool same_size = m_last_frame && frame && - m_last_frame->width() == frame->width() && m_last_frame->height() == frame->height(); - if (same_size && ImageMatch::pixel_RMSD(m_last_frame, frame) < 2.0){ + if (same_screen(m_last_frame, frame)){ std::optional stalled = unchanged_problem(state, when); if (stalled){ return stalled; diff --git a/SerialPrograms/Source/CommonTools/ScreenMachine/ScreenObservation.h b/SerialPrograms/Source/CommonTools/ScreenMachine/ScreenObservation.h index 6c80b29327..636e8eec7d 100644 --- a/SerialPrograms/Source/CommonTools/ScreenMachine/ScreenObservation.h +++ b/SerialPrograms/Source/CommonTools/ScreenMachine/ScreenObservation.h @@ -20,6 +20,7 @@ #include #include #include +#include #include "Common/Cpp/Time.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" @@ -77,6 +78,17 @@ struct ScreenObservation{ std::optional frame = std::nullopt; }; +// "fade_black", "fade_white", "text_box", "battle", "can_move", "still", +// "choice_box", "interact_prompt". +std::string_view screen_event_name(ScreenEvent event); + +// The events in `events` joined by `separator`, or "nothing" when empty. +std::string describe(const ScreenEvents& events, std::string_view separator = ", "); + +// Whether `a` and `b` both have a frame of the same size within the +// still-screen RMSD threshold (2.0). +bool same_screen(const VideoSnapshot& a, const VideoSnapshot& b); + } // namespace PokemonAutomation diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp index 57691f3c19..9a5cf86d3d 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.cpp @@ -35,12 +35,17 @@ #include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" #include "PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h" +#include "Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h" +#include "Pokemon/Navigation/Pokemon_Gates_Tests.h" #include "Pokemon/Navigation/Pokemon_LegPlanner_Tests.h" #include "Pokemon/Navigation/Pokemon_LegWalker_Tests.h" #include "Pokemon/Navigation/Pokemon_MapData_Tests.h" +#include "Pokemon/Navigation/Pokemon_MoveMechanics_Tests.h" #include "Pokemon/Navigation/Pokemon_RouteLog_Tests.h" #include "Pokemon/Navigation/Pokemon_RuntimeMap_Tests.h" #include "Pokemon/Navigation/Pokemon_WallRecovery_Tests.h" +#include "Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h" +#include "Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.h" #include "VideoGames/PokemonHome/PokemonHome_Tests.h" #include "VideoGames/PokemonSwSh/PokemonSwSh_Tests.h" #include "VideoGames/PokemonLA/PokemonLA_Tests.h" @@ -83,8 +88,13 @@ UnitTestDatabase make_UNIT_TESTS_ALL(){ Pokemon::add_tests_LegWalker(ret); Pokemon::add_tests_WallRecovery(ret); Pokemon::add_tests_MapData(ret); + Pokemon::add_tests_ConnectedMaps(ret); + Pokemon::add_tests_Gates(ret); + Pokemon::add_tests_MoveMechanics(ret); Pokemon::add_tests_RuntimeMap(ret); Pokemon::add_tests_RouteLog(ret); + Pokemon::add_tests_SimFaults(ret); + Pokemon::add_tests_SimGolden(ret); Pokemon::add_tests_AutoStory(ret); NintendoSwitch::add_tests_CheckOnlineDetector(ret); NintendoSwitch::add_tests_FailedToConnectDetector(ret); @@ -123,6 +133,25 @@ const StringSelectDatabase& TEST_DATABASE(){ } +namespace{ + +// For each test in `UNIT_TESTS_ALL()` whose name contains `filter`, in name order, call +// `add_test(test)`. An empty `filter` matches all the tests. Return the number of tests +// visited. +template +size_t add_tests_matching(const std::string& filter, AddTest&& add_test){ + size_t count = 0; + for (const auto& test : UNIT_TESTS_ALL()){ + if (filter.empty() || test.first.contains(filter)){ + count++; + add_test(test.second); + } + } + return count; +} + +} + UnitTestRunner_Descriptor::UnitTestRunner_Descriptor() @@ -253,15 +282,12 @@ void UnitTestRunner::on_config_value_changed(void* object){ if (object == &SUBSTRING_TEST){ std::string name = SUBSTRING_TEST; TESTS_TO_RUN.set(""); - size_t count = 0; - for (const auto& test : UNIT_TESTS_ALL()){ - if (test.first.contains(name)){ - count++; - if (count <= 1000){ - TESTS_TO_RUN.append(test.first + "\n"); - } + size_t num_shown = 0; + size_t count = add_tests_matching(name, [&](std::shared_ptr test){ + if (++num_shown <= 1000){ + TESTS_TO_RUN.append(test->name() + "\n"); } - } + }); if (count > 1000){ TESTS_TO_RUN.append("<" + tostr_u_commas(count - 1000) + " more...>\n"); } @@ -292,6 +318,12 @@ void UnitTestRunner::program(ProgramEnvironment& env, CancellableScope& scope){ const UnitTestDatabase& all_tests = UNIT_TESTS_ALL(); + auto add_matching = [&](const std::string& filter){ + add_tests_matching(filter, [&](std::shared_ptr test){ + runner.add_test(test); + }); + }; + switch ((RunMode)RUN_MODE){ case RunMode::RUN_ONE:{ auto iter = all_tests.find(SINGLE_TEST.slug()); @@ -305,22 +337,13 @@ void UnitTestRunner::program(ProgramEnvironment& env, CancellableScope& scope){ runner.add_test(iter->second); break; } - case RunMode::RUN_SUBSTRING_MATCH:{ - std::string name = SUBSTRING_TEST; - for (const auto& test : all_tests){ - if (test.first.contains(name)){ - runner.add_test(test.second); - } - } + case RunMode::RUN_SUBSTRING_MATCH: + add_matching(SUBSTRING_TEST); break; - } - case RunMode::RUN_ALL:{ - for (const auto& test : all_tests){ - runner.add_test(test.second); - } + case RunMode::RUN_ALL: + add_matching(""); break; } - } runner.run(); } @@ -381,7 +404,7 @@ void UnitTestRunner::on_test_finished( -bool CommandLineUnitTestRunner::run(bool augment_color_distortions){ +bool CommandLineUnitTestRunner::run(bool augment_color_distortions, const std::string& test_substring){ if (augment_color_distortions){ // Load the distortion data before any test runs. Each `ImageUnitTest` checks the global // manager when it runs, and only runs with distortions if it is loaded. @@ -407,8 +430,15 @@ bool CommandLineUnitTestRunner::run(bool augment_color_distortions){ GlobalThreadPools::unlimited_normal() ); runner.add_listener(*this); - for (const auto& test : UNIT_TESTS_ALL()){ - runner.add_test(test.second); + size_t num_matching = add_tests_matching(test_substring, [&](std::shared_ptr test){ + runner.add_test(test); + }); + if (!test_substring.empty()){ + if (num_matching == 0){ + m_logger.log("No test name contains \"" + test_substring + "\". No tests will be run.", COLOR_ORANGE); + }else{ + m_logger.log("Running the " + tostr_u_commas(num_matching) + " tests whose name contains \"" + test_substring + "\""); + } } runner.run(); diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.h b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.h index c3aeb94f07..3baffcc745 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.h +++ b/SerialPrograms/Source/ComputerPrograms/ComputerPrograms_UnitTestRunner.h @@ -89,12 +89,15 @@ class CommandLineUnitTestRunner : public PokemonAutomation::UnitTestRunner::List , m_failed_tests(0) {} - // Run all the unit tests. Return true if any test failed. + // Run the unit tests. Return true if any test failed. // If `augment_color_distortions` is true, also run each image test under different color // distortion augmentation to widen the test coverage, using the distortion data in the // CaptureCardCalibration/ folder of the test repo. If that data can't be loaded, log the // error and return true without running any test. - bool run(bool augment_color_distortions); + // If `test_substring` is not empty, only run the tests whose name contains that substring + // (case sensitive, the same matching as the GUI's "Run All Tests Containing This Substring" + // mode). If nothing matches, no test runs and a warning is logged. + bool run(bool augment_color_distortions, const std::string& test_substring); private: diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp index 147fa168a9..ae61bbc538 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_AuthoredCheckpointJson_Tests.cpp @@ -33,24 +33,24 @@ enum class Failure{ MISSING_RESOURCE, }; -struct AuthoredInput{ - std::string name; - std::string json; - std::string game = "frlg"; - bool resource = false; - std::string file = "plan"; -}; +struct AuthoredCase{ + struct Input{ + std::string name; + std::string json; + std::string game = "frlg"; + bool resource = false; + std::string file = "plan"; + }; -struct AuthoredExpectation{ - std::string checkpoint = "00.05"; - std::string execution = R"({"menu":"before_pokedex"})"; - std::vector events = {"first", "second"}; - Failure failure = Failure::NONE; -}; + struct Expectation{ + std::string checkpoint = "00.05"; + std::string execution = R"({"menu":"before_pokedex"})"; + std::vector events = {"first", "second"}; + Failure failure = Failure::NONE; + }; -struct AuthoredCase{ - AuthoredInput input; - AuthoredExpectation expectation; + Input input; + Expectation expectation; }; const AuthoredCase CASES[] = { diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp index 3d39269e07..c54b7f4141 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.cpp @@ -323,8 +323,53 @@ DeclaredPose read_declared_pose(const JsonValue& value, std::string_view source) return result; } +GateChange read_gate_change(const JsonValue& value, std::string_view source){ + const JsonObject& root = fields(value, {"opened", "switches"}, source); + GateChange result; + if (const JsonValue* field = root.get_value("opened")){ + for (std::string& key : read_strings(*field, source)){ + result.opened.insert(std::move(key)); + } + } + if (const JsonValue* field = root.get_value("switches")){ + for (const auto& [id, on] : field->to_object_throw(std::string(source))){ + result.switches[id] = on.to_boolean_throw(std::string(source)); + } + } + return result; +} + +JsonValue write_gate_change(const GateChange& change){ + JsonObject object; + if (!change.opened.empty()){ + JsonArray opened; + for (const std::string& key : change.opened){ + opened.push_back(key); + } + object["opened"] = std::move(opened); + } + if (!change.switches.empty()){ + JsonObject switches; + for (const auto& [id, on] : change.switches){ + switches[id] = on; + } + object["switches"] = std::move(switches); + } + return object; +} + +GateState read_gate_state(const JsonValue& value, std::string_view source){ + GateState result; + apply_gate_change(result, read_gate_change(value, source)); + return result; +} + +JsonValue write_gate_state(const GateState& state){ + return write_gate_change(gate_change_between(GateState(), state)); +} + StoryStep read_story_step(const JsonValue& value, std::string_view source, std::span actions){ - const JsonObject& root = fields(value, {"id", "kind", "why", "action", "args", "skip_if", "declared_after"}, source); + const JsonObject& root = fields(value, {"id", "kind", "why", "action", "args", "skip_if", "declared_after", "gates_after", "flags_after"}, source); StoryStep result; result.name = root.get_string_throw("id"); if (result.name.empty()){ @@ -344,11 +389,17 @@ StoryStep read_story_step(const JsonValue& value, std::string_view source, std:: if (const JsonValue* field = root.get_value("declared_after")){ result.pose_after = read_declared_pose(*field, source); } + if (const JsonValue* field = root.get_value("gates_after")){ + result.gates_after = read_gate_change(*field, source); + } + if (const JsonValue* field = root.get_value("flags_after")){ + result.flags_after = read_strings(*field, source); + } return result; } StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view source, std::span actions){ - const JsonObject& root = fields(value, {"id", "title", "start", "events", "metadata"}, source); + const JsonObject& root = fields(value, {"id", "title", "start", "start_gates", "start_flags", "events", "metadata"}, source); StoryCheckpoint result; result.id = root.get_string_throw("id"); if (result.id.empty()){ @@ -358,6 +409,12 @@ StoryCheckpoint read_story_checkpoint(const JsonValue& value, std::string_view s if (const JsonValue* start = root.get_value("start")){ result.start = read_declared_pose(*start, source); } + if (const JsonValue* gates = root.get_value("start_gates")){ + result.start_gates = read_gate_state(*gates, source); + } + if (const JsonValue* flags = root.get_value("start_flags")){ + result.start_flags = read_strings(*flags, source); + } std::set names; result.steps_json = root.get_value_throw("events").dump(-1); for (const JsonValue& event : root.get_array_throw("events")){ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h index a67f5df31c..5bc64ab097 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h @@ -36,6 +36,20 @@ GridPose read_grid_pose(const JsonValue& value, std::string_view source); DeclaredPose read_declared_pose(const JsonValue& value, std::string_view source); +// Read a gate change, {"opened": ["SilphCo_5F/door_1"], "switches": {"mansion": true}} +// (the gates a step opens, the switches it sets; both optional, unknown +// fields fail) and write it back. +GateChange read_gate_change(const JsonValue& value, std::string_view source); +// The change as JSON, as read_gate_change() reads it. +JsonValue write_gate_change(const GateChange& change); + +// The same as a state: what a checkpoint's "start_gates" says is open and +// on. "switches" that are off need not be listed, and are not written. +GateState read_gate_state(const JsonValue& value, std::string_view source); +// The state as JSON, as read_gate_state() reads it. +JsonValue write_gate_state(const GateState& state); + + // Read a step, its args parsed against its action among `actions` (by // default the built-in ones; a game passes them with its own) and their // fallbacks filled in. Unknown fields, kinds, actions and args, mistyped diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp index 0433258cbb..7fcedf7887 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp @@ -36,28 +36,28 @@ enum class Record{ CHECKPOINT, }; -// A record to read, and which kind it is. -struct WireInput{ - std::string_view name; - Record record = Record::STEP; - std::string_view json; -}; - // What a read gives. using ReadRecord = std::variant; // "" when the record read is as expected, else what differs. using ReadCheck = std::string (*)(const ReadRecord& record); -// What reading it gives: a record the check accepts, or a rejection. -struct WireExpectation{ - ReadCheck check = nullptr; - bool rejected = false; -}; - struct WireCase{ - WireInput input; - WireExpectation expectation; + // A record to read, and which kind it is. + struct Input{ + std::string_view name; + Record record = Record::STEP; + std::string_view json; + }; + + // What reading it gives: a record the check accepts, or a rejection. + struct Expectation{ + ReadCheck check = nullptr; + bool rejected = false; + }; + + Input input; + Expectation expectation; }; std::string expect(bool ok, std::string_view what){ @@ -134,6 +134,47 @@ const WireCase CASES[] = { const DeclaredPose start = ZoneDeclared{.place = "HotelZ", .spot = std::nullopt, .heading = std::nullopt}; return expect(checkpoint.start == start && checkpoint.steps.size() == 1 && checkpoint.steps[0].kind == StoryStepKind::MASH, "a zone start and one scene"); }}}, + {.input = {.name = "step opens gates", .json = R"({"id":"unlock","kind":"talk","gates_after":{"opened":["SilphCo_5F/door_1"],"switches":{"mansion":true}}})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryStep& step = step_of(record); + GateChange expected; + expected.opened.insert("SilphCo_5F/door_1"); + expected.switches["mansion"] = true; + return expect(step.gates_after && *step.gates_after == expected, "door_1 opened and the mansion switch on"); + }}}, + {.input = {.name = "step with no gates", .json = R"({"id":"plain","kind":"talk"})"}, .expectation = {.check = [](const ReadRecord& record){ + return expect(!step_of(record).gates_after, "no gate change"); + }}}, + {.input = {.name = "flags: given after a step, held at the start", .record = Record::CHECKPOINT, .json = R"({"id":"16.02","title":"Silph","start_flags":["has_pass"],"events":[{"id":"a","kind":"talk","flags_after":["card_key_held"]},{"id":"b","kind":"talk"}]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + return expect( + checkpoint.start_flags == std::vector{"has_pass"} + && checkpoint.steps[0].flags_after == std::vector{"card_key_held"} + && checkpoint.steps[1].flags_after.empty(), + "start_flags and flags_after" + ); + }}}, + {.input = {.name = "gate change with an unknown field", .json = R"({"id":"x","kind":"talk","gates_after":{"closed":["a/b"]}})"}, .expectation = {.rejected = true}}, + {.input = {.name = "checkpoint gate state", .record = Record::CHECKPOINT, .json = R"({"id":"16.02","title":"Silph","start_gates":{"opened":["SilphCo_5F/door_1"]},"events":[{"id":"a","kind":"talk","gates_after":{"opened":["SilphCo_5F/door_2"]}},{"id":"b","kind":"talk","gates_after":{"switches":{"mansion":true}}},{"id":"c","kind":"talk"}]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + if (!checkpoint.start_gates || checkpoint.start_gates->opened.size() != 1){ + return std::string("Expected start_gates with door_1 open."); + } + const GateState none = checkpoint_gates(checkpoint, 0); + const GateState first = checkpoint_gates(checkpoint, 1); + const GateState all = checkpoint_gates(checkpoint, 3); + if (!(none == *checkpoint.start_gates) || first.opened.size() != 2 || first.switch_on("mansion")){ + return std::string("Expected the start, then door_2 as well after one step."); + } + if (!all.switch_on("mansion") || !(checkpoint_gates(checkpoint, 99) == all)){ + return std::string("Expected the switch on after the steps, and past the end the same."); + } + const JsonValue written = write_gate_state(all); + return expect(read_gate_state(written, "round trip") == all, "the gate state to read back as written"); + }}}, + {.input = {.name = "checkpoint without gates", .record = Record::CHECKPOINT, .json = R"({"id":"x","title":"X","events":[{"id":"a","kind":"talk"}]})"}, .expectation = {.check = [](const ReadRecord& record){ + const StoryCheckpoint& checkpoint = std::get(record); + return expect(!checkpoint.start_gates && checkpoint_gates(checkpoint, 1) == GateState(), "no start gates and nothing open"); + }}}, {.input = {.name = "ordered checkpoint", .record = Record::CHECKPOINT, .json = R"({"id":"00.05","title":"Parcel","events":[ {"id":"first","kind":"talk"}, {"id":"second","kind":"scene"} ]})"}, .expectation = {.check = [](const ReadRecord& record){ const StoryCheckpoint& checkpoint = std::get(record); return expect(checkpoint.id == "00.05" && checkpoint.title == "Parcel" && !checkpoint.start && checkpoint.steps.size() == 2 @@ -201,7 +242,7 @@ std::vector test_actions(){ // `input` read. -ReadRecord read_record(const WireInput& input){ +ReadRecord read_record(const WireCase::Input& input){ static const std::vector actions = test_actions(); const JsonValue value = parse_json(std::string(input.json)); switch (input.record){ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.cpp new file mode 100644 index 0000000000..926483bfb0 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.cpp @@ -0,0 +1,39 @@ +/* Screen Observation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_ScreenObservation.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +ScreenObservation screen_observation(const ScreenEvents& events){ + using EngineEvent = PokemonAutomation::ScreenEvent; + ScreenObservation look; + const std::pair same[] = { + {ScreenEvent::FADE_BLACK, EngineEvent::FADE_BLACK}, + {ScreenEvent::FADE_WHITE, EngineEvent::FADE_WHITE}, + {ScreenEvent::DIALOG_BOX, EngineEvent::TEXT_BOX}, + {ScreenEvent::CHOICE_BOX, EngineEvent::TEXT_BOX}, + {ScreenEvent::BATTLE_STARTED, EngineEvent::BATTLE}, + {ScreenEvent::PLAYER_CAN_MOVE, EngineEvent::CAN_MOVE}, + {ScreenEvent::SCREEN_STILL, EngineEvent::STILL}, + {ScreenEvent::CHOICE_BOX, EngineEvent::CHOICE_BOX}, + {ScreenEvent::INTERACT_PROMPT, EngineEvent::INTERACT_PROMPT}, + }; + for (const auto& [event, engine_event] : same){ + if (events.has(event)){ + look.events.add(engine_event); + } + } + return look; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.h new file mode 100644 index 0000000000..673d91c72c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.h @@ -0,0 +1,29 @@ +/* Screen Observation + * + * From: https://github.com/PokemonAutomation/ + * + * Bridges a ScreenEventObserver (Pokemon::ScreenEvents) to the story + * engine's look (ScreenObservation). + * + */ + +#ifndef PokemonAutomation_Pokemon_ScreenObservation_H +#define PokemonAutomation_Pokemon_ScreenObservation_H + +#include "CommonTools/ScreenMachine/ScreenObservation.h" +#include "Pokemon/AutoStory/Pokemon_ScreenEventTypes.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A ScreenEventObserver's events as one look for the story engine: +// DIALOG_BOX is TEXT_BOX; CHOICE_BOX adds TEXT_BOX; BATTLE_STARTED is +// BATTLE; PLAYER_CAN_MOVE is CAN_MOVE; SCREEN_STILL is STILL; the fades +// and INTERACT_PROMPT keep their names. No time and no frame. +ScreenObservation screen_observation(const ScreenEvents& events); + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp index 1a208e8862..7dfd736896 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEnginePolicy_Tests.cpp @@ -83,29 +83,29 @@ StoryGame engine_game(std::optional candies){ -// One engine run of 00.31 in `phase`, the player ending on `end_map`. -struct EngineInput{ - std::string_view name; - std::string_view phase; - HashRecord hash = HashRecord::MATCHING; - std::string_view steps = TALK_STEPS; - // Where the talk leaves the player; empty: the talk opens no text. - std::string_view end_map = "RocketHideout_B3F"; - std::optional candies = 2; -}; +struct EngineCase{ + // One engine run of 00.31 in `phase`, the player ending on `end_map`. + struct Input{ + std::string_view name; + std::string_view phase; + HashRecord hash = HashRecord::MATCHING; + std::string_view steps = TALK_STEPS; + // Where the talk leaves the player; empty: the talk opens no text. + std::string_view end_map = "RocketHideout_B3F"; + std::optional candies = 2; + }; -// The save mode chosen, the verdict, whether the game saved (each save -// logs "[Test] save") and a line the run logged. -struct EngineExpectation{ - StorySaveMode mode = StorySaveMode::NONE; - CheckpointVerdict verdict = CheckpointVerdict::PASSED; - size_t saves = 0; - std::string_view line = {}; -}; + // The save mode chosen, the verdict, whether the game saved (each save + // logs "[Test] save") and a line the run logged. + struct Expectation{ + StorySaveMode mode = StorySaveMode::NONE; + CheckpointVerdict verdict = CheckpointVerdict::PASSED; + size_t saves = 0; + std::string_view line = {}; + }; -struct EngineCase{ - EngineInput input; - EngineExpectation expectation; + Input input; + Expectation expectation; }; const EngineCase ENGINE_CASES[] = { @@ -201,23 +201,23 @@ class StoryEngineSaveTest : public UnitTest{ -// Two checkpoints' events, hashed with the built-in actions. -struct HashInput{ - std::string_view name; - std::string_view a; - std::string_view b; -}; +struct HashCase{ + // Two checkpoints' events, hashed with the built-in actions. + struct Input{ + std::string_view name; + std::string_view a; + std::string_view b; + }; -// Whether they hash the same, and `a`'s hash when pinned: a change to it -// means every recorded verification goes stale. -struct HashExpectation{ - bool same = true; - std::optional hash_a = std::nullopt; -}; + // Whether they hash the same, and `a`'s hash when pinned: a change to it + // means every recorded verification goes stale. + struct Expectation{ + bool same = true; + std::optional hash_a = std::nullopt; + }; -struct HashCase{ - HashInput input; - HashExpectation expectation; + Input input; + Expectation expectation; }; inline constexpr std::string_view ROUTE_B3F = R"([{"id": "go", "kind": "route", "args": {"target": {"map": "RocketHideout_B3F", "tiles": [[12, 13]]}}}])"; @@ -271,23 +271,23 @@ class StoryStepsHashTest : public UnitTest{ -// A checkpoint's "metadata", read. -struct MetadataInput{ - std::string_view name; - std::string_view metadata; -}; +struct MetadataCase{ + // A checkpoint's "metadata", read. + struct Input{ + std::string_view name; + std::string_view metadata; + }; -// The error the read throws (contained), or what it read. -struct MetadataExpectation{ - std::string_view error = {}; - StoryPhase phase = StoryPhase::TESTING; - std::string_view steps_hash = {}; - size_t items = 0; -}; + // The error the read throws (contained), or what it read. + struct Expectation{ + std::string_view error = {}; + StoryPhase phase = StoryPhase::TESTING; + std::string_view steps_hash = {}; + size_t items = 0; + }; -struct MetadataCase{ - MetadataInput input; - MetadataExpectation expectation; + Input input; + Expectation expectation; }; const MetadataCase METADATA_CASES[] = { @@ -341,21 +341,21 @@ class StoryMetadataTest : public UnitTest{ -// What a look showed, classified by ScreenMachine states that match on -// observations. -struct ScreenInput{ - std::string_view name; - std::vector events; -}; +struct ScreenCase{ + // What a look showed, classified by ScreenMachine states that match on + // observations. + struct Input{ + std::string_view name; + std::vector events; + }; -// The state matched; none when no state did. -struct ScreenExpectation{ - std::optional state = std::nullopt; -}; + // The state matched; none when no state did. + struct Expectation{ + std::optional state = std::nullopt; + }; -struct ScreenCase{ - ScreenInput input; - ScreenExpectation expectation; + Input input; + Expectation expectation; }; const ScreenCase SCREEN_CASES[] = { diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp index d272a19648..e15bd54774 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngineRuns_Tests.cpp @@ -585,22 +585,22 @@ std::string segment_no_reload_for_console_only(CancellableScope& scope){ // Gap 7: the first checkpoint is retried after a reload; one after it // only when the one before saved at its end (#329). -struct SegmentInput{ - std::string_view name; - StoryPhase phase; - // Which checkpoint fails once: 0 or 1. - size_t flaky = 0; -}; +struct SegmentCase{ + struct Input{ + std::string_view name; + StoryPhase phase; + // Which checkpoint fails once: 0 or 1. + size_t flaky = 0; + }; -struct SegmentExpectation{ - bool completed = false; - size_t reloads = 0; - size_t saves = 0; -}; + struct Expectation{ + bool completed = false; + size_t reloads = 0; + size_t saves = 0; + }; -struct SegmentCase{ - SegmentInput input; - SegmentExpectation expectation; + Input input; + Expectation expectation; }; const SegmentCase SEGMENT_CASES[] = { @@ -675,20 +675,20 @@ std::string verify_saves_after_all_passed(CancellableScope& scope){ } -// One check above, by name. -struct RunsInput{ - std::string_view name; - std::string (*check)(CancellableScope& scope); -}; +struct RunsCase{ + // One check above, by name. + struct Input{ + std::string_view name; + std::string (*check)(CancellableScope& scope); + }; -// The check's error: none. -struct RunsExpectation{ - std::string_view error = {}; -}; + // The check's error: none. + struct Expectation{ + std::string_view error = {}; + }; -struct RunsCase{ - RunsInput input; - RunsExpectation expectation; + Input input; + Expectation expectation; }; const RunsCase RUNS_CASES[] = { diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp index 4548921c9b..4e16d05e13 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_StoryEngine_Tests.cpp @@ -127,24 +127,24 @@ StoryStep make_step(StoryStepKind kind, std::string action, StoryActionArgs args -// A step checked and, when it lints clean, dispatched on a backend that -// shows talk text once, then the overworld. -struct RegistryInput{ - std::string_view name; - StoryStep step; -}; - -// The lint errors joined by "; ", then (for a clean step) the failure and -// the inputs sent. -struct RegistryExpectation{ - std::string_view lint = {}; - std::string_view failure = {}; - std::string_view inputs = {}; -}; - struct RegistryCase{ - RegistryInput input; - RegistryExpectation expectation; + // A step checked and, when it lints clean, dispatched on a backend that + // shows talk text once, then the overworld. + struct Input{ + std::string_view name; + StoryStep step; + }; + + // The lint errors joined by "; ", then (for a clean step) the failure and + // the inputs sent. + struct Expectation{ + std::string_view lint = {}; + std::string_view failure = {}; + std::string_view inputs = {}; + }; + + Input input; + Expectation expectation; }; const RegistryCase REGISTRY_CASES[] = { @@ -208,26 +208,26 @@ class StoryActionRegistryTest : public UnitTest{ -// One step, read from JSON, run by the step runner on a backend that -// shows the overworld, with `flags` set and the "door_open" reader -// reading `door_open`. -struct RunnerInput{ - std::string_view name; - std::string_view step; - std::vector flags = {}; - std::optional door_open = std::nullopt; -}; - -// The failure, a line the run logged and the map of the outcome's pose. -struct RunnerExpectation{ - std::string_view failure = {}; - std::string_view line = {}; - std::string_view pose_map = {}; -}; - struct RunnerCase{ - RunnerInput input; - RunnerExpectation expectation; + // One step, read from JSON, run by the step runner on a backend that + // shows the overworld, with `flags` set and the "door_open" reader + // reading `door_open`. + struct Input{ + std::string_view name; + std::string_view step; + std::vector flags = {}; + std::optional door_open = std::nullopt; + }; + + // The failure, a line the run logged and the map of the outcome's pose. + struct Expectation{ + std::string_view failure = {}; + std::string_view line = {}; + std::string_view pose_map = {}; + }; + + Input input; + Expectation expectation; }; const RunnerCase RUNNER_CASES[] = { @@ -283,20 +283,20 @@ class StoryStepRunnerTest : public UnitTest{ -// take_warp north to B3F, from B4F, on a scripted game. -struct WarpInput{ - std::string_view name; - std::vector> looks; -}; - -// How take_warp ended: "" for arrived. -struct WarpExpectation{ - std::string_view failure = {}; -}; - struct WarpCase{ - WarpInput input; - WarpExpectation expectation; + // take_warp north to B3F, from B4F, on a scripted game. + struct Input{ + std::string_view name; + std::vector> looks; + }; + + // How take_warp ended: "" for arrived. + struct Expectation{ + std::string_view failure = {}; + }; + + Input input; + Expectation expectation; }; const WarpCase WARP_CASES[] = { diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.cpp index 9f32440e80..3dabf2da1d 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.cpp @@ -20,6 +20,20 @@ std::string pose_text(const ZonePose& pose){ return std::format("zone {}", (pose.zone.empty() ? std::string("unknown") : pose.zone)); } +double direction_degrees(Direction direction){ + switch (direction){ + case Direction::NORTH: + return 0; + case Direction::EAST: + return 90; + case Direction::SOUTH: + return 180; + case Direction::WEST: + return -90; + } + return 0; +} + } // namespace Pokemon diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.h b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.h index 69d698ec82..2931604251 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Engine/Pokemon_ZonePose.h @@ -13,6 +13,7 @@ #include #include "Pokemon/AutoStory/Types/Pokemon_DeclaredPose.h" +#include "Pokemon/Navigation/Pokemon_Grid.h" #include "Pokemon_StoryPoseConcept.h" namespace PokemonAutomation{ @@ -32,6 +33,9 @@ bool pose_matches(const ZonePose& actual, const ZonePose& target); // "zone LumioseCity". std::string pose_text(const ZonePose& pose); +// `direction` as degrees clockwise of straight on (0, 90, 180, -90). +double direction_degrees(Direction direction); + // No tiles: no built-in tile walks. It declares a place, whose name is the // zone; the spot and heading wait for a position reader. template <> diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp index 453a975516..044c77b930 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStoryStats_Tests.cpp @@ -18,23 +18,23 @@ namespace Pokemon{ namespace{ -// Counts added to fresh stats, in order. -struct StoryCountsInput{ - std::string name; - std::vector added; -}; - -// The stats after them: counts add up rather than replace. -struct StoryCountsExpectation{ - uint64_t segments; - uint64_t checkpoints; - uint64_t resets; -}; - // Counts recorded into the AutoStory stats and the totals they must reach. struct StoryCountsCase{ - StoryCountsInput input; - StoryCountsExpectation expectation; + // Counts added to fresh stats, in order. + struct Input{ + std::string name; + std::vector added; + }; + + // The stats after them: counts add up rather than replace. + struct Expectation{ + uint64_t segments; + uint64_t checkpoints; + uint64_t resets; + }; + + Input input; + Expectation expectation; }; class Test_StoryCounts : public UnitTest{ @@ -49,7 +49,7 @@ class Test_StoryCounts : public UnitTest{ for (const StoryRunCounts& counts : m_case.input.added){ record_story_counts(counts, stats); } - const StoryCountsExpectation& expected = m_case.expectation; + const StoryCountsCase::Expectation& expected = m_case.expectation; if (stats.m_segment != expected.segments || stats.m_checkpoint != expected.checkpoints || stats.m_reset != expected.resets){ return std::format( "Expected {} segments, {} checkpoints and {} resets, got {}, {} and {}", diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h index 906540637b..0e51776983 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -19,7 +19,6 @@ #include "Engine/Pokemon_StoryEngine_Tests.h" #include "Pokemon/Options/Pokemon_StoryRangeOptions_Tests.h" #include "Pokemon_AutoStorySelect_Tests.h" -#include "Pokemon_StoryRun_Tests.h" #include "Pokemon_AutoStoryStats_Tests.h" #include "Pokemon_Interrupts_Tests.h" #include "Pokemon_SceneJudges_Tests.h" @@ -28,6 +27,7 @@ #include "Pokemon_StoryEvents_Tests.h" #include "Pokemon_StoryInterrupts_Tests.h" #include "Pokemon_StoryLog_Tests.h" +#include "Pokemon_StoryRun_Tests.h" #include "Pokemon_StorySavePolicy_Tests.h" #include "Pokemon_StorySegments_Tests.h" #include "Pokemon_StoryStepExecutor_Tests.h" diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h index a4dd2ac915..7a2ac6ac4e 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_FadeProfiles.h @@ -2,7 +2,8 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_Transitions.h, unchanged; it includes this header. + * Per-game fade thresholds (FadeProfile) and the transition kinds the tracker + * reports. Their definitions are in Pokemon_Transitions.cpp. * */ @@ -10,12 +11,8 @@ #define PokemonAutomation_Pokemon_FadeProfiles_H #include -#include -#include #include #include "Common/Cpp/Time.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -64,7 +61,7 @@ struct FadeProfile{ }; // BDSP. The uniform tier is the shared walk's (FADE_MAX_STDDEV_SUM, the -// Oreburgh Gate's textured floor is no fade, lab-B 2026-11-08); the partial +// Oreburgh Gate's textured floor is no fade); the partial // tier is run_into_door()'s 60, which caught the doorway's dim fade frames. // A cave mouth's fade is dim (45 to 64 a channel), hence the dark sum of 225. // The flash and white-fade holds are provisional: no console frames of an diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h index c574b2503f..ffe9602115 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_InterruptHandlers.h @@ -2,7 +2,8 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_StoryInterrupts.h, unchanged; it includes this header. + * The table of a game's interrupt handlers and the screen look they read. + * Pokemon_StoryInterrupts.h builds on it. * */ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp index 53aedfbe7c..57740f5820 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts.cpp @@ -5,7 +5,9 @@ */ #include +#include #include +#include #include "Pokemon_Interrupts.h" namespace PokemonAutomation{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp index f321c506ab..111d42035f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Interrupts_Tests.cpp @@ -8,7 +8,6 @@ */ #include -#include #include #include #include @@ -18,6 +17,7 @@ #include "Pokemon_Interrupts.h" #include "Pokemon_Interrupts_Tests.h" #include "Pokemon_ScreenEvents.h" +#include "Pokemon_TestExpect.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -28,13 +28,6 @@ using namespace std::chrono_literals; const WallClock T0 = WallClock() + std::chrono::hours(1); -UnitTestResult expect_equal(const std::string& what, const std::string& got, const std::string& expected){ - if (got == expected){ - return true; - } - return std::format("{}: expected \"{}\", got \"{}\"", what, expected, got); -} - // One frame of a synthetic scene: its events, at `ms` after T0. struct Frame{ int ms; @@ -186,17 +179,16 @@ UnitTestResult test_watcher_log(){ } -struct InterruptsInput{ - std::string name; - std::function body; -}; - -struct InterruptsExpectation{ -}; - struct InterruptsCase{ - InterruptsInput input; - InterruptsExpectation expectation; + struct Input{ + std::string name; + UnitTestResult (*body)(); + }; + struct Expectation{ + }; + + Input input; + Expectation expectation; }; class Test_Interrupts : public UnitTest{ @@ -214,23 +206,22 @@ class Test_Interrupts : public UnitTest{ }; -// A synthetic scene, and the window of it to judge. -struct ClassifyInput{ - std::string name; - std::vector frames; - int until_ms = 0; - InterruptKnobs knobs = {}; - int window_from_ms = 0; -}; - -struct ClassifyExpectation{ - // describe(verdict, T0). - std::string verdict; -}; - struct ClassifyCase{ - ClassifyInput input; - ClassifyExpectation expectation; + // A synthetic scene, and the window of it to judge. + struct Input{ + std::string name; + std::vector frames; + int until_ms = 0; + InterruptKnobs knobs = {}; + int window_from_ms = 0; + }; + struct Expectation{ + // describe(verdict, T0). + std::string verdict; + }; + + Input input; + Expectation expectation; }; class Test_InterruptClassify : public UnitTest{ @@ -240,7 +231,7 @@ class Test_InterruptClassify : public UnitTest{ , m_case(std::move(test_case)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const ClassifyInput& input = m_case.input; + const ClassifyCase::Input& input = m_case.input; const ScreenEventLog log = log_of(input.frames, input.until_ms); const InterruptWindow window{T0 + Milliseconds(input.window_from_ms), T0 + Milliseconds(input.until_ms)}; const InterruptVerdict verdict = classify_interrupt(log, window, input.knobs); @@ -252,22 +243,21 @@ class Test_InterruptClassify : public UnitTest{ }; -// A synthetic scene, classified over all of it, and the lags to time it. -struct StepTimeInput{ - std::string name; - std::vector frames; - int until_ms = 0; - std::vector lags; -}; - -struct StepTimeExpectation{ - // "+700 ms" from T0, or "none". - std::string step; -}; - struct StepTimeCase{ - StepTimeInput input; - StepTimeExpectation expectation; + // A synthetic scene, classified over all of it, and the lags to time it. + struct Input{ + std::string name; + std::vector frames; + int until_ms = 0; + std::vector lags; + }; + struct Expectation{ + // "+700 ms" from T0, or "none". + std::string step; + }; + + Input input; + Expectation expectation; }; class Test_InterruptStepTime : public UnitTest{ @@ -277,7 +267,7 @@ class Test_InterruptStepTime : public UnitTest{ , m_case(std::move(test_case)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const StepTimeInput& input = m_case.input; + const StepTimeCase::Input& input = m_case.input; const InterruptVerdict verdict = classify_interrupt(log_of(input.frames, input.until_ms), whole(input.until_ms), {}); const std::optional step = interrupt_step_time(verdict, input.lags); const std::string got = step diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp index 4ded229245..bc587ba860 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.cpp @@ -33,37 +33,37 @@ std::string describe(const WarpSeen& seen){ } -SceneMove TalkOver::look(const ScreenEvents& look, WallClock now){ - if (look.has(ScreenEvent::BATTLE_STARTED)){ - m_quiet_since = WallClock::max(); - m_calm_since = WallClock::max(); +SceneMove TalkOver::look(const ScreenEvents& events, WallClock now){ + if (events.has(ScreenEvent::BATTLE_STARTED)){ + m_quiet_since.reset(); + m_calm_since.reset(); return SceneMove::BATTLE; } - m_fade_showing = fade_in(look); + m_fade_showing = fade_in(events); if (m_fade_showing != WarpFade::NONE){ m_fade = m_fade_showing; } - m_banner |= look.has(ScreenEvent::LOCATION_BANNER); - const bool box = look.has(ScreenEvent::DIALOG_BOX); + m_banner |= events.has(ScreenEvent::LOCATION_BANNER); + const bool box = events.has(ScreenEvent::DIALOG_BOX); // A fade is never calm: BDSP's overworld reads a black frame as no // box, and black stays still, so a closing fade counted as quiet and - // ended Mom's scene as it went down (lab-B 2026-11-09 14:33). + // ended the scene as it went down. const bool calm = !box && m_fade_showing == WarpFade::NONE && - look.has(ScreenEvent::PLAYER_CAN_MOVE) && warped(); - const bool quiet = calm && look.has(ScreenEvent::SCREEN_STILL); + events.has(ScreenEvent::PLAYER_CAN_MOVE) && warped(); + const bool quiet = calm && events.has(ScreenEvent::SCREEN_STILL); if (!calm){ - m_calm_since = WallClock::max(); - }else if (m_calm_since == WallClock::max()){ + m_calm_since.reset(); + }else if (!m_calm_since.has_value()){ m_calm_since = now; } if (!quiet){ - m_quiet_since = WallClock::max(); - }else if (m_quiet_since == WallClock::max()){ + m_quiet_since.reset(); + }else if (!m_quiet_since.has_value()){ m_quiet_since = now; } const bool over = - (quiet && now - m_quiet_since >= TALK_OVER_QUIET) || - (calm && now - m_calm_since >= TALK_OVER_CALM); + (quiet && now - *m_quiet_since >= TALK_OVER_QUIET) || + (calm && now - *m_calm_since >= TALK_OVER_CALM); if (over && m_rule.end_on_quiet){ return SceneMove::DONE; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h index 908dcaa39c..c3d3e44593 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges.h @@ -13,6 +13,7 @@ #ifndef PokemonAutomation_Pokemon_SceneJudges_H #define PokemonAutomation_Pokemon_SceneJudges_H +#include #include #include "Common/Cpp/Time.h" #include "Pokemon_ScreenEvents.h" @@ -51,18 +52,17 @@ enum class SceneMove{ // What ends a talk-over, besides the quiet. struct TalkOverRule{ // A map change must come first: a fade or the banner. Only the quiet - // after it counts: r30's scene went quiet for 5 s before the fade home. + // after it counts: a scene can go quiet for 5 s before the fade home. bool warp = false; // False when a battle is to follow (a trainer's lines pause for more - // than 4 s before it, r210d): no quiet ends the talk then. + // than 4 s before it): no quiet ends the talk then. bool end_on_quiet = true; }; // The overworld with no box and a still screen this long ends it: a scene -// pauses while someone walks off (Dawn and Barry after Rowan leaves, r23), -// a scripted walk-in ran 5 s with no text before Mom spoke (r31), and -// Roark's badge speech pauses for the fanfare (lab-B 2026-10-31 09:45 and -// 2026-11-08 15:06). The clock is the last look that was not quiet. +// pauses while someone walks off, a scripted walk-in can run 5 s with no +// text before someone speaks, and a speech pauses for a fanfare. The clock +// is the last look that was not quiet. constexpr Milliseconds TALK_OVER_QUIET = Milliseconds(5000); // The overworld with no box this long ends it, still or not: wanderers or // grass can keep the screen from ever being still. @@ -80,7 +80,7 @@ class TalkOver{ : m_rule(rule) {} - SceneMove look(const ScreenEvents& look, WallClock now); + SceneMove look(const ScreenEvents& events, WallClock now); // Whether the warp the rule asks for has shown (true without one). bool warped() const; @@ -93,8 +93,9 @@ class TalkOver{ WarpFade m_fade = WarpFade::NONE; WarpFade m_fade_showing = WarpFade::NONE; bool m_banner = false; - WallClock m_quiet_since = WallClock::max(); - WallClock m_calm_since = WallClock::max(); + // Since when the screen has been quiet, and calm; none when it is not. + std::optional m_quiet_since; + std::optional m_calm_since; }; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp index 7073e27efb..de8fdc5bc2 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_SceneJudges_Tests.cpp @@ -7,13 +7,13 @@ */ #include -#include #include #include #include #include "Common/Cpp/TestRunners/UnitTest.h" #include "Pokemon_SceneJudges.h" #include "Pokemon_SceneJudges_Tests.h" +#include "Pokemon_TestExpect.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -22,13 +22,6 @@ namespace{ using namespace std::chrono_literals; -UnitTestResult expect_equal(const std::string& what, const std::string& got, const std::string& expected){ - if (got == expected){ - return true; - } - return std::format("{}: expected \"{}\", got \"{}\"", what, expected, got); -} - UnitTestResult test_warp_seen(){ WarpSeen seen = note_warp({}, {ScreenEvent::DIALOG_BOX}, "Route 203"); @@ -93,9 +86,8 @@ UnitTestResult test_talk_over(){ SceneMove::DONE, 6}, {"no quiet ends a talk before a battle", {.end_on_quiet = false}, repeat(QUIET, 30), SceneMove::DONE, -1}, {"a battle", {.end_on_quiet = false}, concat(repeat(QUIET, 6), {ScreenEvents{ScreenEvent::BATTLE_STARTED}}), SceneMove::BATTLE, 6}, - // Mom's Running Shoes scene (lab-B 2026-11-09 14:33): quiet, then - // the scene's closing fade. It ended at the fade's start and the - // next step's input landed in the fade. + // Quiet, then the scene's closing fade: the scene must not end at + // the fade's start, or the next step's input lands in the fade. {"a closing fade starts the quiet over", {}, concat(concat(repeat(QUIET, 4), repeat(FADED, 3)), repeat(QUIET, 8)), SceneMove::DONE, 12}, @@ -113,17 +105,17 @@ UnitTestResult test_talk_over(){ } -struct SceneJudgesInput{ - std::string name; - std::function body; -}; +struct SceneJudgesCase{ + struct Input{ + std::string name; + UnitTestResult (*body)(); + }; -struct SceneJudgesExpectation{ -}; + struct Expectation{ + }; -struct SceneJudgesCase{ - SceneJudgesInput input; - SceneJudgesExpectation expectation; + Input input; + Expectation expectation; }; class Test_SceneJudges : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp index 82aae9bf03..f7c7e32402 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_ScreenEvents_Tests.cpp @@ -131,17 +131,16 @@ UnitTestResult test_watcher(){ } -struct ScreenEventsInput{ - std::string name; - std::function body; -}; - -struct ScreenEventsExpectation{ -}; - struct ScreenEventsCase{ - ScreenEventsInput input; - ScreenEventsExpectation expectation; + struct Input{ + std::string name; + std::function body; + }; + struct Expectation{ + }; + + Input input; + Expectation expectation; }; class Test_ScreenEvents : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp index 5ecbd69f35..2e7376990e 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.cpp @@ -107,13 +107,25 @@ Outcome TableExecutor::run(const StoryStep& step, RunState& state){ } try{ Outcome outcome = run_action(step, state); - if (outcome.succeeded() || !cleared_after_failure(step, state, cleared)){ + if (outcome.succeeded()){ + return outcome; + } + switch (look_after_failure(step, state, cleared)){ + case AfterFailure::RETRY: + continue; + case AfterFailure::GAME_NOT_RUNNING: + return outcome_game_not_running(); + case AfterFailure::KEEP: return outcome; } }catch (OperationFailedException& e){ - if (cleared_after_failure(step, state, cleared)){ + const AfterFailure after = look_after_failure(step, state, cleared); + if (after == AfterFailure::RETRY){ continue; } + if (after == AfterFailure::GAME_NOT_RUNNING){ + return outcome_game_not_running(); + } if (m_guard.stops_on_failure(step)){ throw; } @@ -153,11 +165,15 @@ std::optional TableExecutor::clear_interrupts(const StoryStep& step, Ru return std::nullopt; } -// Whether an interrupt explains the failure of `step`: one showed after -// it failed and is cleared, so the step runs again. -bool TableExecutor::cleared_after_failure(const StoryStep& step, RunState& state, size_t& cleared){ +// What explains the failure of `step`, if anything: an interrupt that +// showed after it failed and is cleared, or the game not running. +AfterFailure TableExecutor::look_after_failure(const StoryStep& step, RunState& state, size_t& cleared){ const size_t before = cleared; - return !clear_interrupts(step, state, cleared) && cleared > before; + const std::optional failed = clear_interrupts(step, state, cleared); + if (failed){ + return failed->failure == GAME_NOT_RUNNING ? AfterFailure::GAME_NOT_RUNNING : AfterFailure::KEEP; + } + return cleared > before ? AfterFailure::RETRY : AfterFailure::KEEP; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h index 3e2792a695..23711eb83c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions.h @@ -23,7 +23,6 @@ #include #include #include -#include #include #include #include @@ -109,6 +108,17 @@ class StepGuard{ }; +// What a look at the screen after a step failed found. +enum class AfterFailure{ + // Nothing explains the failure: it is the step's own. + KEEP, + // An interrupt explains it and is cleared: the step runs again. + RETRY, + // The game is not running (the Switch's HOME menu): the failure is + // that, and the step is not run again. + GAME_NOT_RUNNING, +}; + // Runs each step with the table's action for it, inside `guard`. class TableExecutor : public StoryStepExecutor{ public: @@ -138,7 +148,7 @@ class TableExecutor : public StoryStepExecutor{ private: std::optional clear_interrupts(const StoryStep& step, RunState& state, size_t& cleared); - bool cleared_after_failure(const StoryStep& step, RunState& state, size_t& cleared); + AfterFailure look_after_failure(const StoryStep& step, RunState& state, size_t& cleared); const StoryActionTable& m_table; StepGuard& m_guard; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp index 4e3b98983a..a4e8020210 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.cpp @@ -253,18 +253,18 @@ UnitTestResult test_guard_stop_rethrows(){ } -struct StoryActionsInput{ - std::string_view name; - UnitTestResult (*test)(); -}; +struct StoryActionsCase{ + struct Input{ + std::string_view name; + UnitTestResult (*test)(); + }; -struct StoryActionsExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct StoryActionsCase{ - StoryActionsInput input; - StoryActionsExpectation expectation; + Input input; + Expectation expectation; }; class Test_StoryActions : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h index d3593d58f6..6f6f908d18 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryActions_Tests.h @@ -13,7 +13,7 @@ namespace PokemonAutomation{ namespace Pokemon{ -// Registers unit tests for story action tables, the variant parser and the table executor. +// Registers unit tests for story action tables, checkpoint lint and the table executor. void add_tests_StoryActions(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h index 48f20e317e..ffda3cee12 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvent.h @@ -10,6 +10,7 @@ #define PokemonAutomation_Pokemon_StoryEvent_H #include +#include #include #include #include @@ -66,6 +67,9 @@ struct Event{ std::string why; // Skipped when all of these hold (and there is at least one). std::vector skip_if; + // Run when the event is skipped: what the event leaves in the run + // state that is already so (a door it opens, a flag it sets). + std::function when_skipped; // Must hold before `act`; a failure is "require_failed". std::vector require; Act act; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp index 8afcdfe404..deb4003d8f 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents.cpp @@ -412,6 +412,9 @@ CheckpointReport run_checkpoint(RunState& state, Checkpoint& checkpoint, EventLo EventRun run{checkpoint, c + 1, event, state, log, std::vector(event.recoveries.size(), 0), 0}; if (already_done(event, state)){ log_status("skipped", run); + if (event.when_skipped){ + event.when_skipped(state); + } report.events_skipped++; continue; } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp index a1d485644e..cafb66cd54 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryEvents_Tests.cpp @@ -611,18 +611,18 @@ UnitTestResult test_lint(){ } -struct StoryEventInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct StoryEventTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct StoryEventExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct StoryEventTestCase{ - StoryEventInput input; - StoryEventExpectation expectation; + Input input; + Expectation expectation; }; class Test_StoryEvents : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp index 0012c5d2eb..8c50b18d37 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.cpp @@ -10,6 +10,7 @@ #include #include #include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" #include "Pokemon_StoryInterrupts.h" namespace PokemonAutomation{ @@ -146,6 +147,17 @@ std::string describe(const ScreenSettle& settle){ } +// The handler's outcome. A handler drives the console, which it can lose: +// that is a failed outcome too, not an exception for the executor's caller. +Outcome run_handler(const InterruptHandler& handler, const InterruptVerdict& verdict, RunState& state){ + try{ + return handler.handle(verdict, state); + }catch (OperationFailedException& e){ + return outcome_failed("operation_failed", e.message()); + } +} + + InterruptCheck clear_story_interrupt(const StoryInterrupts& interrupts, const StoryStep& step, RunState& state){ InterruptCheck out; out.verdict = settled_verdict(interrupts, step.kind, out.screen); @@ -171,7 +183,7 @@ InterruptCheck clear_story_interrupt(const StoryInterrupts& interrupts, const St out.outcome = outcome_failed("unhandled_interrupt", std::format("{} before {}", interrupt_kind_name(kind), step.name)); return out; } - const Outcome handled = handler->handle(out.verdict, state); + const Outcome handled = run_handler(*handler, out.verdict, state); if (!handled.succeeded()){ out.outcome = outcome_failed("interrupt_failed", std::format("{}: {}", interrupt_kind_name(kind), to_string(handled))); return out; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h index 2bceba34c6..61945b8459 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts.h @@ -34,17 +34,12 @@ #ifndef PokemonAutomation_Pokemon_StoryInterrupts_H #define PokemonAutomation_Pokemon_StoryInterrupts_H -#include -#include -#include -#include #include -#include +#include "Pokemon_InterruptHandlers.h" #include "Pokemon_Interrupts.h" #include "Pokemon_ScreenEvents.h" #include "Pokemon_StoryEvents.h" #include "Pokemon_StoryStepExecutor.h" -#include "Pokemon_InterruptHandlers.h" namespace PokemonAutomation{ namespace Pokemon{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp index 234e0d926b..e994e11745 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryInterrupts_Tests.cpp @@ -347,8 +347,8 @@ UnitTestResult test_unsettled_before_a_battle(){ } // A battle's opening still playing when a walk step begins: the walk -// before it ended in grass or in a trainer's sight (BDSP fault sweep, 51 -// steps of 00.01-01.11). The looks wait for the battle, past max_looks, +// before it ended in grass or in a trainer's sight. The looks wait for the +// battle, past max_looks, // and its handler clears it before the step. UnitTestResult test_opening_before_a_walk(ScreenLook opening, ScreenLook battle, const std::string& kind, const std::string& handler){ FakeGame game; @@ -492,8 +492,7 @@ UnitTestResult test_screen_before_each_step(){ }); } -// The program started on the HOME menu (lab-B 2026-11-09 15:31: "before -// save: settled overworld", then X on HOME and a 22-tile walk on it). The +// The program started with the game closed and the HOME menu showing. The // screen is told as HOME and the step fails at once, before any input, // and before a step that starts on a battle's opening too. UnitTestResult test_home_menu_before_a_step(){ @@ -568,6 +567,78 @@ UnitTestResult test_home_menu_stops_the_segment(){ return true; } +// A handler that drives the console can lose it. That fails the step as +// interrupt_failed, like a handler that returns a failure: it must not +// escape the executor, and the step is not run. +UnitTestResult test_handler_throws(){ + FakeGame game; + game.screens = {dialog()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers = InterruptHandlerTable(); + interrupts.handlers.add(InterruptKind::DIALOG, InterruptHandler{ + .handle = [&game](const InterruptVerdict&, RunState&) -> Outcome{ + game.trace.push_back("clear dialog"); + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, "the console is gone"); + }, + .pose = InterruptPose::UNCHANGED, + }); + try{ + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk")); + if (run.outcome.failure != "interrupt_failed"){ + return std::format("Expected interrupt_failed, got {}", to_string(run.outcome)); + } + }catch (OperationFailedException& e){ + return std::format("The handler's failure escaped the executor: {}", e.message()); + } + return expect_trace(game, {"look", "clear dialog", "told dialog interrupt_failed: dialog: operation_failed: the console is gone"}); +} + +// The same loss after a step failed, while the executor looks for what +// explains the failure: the step's own failure is kept. +UnitTestResult test_handler_throws_after_a_failure(){ + FakeGame game; + game.screens = {quiet(), dialog()}; + StoryInterrupts interrupts = fake_interrupts(game); + interrupts.handlers = InterruptHandlerTable(); + interrupts.handlers.add(InterruptKind::DIALOG, InterruptHandler{ + .handle = [&game](const InterruptVerdict&, RunState&) -> Outcome{ + game.trace.push_back("clear dialog"); + throw OperationFailedException(ErrorReportMode::NO_ERROR_REPORT, "the console is gone"); + }, + .pose = InterruptPose::UNCHANGED, + }); + try{ + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk"), FakeAction{.failures = 1}); + if (run.outcome.failure != "dialog"){ + return std::format("Expected the step's own failure, got {}", to_string(run.outcome)); + } + }catch (OperationFailedException& e){ + return std::format("The handler's failure escaped the executor: {}", e.message()); + } + return true; +} + +// A step that fails and then shows the HOME menu did not fail on its own: +// the game is not running, so the segment must stop instead of recovering +// or reloading with the game closed. +UnitTestResult test_home_menu_after_a_failed_step(){ + for (bool throws : {false, true}){ + FakeGame game; + game.screens = {quiet(), home_menu()}; + StoryInterrupts interrupts = fake_interrupts(game); + const FakeRun run = run_step(game, interrupts, make(StoryStepKind::ROUTE, "walk"), FakeAction{.failures = 1, .throws = throws}); + if (run.outcome.failure != "game_not_running"){ + return std::format("Expected game_not_running after a step that {} and then showed HOME, got {}", + throws ? "threw" : "failed", to_string(run.outcome)); + } + const size_t runs = static_cast(std::count(game.trace.begin(), game.trace.end(), "run walk")); + if (runs != 1){ + return std::format("Expected the step run once, got {} runs", runs); + } + } + return true; +} + UnitTestResult test_settle_of_a_look(){ struct Row{ std::string name; @@ -592,18 +663,18 @@ UnitTestResult test_settle_of_a_look(){ } -struct StoryInterruptsInput{ - std::string_view name; - UnitTestResult (*test)(); -}; +struct StoryInterruptsCase{ + struct Input{ + std::string_view name; + UnitTestResult (*test)(); + }; -struct StoryInterruptsExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct StoryInterruptsCase{ - StoryInterruptsInput input; - StoryInterruptsExpectation expectation; + Input input; + Expectation expectation; }; class Test_StoryInterrupts : public UnitTest{ @@ -717,6 +788,18 @@ const StoryInterruptsCase STORY_INTERRUPTS_CASES[] = { .input = {.name = "the HOME menu stops the segment", .test = test_home_menu_stops_the_segment}, .expectation = {.description = "no recovery in place, no reload"}, }, + { + .input = {.name = "a handler that throws fails the step", .test = test_handler_throws}, + .expectation = {.description = "interrupt_failed, the step not run, nothing escapes"}, + }, + { + .input = {.name = "a handler that throws after a failed step", .test = test_handler_throws_after_a_failure}, + .expectation = {.description = "the step's own failure, nothing escapes"}, + }, + { + .input = {.name = "the HOME menu after a failed step", .test = test_home_menu_after_a_failed_step}, + .expectation = {.description = "game_not_running instead of the step's failure, run once"}, + }, }; } // namespace diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp index 1cc32c258b..5172022a55 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryLog_Tests.cpp @@ -16,21 +16,21 @@ namespace Pokemon{ namespace{ -// A formatter's line, made when the table is built. -struct StoryLogInput{ - std::string name; - std::string line; -}; - -// The exact line: the lab watcher and the engine tests read these. -struct StoryLogExpectation{ - std::string line; -}; - // One formatter call and the line it must make. struct StoryLogCase{ - StoryLogInput input; - StoryLogExpectation expectation; + // A formatter's line, made when the table is built. + struct Input{ + std::string name; + std::string line; + }; + + // The exact line: the lab watcher and the engine tests read these. + struct Expectation{ + std::string line; + }; + + Input input; + Expectation expectation; }; class Test_StoryLog : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h index b9c0eb53db..d3081a8a8c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPose.h @@ -17,6 +17,8 @@ #include #include #include "Common/Cpp/MoveOnlyFunction.h" +#include "Pokemon/Navigation/Pokemon_GatedTypes.h" +#include "Pokemon/Navigation/Pokemon_GateState.h" #include "Pokemon_StoryLog.h" namespace PokemonAutomation{ @@ -70,8 +72,17 @@ std::string to_string(const Pose& pose); struct RunState{ Pose pose; std::set flags; + // The gates open and the switches on (Pokemon_GateState.h): from the + // checkpoint's start_gates, then each step's gates_after as it is done. + GateState gates; }; +// The rules a plan over `state`'s gates follows: the flag "card_key_held" +// (set after the Card Key is picked up) lets it open card-key gates. +inline GateRules gate_rules_of(const RunState& state){ + return GateRules{.card_key_held = state.flags.contains("card_key_held")}; +} + } // namespace Pokemon diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp index 2b56c6b435..5266a751e7 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryPreflight.cpp @@ -26,6 +26,12 @@ namespace{ // Color bars are seven flat vertical stripes of different colors. constexpr size_t BAR_COUNT = 7; +// Each stripe is sampled in its middle, away from its edges: inset by this +// fraction of its width on each side, and from the top for this fraction of +// the frame's height. +constexpr double BAR_INSET = 0.25; +constexpr double BAR_TOP = 0.1; +constexpr double BAR_HEIGHT = 0.5; // A stripe flatter than this (stddev sum) is one solid color. constexpr double BAR_MAX_STDDEV = 30; // Two stripes this far apart (RGB distance) are different bars. @@ -37,7 +43,7 @@ bool shows_color_bars(const ImageViewRGB32& frame){ std::array bars; for (size_t c = 0; c < BAR_COUNT; c++){ const double width = 1.0 / BAR_COUNT; - const ImageFloatBox stripe(c * width + width * 0.25, 0.1, width * 0.5, 0.5); + const ImageFloatBox stripe(c * width + width * BAR_INSET, BAR_TOP, width * (1 - 2 * BAR_INSET), BAR_HEIGHT); const ImageStats stats = image_stats(extract_box_reference(frame, stripe)); if (stats.stddev.sum() > BAR_MAX_STDDEV){ return false; diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h index 9215d63a1c..d888b9f73d 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun.h @@ -19,8 +19,8 @@ * run before anything is saved. * - The first checkpoint's own save at its start runs only for a new * game: after a load the save is already there, and from the game as - * it is the place is unconfirmed (console B, 2026-11-11: a run on the - * HOME menu "saved" first). + * it is the place is unconfirmed (the game may be on the HOME + * menu). * - A failure leaves the game where it failed. Nothing here closes the * game; the user (or the next run from the save) resumes from there. * diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp index a45f39b5a4..b1c187331b 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp @@ -62,21 +62,21 @@ struct FakeGame{ }; // A start as the program asks for it, and what the game must have done. -struct StartInput{ - std::string name; - StoryStart start; - std::string place_error; - StoryPreflight preflight; -}; -struct StartExpectation{ - bool succeeds; - size_t loads; - size_t rereads; - bool save_loaded; -}; struct StartCase{ - StartInput input; - StartExpectation expectation; + struct Input{ + std::string name; + StoryStart start; + std::string place_error; + StoryPreflight preflight; + }; + struct Expectation{ + bool succeeds; + size_t loads; + size_t rereads; + bool save_loaded; + }; + Input input; + Expectation expectation; }; constexpr StoryPreflight READY{.video_alive = true, .controller_ready = true, .game_running = true}; @@ -134,8 +134,8 @@ class Test_StoryStart : public UnitTest{ }; const StartCase START_CASES[] = { - // Console B, 2026-11-11: a BDSP run started at 00.04b with the game - // left at 00.04d walked from 00.04d's position. + // A game left at a later checkpoint must not be walked from: a + // checkpoint with a save loads that save first. { .input = {.name = "a checkpoint with a save loads it first", .start = StoryStart::FROM_SAVE, .place_error = "", .preflight = READY}, .expectation = {.succeeds = true, .loads = 1, .rereads = 1, .save_loaded = true}, @@ -152,9 +152,8 @@ const StartCase START_CASES[] = { .input = {.name = "a live start loads nothing", .start = StoryStart::LIVE, .place_error = "", .preflight = READY}, .expectation = {.succeeds = true, .loads = 0, .rereads = 0, .save_loaded = false}, }, - // Console B, 2026-11-11 13:32: the game was on HOME; the run saved, - // pressed X/R/ZL on HOME, then "loaded" nothing. The preflight stops it - // before any press. + // The game is on the HOME menu: every press would go to the console's + // menus, so the preflight stops the run before any press. { .input = {.name = "the HOME menu stops the run before the load", .start = StoryStart::FROM_SAVE, .place_error = "", .preflight = ON_HOME}, .expectation = {.succeeds = false, .loads = 0, .rereads = 0, .save_loaded = false}, @@ -176,16 +175,16 @@ const StartCase START_CASES[] = { // A preflight's checks, and the failure it reads as: the setup's, not // the story's, naming every check that failed. -struct PreflightInput{ - std::string name; - StoryPreflight preflight; -}; -struct PreflightExpectation{ - std::string outcome; -}; struct PreflightCase{ - PreflightInput input; - PreflightExpectation expectation; + struct Input{ + std::string name; + StoryPreflight preflight; + }; + struct Expectation{ + std::string outcome; + }; + Input input; + Expectation expectation; }; class Test_StoryPreflight : public UnitTest{ @@ -222,16 +221,16 @@ const PreflightCase PREFLIGHT_CASES[] = { // Whether the first checkpoint saves at its start: only a new game's. After // a load the save is already there; from the game as it is the place is -// unconfirmed (console B, 2026-11-11: "save" ran first on HOME). -struct FirstSaveInput{ - StoryStart start; -}; -struct FirstSaveExpectation{ - bool saves; -}; +// unconfirmed (the game may be on the HOME menu). struct FirstSaveCase{ - FirstSaveInput input; - FirstSaveExpectation expectation; + struct Input{ + StoryStart start; + }; + struct Expectation{ + bool saves; + }; + Input input; + Expectation expectation; }; class Test_StoryFirstSave : public UnitTest{ @@ -260,10 +259,24 @@ const FirstSaveCase FIRST_SAVE_CASES[] = { // A failed attempt's reload loads the save through the game. +struct ReloadCase{ + struct Input{ + std::string name; + }; + struct Expectation{ + size_t loads; + size_t rereads; + std::string log_line; + }; + Input input; + Expectation expectation; +}; + class Test_StoryReload : public UnitTest{ public: - Test_StoryReload() - : UnitTest("Pokemon::StoryRun - a retry reloads the save") + Test_StoryReload(const ReloadCase& test_case) + : UnitTest(std::format("Pokemon::StoryRun - {}", test_case.input.name)) + , m_case(test_case) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -272,20 +285,46 @@ class Test_StoryReload : public UnitTest{ SegmentHooks hooks = story_segment_hooks(game); RunState state; const Outcome outcome = hooks.reload(state); - if (!outcome.succeeded() || fake.loads != 1 || fake.rereads != 1 || !fake.logged("[Story] retry: loading the save")){ - return std::format("Expected one load and reread, got {} and {} ({})", fake.loads, fake.rereads, to_string(outcome)); + const ReloadCase::Expectation& expected = m_case.expectation; + if (!outcome.succeeded() || fake.loads != expected.loads || fake.rereads != expected.rereads || !fake.logged(expected.log_line)){ + return std::format("Expected {} load and {} reread, got {} and {} ({})", expected.loads, expected.rereads, fake.loads, fake.rereads, to_string(outcome)); } return true; } + +private: + const ReloadCase m_case; +}; + +const ReloadCase RELOAD_CASES[] = { + { + .input = {.name = "a retry reloads the save"}, + .expectation = {.loads = 1, .rereads = 1, .log_line = "[Story] retry: loading the save"}, + }, }; // A run that stopped short throws, logs the failure line and touches // nothing in the game: no reload, no save, no reset to HOME. +struct FailureCase{ + struct Input{ + std::string name; + std::string checkpoint; + std::string event; + std::string stopped_after; + }; + struct Expectation{ + std::string message; + }; + Input input; + Expectation expectation; +}; + class Test_StoryFailureLeavesGame : public UnitTest{ public: - Test_StoryFailureLeavesGame() - : UnitTest("Pokemon::StoryRun - a failed run leaves the game where it failed") + Test_StoryFailureLeavesGame(const FailureCase& test_case) + : UnitTest(std::format("Pokemon::StoryRun - {}", test_case.input.name)) + , m_case(test_case) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -293,18 +332,18 @@ class Test_StoryFailureLeavesGame : public UnitTest{ StoryGameHooks game = fake.hooks(); SegmentReport report; report.completed = false; - report.failed_checkpoint = "00.04b"; - report.failed_event = "talk_mom"; + report.failed_checkpoint = m_case.input.checkpoint; + report.failed_event = m_case.input.event; report.failure = outcome_failed("expect_failed", "dialogue opened"); AutoStoryStats stats; std::string message; try{ - finish_story_run(report, "00.05", stats, game); + finish_story_run(report, m_case.input.stopped_after, stats, game); return "Expected an OperationFailedException"; }catch (OperationFailedException& e){ message = e.message(); } - if (message != "AutoStory stopped at 00.04b talk_mom: expect_failed: dialogue opened"){ + if (message != m_case.expectation.message){ return std::format("Unexpected message: {}", message); } if (!fake.logged(STORY_LEFT_WHERE_FAILED)){ @@ -315,14 +354,37 @@ class Test_StoryFailureLeavesGame : public UnitTest{ } return true; } + +private: + const FailureCase m_case; +}; + +const FailureCase FAILURE_CASES[] = { + { + .input = {.name = "a failed run leaves the game where it failed", .checkpoint = "00.04b", .event = "talk_mom", .stopped_after = "00.05"}, + .expectation = {.message = "AutoStory stopped at 00.04b talk_mom: expect_failed: dialogue opened"}, + }, }; // A completed run logs and returns the line the finish notification sends. +struct FinishedCase{ + struct Input{ + std::string name; + std::string last_checkpoint; + }; + struct Expectation{ + std::string line; + }; + Input input; + Expectation expectation; +}; + class Test_StoryFinished : public UnitTest{ public: - Test_StoryFinished() - : UnitTest("Pokemon::StoryRun - a completed run is done through its last checkpoint") + Test_StoryFinished(const FinishedCase& test_case) + : UnitTest(std::format("Pokemon::StoryRun - {}", test_case.input.name)) + , m_case(test_case) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -331,20 +393,44 @@ class Test_StoryFinished : public UnitTest{ SegmentReport report; report.completed = true; AutoStoryStats stats; - const std::string done = finish_story_run(report, "00.05", stats, game); - if (done != "AutoStory: done through 00.05." || !fake.logged(done)){ + const std::string done = finish_story_run(report, m_case.input.last_checkpoint, stats, game); + if (done != m_case.expectation.line || !fake.logged(done)){ return std::format("Unexpected finish line: {}", done); } return true; } + +private: + const FinishedCase m_case; +}; + +const FinishedCase FINISHED_CASES[] = { + { + .input = {.name = "a completed run is done through its last checkpoint", .last_checkpoint = "00.05"}, + .expectation = {.line = "AutoStory: done through 00.05."}, + }, }; // A verify run short of its passes throws with the summary. +struct VerifyCase{ + struct Input{ + std::string name; + std::string checkpoint; + size_t passes; + }; + struct Expectation{ + std::string message; + }; + Input input; + Expectation expectation; +}; + class Test_StoryVerifyFailed : public UnitTest{ public: - Test_StoryVerifyFailed() - : UnitTest("Pokemon::StoryRun - an unverified checkpoint fails with its summary") + Test_StoryVerifyFailed(const VerifyCase& test_case) + : UnitTest(std::format("Pokemon::StoryRun - {}", test_case.input.name)) + , m_case(test_case) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ @@ -352,20 +438,30 @@ class Test_StoryVerifyFailed : public UnitTest{ StoryGameHooks game = fake.hooks(); VerifyPolicy policy; VerifyReport report; - report.passes = 1; + report.passes = m_case.input.passes; report.verified = false; std::string message; try{ - finish_story_verify("00.15b", policy, report, game); + finish_story_verify(m_case.input.checkpoint, policy, report, game); return "Expected an OperationFailedException"; }catch (OperationFailedException& e){ message = e.message(); } - if (message != "AutoStory verify: 00.15b 1/3 passed, 2 needed." || !fake.logged(STORY_LEFT_WHERE_FAILED)){ + if (message != m_case.expectation.message || !fake.logged(STORY_LEFT_WHERE_FAILED)){ return std::format("Unexpected message: {}", message); } return true; } + +private: + const VerifyCase m_case; +}; + +const VerifyCase VERIFY_CASES[] = { + { + .input = {.name = "an unverified checkpoint fails with its summary", .checkpoint = "00.15b", .passes = 1}, + .expectation = {.message = "AutoStory verify: 00.15b 1/3 passed, 2 needed."}, + }, }; } // namespace @@ -381,10 +477,18 @@ void add_tests_StoryRun(UnitTestDatabase& database){ for (const FirstSaveCase& test_case : FIRST_SAVE_CASES){ database.add(test_case); } - database.add(); - database.add(); - database.add(); - database.add(); + for (const ReloadCase& test_case : RELOAD_CASES){ + database.add(test_case); + } + for (const FailureCase& test_case : FAILURE_CASES){ + database.add(test_case); + } + for (const FinishedCase& test_case : FINISHED_CASES){ + database.add(test_case); + } + for (const VerifyCase& test_case : VERIFY_CASES){ + database.add(test_case); + } } diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.cpp index bae25ec95a..72dcc9961a 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySavePolicy_Tests.cpp @@ -391,21 +391,21 @@ UnitTestResult test_end_pose_from_the_plan(){ } -// The scenario to run. -struct SavePolicyInput{ - std::string name; - UnitTestResult (*test)() = nullptr; -}; - -// What the scenario checks; it returns its own failure. -struct SavePolicyExpectation{ - std::string_view description; -}; - // A save-policy scenario and its expected result. struct SavePolicyCase{ - SavePolicyInput input; - SavePolicyExpectation expectation; + // The scenario to run. + struct Input{ + std::string name; + UnitTestResult (*test)() = nullptr; + }; + + // What the scenario checks; it returns its own failure. + struct Expectation{ + std::string_view description; + }; + + Input input; + Expectation expectation; }; class Test_StorySavePolicy : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp index c4073dd8d5..efcacab7ca 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StorySegments_Tests.cpp @@ -407,18 +407,18 @@ UnitTestResult test_describe(){ } -struct StorySegmentInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct StorySegmentTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct StorySegmentExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct StorySegmentTestCase{ - StorySegmentInput input; - StorySegmentExpectation expectation; + Input input; + Expectation expectation; }; class Test_StorySegments : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp index 4693e73eec..3c0c574010 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor.cpp @@ -52,8 +52,21 @@ Event story_event(const StoryStep& step, StoryStepExecutor& executor){ })); } event.act = [&executor, &step](RunState& state){ - return executor.run(step, state); + Outcome outcome = executor.run(step, state); + // What a step that failed did to the game is not known to the run. + if (outcome.succeeded()){ + if (step.gates_after){ + apply_gate_change(state.gates, *step.gates_after); + } + state.flags.insert(step.flags_after.begin(), step.flags_after.end()); + } + return outcome; }; + if (step.gates_after){ + event.when_skipped = [&step](RunState& state){ + apply_gate_change(state.gates, *step.gates_after); + }; + } if (step.pose_after){ event.pose_learned = pose_of(*step.pose_after); } @@ -63,13 +76,24 @@ Event story_event(const StoryStep& step, StoryStepExecutor& executor){ namespace{ // The first event of a checkpoint that starts from a save: where the save -// leaves the player, for a run that reloaded it. -Event from_save_event(const Pose& start){ +// leaves the player, and the gates and flags it has, for a run that +// reloaded it. +Event from_save_event(const StoryCheckpoint& data){ Event event; event.name = "from_save"; event.why = "where the checkpoint's save leaves the player"; - event.act = [](RunState&){ return outcome_ok(); }; - event.pose_learned = start; + // A checkpoint that does not say what its save has leaves the run's + // gates as the steps before it made them. + event.act = [gates = data.start_gates, flags = data.start_flags](RunState& state){ + if (gates){ + state.gates = *gates; + } + state.flags.insert(flags.begin(), flags.end()); + return outcome_ok(); + }; + if (data.start){ + event.pose_learned = pose_of(*data.start); + } return event; } @@ -99,8 +123,8 @@ Checkpoint build_story_checkpoint(const StoryCheckpoint& data, StoryStepExecutor executor.begin_attempt(data); Checkpoint checkpoint; checkpoint.id = data.id; - if (data.start){ - checkpoint.events.push_back(from_save_event(pose_of(*data.start))); + if (data.start || data.start_gates || !data.start_flags.empty()){ + checkpoint.events.push_back(from_save_event(data)); } for (const StoryStep& step : data.steps){ checkpoint.events.push_back(story_event(step, executor)); diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp index 1d9ef32865..6002f95900 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp @@ -50,6 +50,9 @@ class FakeExecutor : public StoryStepExecutor{ std::map failures_left; // The pose each step started from, by name. std::vector> poses_seen; + // The gates and the run flags each step started with, by name. + std::vector> gates_seen; + std::vector>> flags_seen; // The checkpoints begun, one per attempt. std::vector attempts; // Game steps by name that change nothing in the game. @@ -61,6 +64,8 @@ class FakeExecutor : public StoryStepExecutor{ virtual Outcome run(const StoryStep& step, RunState& state) override{ poses_seen.emplace_back(step.name, to_string(state.pose)); + gates_seen.emplace_back(step.name, state.gates); + flags_seen.emplace_back(step.name, state.flags); trace.push_back(std::format("{} {}", story_step_kind_name(step.kind), step.name)); if (failing.contains(step.name)){ return outcome_failed("blocked", std::format("{} was blocked", step.name)); @@ -294,6 +299,78 @@ UnitTestResult test_pose_propagation(){ return true; } +// A checkpoint whose save has Silph's first door open: a step opens the +// second and gives the Card Key, a failing step changes nothing. +StoryCheckpoint silph_checkpoint(){ + StoryStep key = make(StoryStepKind::TALK, "card_key"); + key.gates_after = GateChange{.opened = {"SilphCo_5F/door_2"}}; + key.flags_after = {"card_key_held"}; + StoryStep blocked = make(StoryStepKind::TALK, "blocked"); + blocked.gates_after = GateChange{.opened = {"SilphCo_5F/door_3"}}; + blocked.flags_after = {"never"}; + GateState start; + start.opened.insert("SilphCo_5F/door_1"); + return StoryCheckpoint{ + .id = "16.02", + .title = "Silph", + .steps = {make(StoryStepKind::TALK, "before"), key, make(StoryStepKind::TALK, "after"), blocked}, + .start_gates = start, + .start_flags = {"has_pass"}, + }; +} + +UnitTestResult test_gate_state_carried(){ + const StoryCheckpoint data = silph_checkpoint(); + FakeExecutor executor; + executor.failing = {"blocked"}; + const Run result = run(data, executor); + if (executor.gates_seen.size() != 4){ + return std::format("Expected four steps run, got {}:{}", executor.gates_seen.size(), joined(executor.trace)); + } + const GateState& before = executor.gates_seen[0].second; + const GateState& after = executor.gates_seen[2].second; + if (before.opened != std::set{"SilphCo_5F/door_1"} || !executor.flags_seen[0].second.contains("has_pass")){ + return "Expected the save's own gates and flags at the first step."; + } + if (executor.flags_seen[1].second.contains("card_key_held")){ + return "The Card Key was held before its step was done."; + } + if (after.opened != std::set{"SilphCo_5F/door_1", "SilphCo_5F/door_2"} || !executor.flags_seen[2].second.contains("card_key_held")){ + return "Expected door_2 open and the Card Key held after the step that gave it."; + } + if (result.state.gates.opened.contains("SilphCo_5F/door_3") || result.state.flags.contains("never")){ + return "A step that failed changed the gates or the flags."; + } + return true; +} + +UnitTestResult test_skipped_step_gates_applied(){ + // A step that skip_if skips has its effect already: the door it opens + // is open for the steps after it, and a later step that needs it runs + // with it open. + StoryStep open_door = make(StoryStepKind::TALK, "open_door"); + open_door.skip_if = {"door_done"}; + open_door.gates_after = GateChange{.opened = {"SilphCo_5F/door_2"}}; + const StoryCheckpoint data{ + .id = "16.02", + .title = "Silph", + .steps = {open_door, make(StoryStepKind::TALK, "after")}, + }; + FakeExecutor executor; + executor.conditions = {"door_done"}; + const Run result = run(data, executor); + if (!result.report.completed || result.report.events_skipped != 1){ + return std::format("Expected the door step skipped:{}", joined(result.lines)); + } + if (executor.gates_seen.size() != 1 || !executor.gates_seen[0].second.opened.contains("SilphCo_5F/door_2")){ + return "Expected the step after a skipped door step to see the door open."; + } + if (!result.state.gates.opened.contains("SilphCo_5F/door_2")){ + return "Expected the door open at the end of the checkpoint."; + } + return true; +} + UnitTestResult test_failure_names_the_step(){ const StoryCheckpoint data = lab_checkpoint(); FakeExecutor executor; @@ -727,18 +804,18 @@ UnitTestResult test_lint(){ } -struct StoryStepInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct StoryStepTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct StoryStepExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct StoryStepTestCase{ - StoryStepInput input; - StoryStepExpectation expectation; + Input input; + Expectation expectation; }; class Test_StoryStepExecutor : public UnitTest{ @@ -772,6 +849,14 @@ const StoryStepTestCase STORY_STEP_CASES[] = { .input = {.name = "a failure names its step", .test = test_failure_names_the_step}, .expectation = {.description = "records failing step identifier on error"}, }, + { + .input = {.name = "gate state and run flags carried from the save through the steps", .test = test_gate_state_carried}, + .expectation = {.description = "applies start_gates, start_flags, gates_after and flags_after in order"}, + }, + { + .input = {.name = "a skipped step's gates_after is applied", .test = test_skipped_step_gates_applied}, + .expectation = {.description = "the gates a skipped step opened are open for the steps after it"}, + }, { .input = {.name = "unsupported kinds and lost battles", .test = test_unsupported_and_lost_battles}, .expectation = {.description = "flags unsupported step types and handles battle defeat"}, diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h new file mode 100644 index 0000000000..203bed4d21 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_TestExpect.h @@ -0,0 +1,31 @@ +/* Test Expect + * + * From: https://github.com/PokemonAutomation/ + * + * Checks the unit tests of the AutoStory judges share. + * + */ + +#ifndef PokemonAutomation_Pokemon_TestExpect_H +#define PokemonAutomation_Pokemon_TestExpect_H + +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Passes when `got` is `expected`; else fails naming `what`. +inline UnitTestResult expect_equal(const std::string& what, const std::string& got, const std::string& expected){ + if (got == expected){ + return true; + } + return std::format("{}: expected \"{}\", got \"{}\"", what, expected, got); +} + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp index ef4818a42e..18ef603a22 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp @@ -9,6 +9,8 @@ */ #include +#include +#include #include #include #include @@ -78,25 +80,25 @@ std::string run_tracker(const std::vector& spans, TransitionTracker& track } -// A synthetic stream of frames, through one game's profile. -struct TrackInput{ - std::string name; - std::vector spans; - const FadeProfile* profile = &BDSP_FADE_PROFILE; - bool compare = true; -}; - -struct TrackExpectation{ - // The transitions completed, as run_tracker() puts them. - std::string transitions; - // What judge_warp() makes of the tracker's current() at the end; empty - // for none. - std::string warp = ""; -}; - struct TrackCase{ - TrackInput input; - TrackExpectation expectation; + // A synthetic stream of frames, through one game's profile. + struct Input{ + std::string name; + std::vector spans; + const FadeProfile* profile = &BDSP_FADE_PROFILE; + bool compare = true; + }; + + struct Expectation{ + // The transitions completed, as run_tracker() puts them. + std::string transitions; + // What judge_warp() makes of the tracker's current() at the end; empty + // for none. + std::string warp = ""; + }; + + Input input; + Expectation expectation; }; class Test_TransitionTracker : public UnitTest{ @@ -106,7 +108,7 @@ class Test_TransitionTracker : public UnitTest{ , m_case(std::move(test_case)) {} virtual UnitTestResult run(Logger&, CancellableScope&) const override{ - const TrackInput& input = m_case.input; + const TrackCase::Input& input = m_case.input; TransitionTracker tracker(*input.profile, input.compare ? compare_means : TransitionTracker::CompareScenes()); const std::string got = run_tracker(input.spans, tracker); if (got != m_case.expectation.transitions){ @@ -161,29 +163,40 @@ UnitTestResult test_sample_of_frame(){ } -// Captured frames: CommandLineTests//Transitions// holds -// frames named by their time in ms ("0.png", "250.png"), and expected.txt -// with the transitions run_tracker() should report (no scene comparison). -struct CapturedInput{ - std::string game; - const FadeProfile* profile; -}; - -// Each case folder's expected.txt holds its expectation. -struct CapturedExpectation{ -}; - struct CapturedCase{ - CapturedInput input; - CapturedExpectation expectation; + // Captured frames: CommandLineTests//Transitions// holds + // frames named by their time in ms ("0.png", "250.png"), and expected.txt + // with the transitions run_tracker() should report (no scene comparison). + struct Input{ + std::string game; + const FadeProfile* profile; + }; + + // Each case folder's expected.txt holds its expectation. + struct Expectation{ + }; + + Input input; + Expectation expectation; }; std::string track_captured_case(const Filesystem::Path& folder, const FadeProfile& profile){ std::vector> frames; for (const Filesystem::Path& file : Filesystem::list_directory(folder)){ - if (file.extension().string() == ".png"){ - frames.emplace_back(std::stoi(file.stem().string()), file); + std::string extension = file.extension().string(); + std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char c){ + return static_cast(std::tolower(c)); + }); + if (extension != ".png"){ + continue; + } + const std::string stem = file.stem().string(); + int ms = 0; + const auto parsed = std::from_chars(stem.data(), stem.data() + stem.size(), ms); + if (parsed.ec != std::errc() || parsed.ptr != stem.data() + stem.size()){ + return std::format("frame {} is not named by its time in ms", file.filename().string()); } + frames.emplace_back(ms, file); } std::sort(frames.begin(), frames.end(), [](const auto& a, const auto& b){ return a.first < b.first; @@ -226,22 +239,22 @@ class Test_CapturedTransitions : public UnitTest{ } private: - CapturedInput m_input; + CapturedCase::Input m_input; }; -struct TransitionsInput{ - std::string name; - UnitTestResult (*body)(); -}; +struct TransitionsCase{ + struct Input{ + std::string name; + UnitTestResult (*body)(); + }; -// The body checks its own expectations. -struct TransitionsExpectation{ -}; + // The body checks its own expectations. + struct Expectation{ + }; -struct TransitionsCase{ - TransitionsInput input; - TransitionsExpectation expectation; + Input input; + Expectation expectation; }; class Test_Transitions : public UnitTest{ @@ -255,7 +268,7 @@ class Test_Transitions : public UnitTest{ } private: - TransitionsInput m_input; + TransitionsCase::Input m_input; }; } // namespace diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_WarpJudge.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_WarpJudge.h index ab112a4362..c2b1eb594c 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_WarpJudge.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_WarpJudge.h @@ -2,7 +2,8 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_Interrupts.h, unchanged; it includes this header. + * The warp judge: whether a fade was a warp, from a game's timing. Its + * definitions are in Pokemon_Interrupts.cpp. * */ diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp index 50cda4ade3..d26fb413e3 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryActionArg_Tests.cpp @@ -36,21 +36,21 @@ const StoryActionSpec& mart_spec(){ return spec; } -// Args checked against the Mart's spec, then filled in. -struct ArgsInput{ - std::string_view name; - StoryActionArgs args; -}; - -// The errors joined by "; ", and the args with their fallbacks. -struct ArgsExpectation{ - std::string_view error = {}; - StoryActionArgs filled = {}; -}; - struct ArgsCase{ - ArgsInput input; - ArgsExpectation expectation; + // Args checked against the Mart's spec, then filled in. + struct Input{ + std::string_view name; + StoryActionArgs args; + }; + + // The errors joined by "; ", and the args with their fallbacks. + struct Expectation{ + std::string_view error = {}; + StoryActionArgs filled = {}; + }; + + Input input; + Expectation expectation; }; const ArgsCase CASES[] = { diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h index 6a0c04702d..cc3bf66ce3 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h @@ -14,6 +14,7 @@ #include #include #include +#include "Pokemon/Navigation/Pokemon_GateState.h" #include "Pokemon_DeclaredPose.h" #include "Pokemon_StoryCheckpointMetadata.h" #include "Pokemon_StoryPostconditions.h" @@ -39,8 +40,23 @@ struct StoryCheckpoint{ // Its phase and verification (JSON "metadata"), which decide when a // run of it may save. StoryCheckpointMetadata metadata = {}; + // Which gates are open and which switches are on at the start, where the + // save has any of the story's gates (Silph Co., Pokemon Mansion); none + // where the checkpoint does not say, which the run infers from the + // story so far, or else observes. JSON: "start_gates". + std::optional start_gates = {}; + // The run flags that hold at the start, as flags_after would have set + // them in the story so far, which a reload loses ("card_key_held" in a + // save made after the Card Key). JSON: "start_flags". + std::vector start_flags = {}; }; +// The gate state of `checkpoint` once its first `steps_done` steps are done: +// its start_gates (nothing open, no switch on if it has none) with the +// steps' gates_after applied in order. `steps_done` past the last step is +// the end. +GateState checkpoint_gates(const StoryCheckpoint& checkpoint, size_t steps_done); + } // namespace Pokemon diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointGates.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointGates.cpp new file mode 100644 index 0000000000..2a3561835c --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointGates.cpp @@ -0,0 +1,28 @@ +/* Story Checkpoint Gates + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_StoryCheckpoint.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +GateState checkpoint_gates(const StoryCheckpoint& checkpoint, size_t steps_done){ + GateState gates = checkpoint.start_gates.value_or(GateState()); + const size_t done = std::min(steps_done, checkpoint.steps.size()); + for (size_t c = 0; c < done; c++){ + if (checkpoint.steps[c].gates_after){ + apply_gate_change(gates, *checkpoint.steps[c].gates_after); + } + } + return gates; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h index 4500111b71..d561b0add0 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Types/Pokemon_StoryStep.h @@ -15,6 +15,7 @@ #include #include #include +#include "Pokemon/Navigation/Pokemon_GateState.h" #include "Pokemon_DeclaredPose.h" #include "Pokemon_StoryActionArg.h" #include "Pokemon_StoryStepKind.h" @@ -51,6 +52,14 @@ struct StoryStep{ // Where the step leaves the player, when its action does not say: the // end of a scene that moves the player. std::optional pose_after; + // The gates the step opens and the switches it sets + // (Pokemon/Navigation/Pokemon_GateState.h), applied to the run's gate + // state when the step is done. + std::optional gates_after = {}; + // The run flags the step sets when it is done (JSON "flags_after"): what + // the story's later steps and the planner read, as "card_key_held" after + // the Card Key is picked up, which lets plans open card-key gates. + std::vector flags_after = {}; }; diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp new file mode 100644 index 0000000000..1bd697a03e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp @@ -0,0 +1,153 @@ +/* Connected Maps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_ConnectedMaps.h" + +namespace PokemonAutomation{ +namespace Pokemon{ +namespace{ + +// The tile of `to` that `connection` on `side` leads onto from `here`: +// the edge row or column, shifted by the connection's offset. +TilePos edge_entry(const TilePos& here, Direction side, const MapConnection& connection, const Grid& to){ + TilePos point{here.x - connection.offset, here.y - connection.offset}; + switch (side){ + case Direction::NORTH: + point.y = to.height - 1; + break; + case Direction::SOUTH: + point.y = 0; + break; + case Direction::WEST: + point.x = to.width - 1; + break; + case Direction::EAST: + point.x = 0; + break; + } + return point; +} + +} // namespace + + +const MapData& ConnectedMaps::map(size_t index) const{ + if (index >= m_maps->size()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, + std::format("Map index {} is past the {} connected maps.", index, m_maps->size())); + } + return (*m_maps)[index]; +} + +std::optional ConnectedMaps::find(std::string_view name) const{ + for (size_t index = 0; index < m_maps->size(); index++){ + if ((*m_maps)[index].name == name){ + return index; + } + } + return std::nullopt; +} + +std::optional ConnectedMaps::warp_arrival(const MapWarp& warp) const{ + if (!warp.to){ + return std::nullopt; + } + const std::optional destination = find(warp.to->map); + if (!destination){ + return std::nullopt; + } + const MapData& to = map(*destination); + const auto arrival = to.points.find(warp.to->point); + if (arrival == to.points.end()){ + return std::nullopt; + } + return MapPlace{*destination, arrival->second}; +} + +std::optional ConnectedMaps::across_edge(const MapPlace& from, Direction side) const{ + for (const MapConnection& connection : map(from.map).connections){ + if (connection.side != side){ + continue; + } + const std::optional destination = find(connection.to_map); + if (!destination){ + continue; + } + const Grid& to = map(*destination).tiles; + const TilePos point = edge_entry(from.tile, side, connection, to); + if (to.contains(point)){ + return MapPlace{*destination, point}; + } + } + return std::nullopt; +} + +std::optional ConnectedMaps::neighbour(const MapPlace& from, Direction direction) const{ + const TilePos ahead = from.tile.next(direction); + if (map(from.map).tiles.contains(ahead)){ + return MapPlace{from.map, ahead}; + } + return across_edge(from, direction); +} + + +namespace{ + +// The side of `a` that `b` touches, and the offset of `b`'s tiles along it, +// if their rectangles on the world grid meet along a side. +std::optional touching(const MapData& a, const MapData& b){ + const TilePos pa = a.world->offset; + const TilePos pb = b.world->offset; + const int aw = a.tiles.width; + const int ah = a.tiles.height; + const int bw = b.tiles.width; + const int bh = b.tiles.height; + const bool columns_overlap = pa.x < pb.x + bw && pb.x < pa.x + aw; + const bool rows_overlap = pa.y < pb.y + bh && pb.y < pa.y + ah; + if (columns_overlap && pb.y + bh == pa.y){ + return MapConnection{Direction::NORTH, b.name, pb.x - pa.x}; + } + if (columns_overlap && pb.y == pa.y + ah){ + return MapConnection{Direction::SOUTH, b.name, pb.x - pa.x}; + } + if (rows_overlap && pb.x + bw == pa.x){ + return MapConnection{Direction::WEST, b.name, pb.y - pa.y}; + } + if (rows_overlap && pb.x == pa.x + aw){ + return MapConnection{Direction::EAST, b.name, pb.y - pa.y}; + } + return std::nullopt; +} + +} // namespace + +void connect_by_world(std::vector& maps){ + for (MapData& a : maps){ + for (const MapData& b : maps){ + if (&a == &b || !a.world || !b.world || a.world->name != b.world->name){ + continue; + } + const std::optional connection = touching(a, b); + if (!connection){ + continue; + } + const bool joined = std::ranges::any_of(a.connections, [&](const MapConnection& existing){ + return existing.to_map == b.name; + }); + if (!joined){ + a.connections.push_back(*connection); + } + } + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h new file mode 100644 index 0000000000..5fef2d16a6 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h @@ -0,0 +1,99 @@ +/* Connected Maps + * + * From: https://github.com/PokemonAutomation/ + * + * The one world the tile games (BDSP, FRLG) plan and walk on: maps joined by + * their warps and their edges (MapData::connections). The player's place in + * it is a map and a tile of that map, in the map's own coordinates. Where a + * warp or an edge leads is the same in both games; whether a step is + * allowed, and what the game does on arrival (FRLG walks the player out of + * a door), is each game's. + * + */ + +#ifndef PokemonAutomation_Pokemon_ConnectedMaps_H +#define PokemonAutomation_Pokemon_ConnectedMaps_H + +#include +#include +#include +#include +#include "Pokemon_Grid.h" +#include "Pokemon_MapData.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A tile of one of the connected maps: the map's index and the tile in that +// map's own coordinates. +struct MapPlace{ + size_t map = 0; + TilePos tile; + + bool operator==(const MapPlace& other) const = default; + // Map, then tile: an order for sets and maps of places. + auto operator<=>(const MapPlace& other) const = default; +}; + + +// A view of loaded maps as one connected world. It does not own the maps, +// which must outlive it and keep their order: MapPlace::map indexes them. +class ConnectedMaps{ +public: + explicit ConnectedMaps(const std::vector& maps) + : m_maps(&maps) + {} + // A temporary list would be gone by the first call. + explicit ConnectedMaps(std::vector&& maps) = delete; + + // How many maps are loaded: MapPlace::map runs from 0 to size() - 1. + size_t size() const{ + return m_maps->size(); + } + // The map at `index`; throws InternalProgramError past the last map, + // as from a MapPlace of another world. + const MapData& map(size_t index) const; + // The loaded map named `name`, or nothing. + std::optional find(std::string_view name) const; + + // Where taking `warp` puts the player: its destination point. Nothing + // if it leads to a map that isn't loaded or names a point that map + // doesn't have. + std::optional warp_arrival(const MapWarp& warp) const; + + // The tile past `side` of `from`'s map that carries on `from`'s row or + // column: on the first loaded map connected on that side that has it. + // Nothing if no loaded map there has it. + std::optional across_edge(const MapPlace& from, Direction side) const; + + // The tile next to `from` in `direction`: on the same map, or across + // its edge. Nothing past an edge that leads nowhere loaded. + std::optional neighbour(const MapPlace& from, Direction direction) const; + +private: + const std::vector* m_maps; +}; + + +// Joins the maps that lie on the same world grid (MapData::world) where +// they meet: each map gets a connection on each side to every map whose +// rectangle touches that side, unless it has one to that map already. +// Maps without a world are left alone. +void connect_by_world(std::vector& maps); + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +// A hash of MapPlace, for planners that keep places in unordered sets. +template <> +struct std::hash{ + size_t operator()(const PokemonAutomation::Pokemon::MapPlace& place) const{ + return std::hash()(place.tile) * 31 + place.map; + } +}; + +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp new file mode 100644 index 0000000000..788bfe9b84 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp @@ -0,0 +1,272 @@ +/* Connected Maps Tests + * + * From: https://github.com/PokemonAutomation/ + * + * A town with a route north of it and a lake east of it, joined by their + * places on one world grid (connect_by_world()), and a house the town's + * door warps into: + * + * world x: -1 0 1 2 3 4 5 + * y 0..2: [ Route (6 wide) ] + * y 3..5: [ Town (4) ][Lake] + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_ConnectedMaps.h" +#include "Pokemon_ConnectedMaps_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ +namespace{ + + +MapData open_map(std::string name, int width, int height){ + MapData map; + map.name = std::move(name); + map.tiles = Grid{width, height, std::vector((size_t)width * height, TileKind::OPEN)}; + return map; +} + +MapData on_world(MapData map, const TilePos& offset){ + map.world = MapWorld{"Test", offset}; + return map; +} + +const std::vector& test_maps(){ + static const std::vector maps = []{ + std::vector ret{ + on_world(open_map("Town", 4, 3), {0, 3}), + on_world(open_map("Route", 6, 3), {-1, 0}), + on_world(open_map("Lake", 2, 3), {4, 3}), + open_map("House", 2, 2), + }; + ret[3].points["door"] = {0, 1}; + connect_by_world(ret); + return ret; + }(); + return maps; +} + +// A tile named by its map. +struct NamedPlace{ + std::string_view map; + TilePos tile; +}; + +std::string describe(const ConnectedMaps& world, const std::optional& place){ + if (!place){ + return "nowhere"; + } + return std::format("{} {}", world.map(place->map).name, to_string(place->tile)); +} + +// Why `actual` is not `expected`, if it is not. +std::optional mismatch(const ConnectedMaps& world, const std::optional& actual, const std::optional& expected){ + std::optional wanted; + if (expected){ + wanted = MapPlace{*world.find(expected->map), expected->tile}; + } + if (actual == wanted){ + return std::nullopt; + } + return std::format("Got {}, expected {}.", describe(world, actual), describe(world, wanted)); +} + + +struct StepCase{ + struct Input{ + std::string_view name; + NamedPlace from; + Direction direction; + }; + // Where the step should put the player, or nothing for nowhere. + struct Expectation{ + std::optional place; + }; + Input input; + Expectation expectation; +}; + +class Test_ConnectedMaps_Step : public UnitTest{ +public: + explicit Test_ConnectedMaps_Step(StepCase scenario) + : UnitTest(std::format("Pokemon::ConnectedMaps - {}", scenario.input.name)), m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const ConnectedMaps world(test_maps()); + const StepCase::Input& input = m_scenario.input; + const MapPlace from{*world.find(input.from.map), input.from.tile}; + if (std::optional error = mismatch(world, world.neighbour(from, input.direction), m_scenario.expectation.place)){ + return *error; + } + return true; + } +private: + StepCase m_scenario; +}; + +const StepCase STEP_CASES[] = { + { + .input = {.name = "a step on the same map", .from = {"Town", {1, 1}}, .direction = Direction::EAST}, + .expectation = {.place = NamedPlace{"Town", {2, 1}}}, + }, + { + .input = {.name = "north onto the route, shifted by its offset", .from = {"Town", {0, 0}}, .direction = Direction::NORTH}, + .expectation = {.place = NamedPlace{"Route", {1, 2}}}, + }, + { + .input = {.name = "south off the route into the town", .from = {"Route", {1, 2}}, .direction = Direction::SOUTH}, + .expectation = {.place = NamedPlace{"Town", {0, 0}}}, + }, + { + .input = {.name = "east into the lake", .from = {"Town", {3, 2}}, .direction = Direction::EAST}, + .expectation = {.place = NamedPlace{"Lake", {0, 2}}}, + }, + { + .input = {.name = "west into the town", .from = {"Lake", {0, 1}}, .direction = Direction::WEST}, + .expectation = {.place = NamedPlace{"Town", {3, 1}}}, + }, + { + .input = {.name = "north out of the lake onto the route's last column", .from = {"Lake", {0, 0}}, .direction = Direction::NORTH}, + .expectation = {.place = NamedPlace{"Route", {5, 2}}}, + }, + { + .input = {.name = "north out of the lake past the route's span", .from = {"Lake", {1, 0}}, .direction = Direction::NORTH}, + .expectation = {.place = std::nullopt}, + }, + { + .input = {.name = "an edge no map joins", .from = {"Town", {0, 1}}, .direction = Direction::WEST}, + .expectation = {.place = std::nullopt}, + }, + { + .input = {.name = "past the joined map's span", .from = {"Route", {0, 2}}, .direction = Direction::SOUTH}, + .expectation = {.place = std::nullopt}, + }, + { + .input = {.name = "a map off the world grid joins nothing", .from = {"House", {1, 0}}, .direction = Direction::NORTH}, + .expectation = {.place = std::nullopt}, + }, +}; + + +struct WarpCase{ + struct Input{ + std::string_view name; + MapWarp warp; + }; + // Where the warp should put the player, or nothing for nowhere. + struct Expectation{ + std::optional place; + }; + Input input; + Expectation expectation; +}; + +class Test_ConnectedMaps_Warp : public UnitTest{ +public: + explicit Test_ConnectedMaps_Warp(WarpCase scenario) + : UnitTest(std::format("Pokemon::ConnectedMaps - {}", scenario.input.name)), m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const ConnectedMaps world(test_maps()); + if (std::optional error = mismatch(world, world.warp_arrival(m_scenario.input.warp), m_scenario.expectation.place)){ + return *error; + } + return true; + } +private: + WarpCase m_scenario; +}; + +const WarpCase WARP_CASES[] = { + { + .input = {.name = "a warp to a loaded map's point", .warp = {.to = WarpDestination{"House", "door"}}}, + .expectation = {.place = NamedPlace{"House", {0, 1}}}, + }, + { + .input = {.name = "a warp to a map that isn't loaded", .warp = {.to = WarpDestination{"Cave", "door"}}}, + .expectation = {.place = std::nullopt}, + }, + { + .input = {.name = "a warp to a point the map lacks", .warp = {.to = WarpDestination{"House", "stairs"}}}, + .expectation = {.place = std::nullopt}, + }, + { + .input = {.name = "a warp that leads nowhere", .warp = {}}, + .expectation = {.place = std::nullopt}, + }, +}; + + +struct StalePlaceCase{ + struct Input{ + std::string_view name; + size_t map; + }; + struct Expectation{ + // Whether reading the place throws InternalProgramError. + bool rejected = false; + }; + Input input; + Expectation expectation; +}; + +// A place whose map index is past the loaded maps (from another world, or +// one that has since shrunk) is an InternalProgramError, not a read past +// the end. +class Test_ConnectedMaps_StalePlace : public UnitTest{ +public: + explicit Test_ConnectedMaps_StalePlace(StalePlaceCase scenario) + : UnitTest(std::format("Pokemon::ConnectedMaps - {}", scenario.input.name)), m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const ConnectedMaps world(test_maps()); + const MapPlace stale{m_scenario.input.map, {0, 0}}; + bool rejected = false; + try{ + world.neighbour(stale, Direction::NORTH); + }catch (const InternalProgramError&){ + rejected = true; + } + if (rejected != m_scenario.expectation.rejected){ + return std::format("Map {} of {} was {}, expected it {}.", stale.map, world.size(), + rejected ? "rejected" : "read", m_scenario.expectation.rejected ? "rejected" : "read"); + } + return true; + } +private: + StalePlaceCase m_scenario; +}; + +const StalePlaceCase STALE_PLACE_CASES[] = { + {.input = {.name = "the last map index is read", .map = 3}, .expectation = {.rejected = false}}, + {.input = {.name = "a map index one past the last is rejected", .map = 4}, .expectation = {.rejected = true}}, + {.input = {.name = "a map index far past the last is rejected", .map = 1000}, .expectation = {.rejected = true}}, +}; + + +} // namespace + +void add_tests_ConnectedMaps(UnitTestDatabase& database){ + for (const StepCase& scenario : STEP_CASES){ + database.add(scenario); + } + for (const WarpCase& scenario : WARP_CASES){ + database.add(scenario); + } + for (const StalePlaceCase& scenario : STALE_PLACE_CASES){ + database.add(scenario); + } +} + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h new file mode 100644 index 0000000000..a3d6a6c26b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h @@ -0,0 +1,22 @@ +/* Connected Maps Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_ConnectedMaps_Tests_H +#define PokemonAutomation_Pokemon_ConnectedMaps_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers the checks on stepping and warping between connected maps. +void add_tests_ConnectedMaps(UnitTestDatabase& database); + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.cpp new file mode 100644 index 0000000000..8488e7783d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.cpp @@ -0,0 +1,67 @@ +/* Gate State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_GateState.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +bool GateState::switch_on(const std::string& id) const{ + return switches_on.contains(id); +} + +std::string gate_key(const std::string& map, const std::string& gate_id){ + return map + "/" + gate_id; +} + +void apply_gate_change(GateState& state, const GateChange& change){ + state.opened.insert(change.opened.begin(), change.opened.end()); + for (const auto& [id, on] : change.switches){ + if (on){ + state.switches_on.insert(id); + }else{ + state.switches_on.erase(id); + } + } +} + +GateChange gate_change_between(const GateState& before, const GateState& after){ + GateChange change; + for (const std::string& key : after.opened){ + if (!before.opened.contains(key)){ + change.opened.insert(key); + } + } + for (const std::string& id : after.switches_on){ + if (!before.switch_on(id)){ + change.switches[id] = true; + } + } + for (const std::string& id : before.switches_on){ + if (!after.switch_on(id)){ + change.switches[id] = false; + } + } + return change; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +size_t std::hash::operator()(const PokemonAutomation::Pokemon::GateState& state) const{ + size_t hash = 0; + for (const std::string& key : state.opened){ + hash = hash * 31 + std::hash()(key); + } + for (const std::string& id : state.switches_on){ + hash = hash * 37 + std::hash()(id); + } + return hash; +} diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.h new file mode 100644 index 0000000000..b8d007d668 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.h @@ -0,0 +1,76 @@ +/* Gate State + * + * From: https://github.com/PokemonAutomation/ + * + * Which of the maps' gates (MapData::gates) are open: the card-key doors + * the player has opened, and the state of each switch. A switch is shared + * by every map that lists it as a floor (Pokemon Mansion's statue + * switch), and every gate that follows it is open or closed with it. + * + * The state is plain data, with no map in it; the story keeps it + * (Pokemon_StoryCheckpoint.h). What it makes of a map's tiles is + * Pokemon_GateTiles.h, and the gated planner (Pokemon_GatedPlanner.h) + * searches over it. + * + */ + +#ifndef PokemonAutomation_Pokemon_GateState_H +#define PokemonAutomation_Pokemon_GateState_H + +#include +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Which gates are open and which switches are on. +struct GateState{ + // The card-key gates opened, each as gate_key(map, gate id). + std::set opened; + // The switches (by id) that are on. One not here is off, as at a new game. + std::set switches_on; + + bool operator==(const GateState& other) const = default; + + bool switch_on(const std::string& id) const; +}; + +// What a story step does to the state: gates it opens and switches it sets. +// What a step does to a GateState: gates it opens, switches it sets. +struct GateChange{ + std::set opened; + // The switch's new state, on or off. + std::map switches; + + bool operator==(const GateChange& other) const = default; +}; + +// Names a gate across maps: "SilphCo_5F/door_1". +std::string gate_key(const std::string& map, const std::string& gate_id); + +// Puts `change` on `state`: its gates are opened and its switches set. +void apply_gate_change(GateState& state, const GateChange& change); + +// The change that takes `before` to `after`: the gates `after` has opened +// that `before` has not, and the switches whose state differs. A card-key +// gate does not close again, so one `before` has opened and `after` has not +// is ignored. +GateChange gate_change_between(const GateState& before, const GateState& after); + + + +} // namespace Pokemon +} // namespace PokemonAutomation + + +// A hash of GateState, for planners that keep it in the search state. +template <> +struct std::hash{ + size_t operator()(const PokemonAutomation::Pokemon::GateState& state) const; +}; + +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.cpp new file mode 100644 index 0000000000..2c3053b27d --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.cpp @@ -0,0 +1,76 @@ +/* Gate Tiles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_GateTiles.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const MapGate* gate_at(const MapData& map, const TilePos& pos){ + for (const auto& [id, gate] : map.gates){ + for (const TilePos& tile : gate.tiles){ + if (tile == pos){ + return &gate; + } + } + } + return nullptr; +} + +bool gate_is_open(const MapData& map, const MapGate& gate, const GateState& state){ + if (gate.kind == GateKind::SWITCH){ + return state.switch_on(gate.switch_id) == gate.open_when_on; + } + return gate.open_at_new_game || state.opened.contains(gate_key(map.name, gate.id)); +} + +TileKind resolved_tile(const MapData& map, const TilePos& pos, const GateState& state){ + const TileKind tile = map.tiles.at(pos); + if (tile != TileKind::GATE){ + return tile; + } + const MapGate* gate = gate_at(map, pos); + return gate != nullptr && gate_is_open(map, *gate, state) ? gate->open_tile : TileKind::WALL; +} + +Grid resolve_tiles(const MapData& map, const GateState& state){ + Grid grid = map.tiles; + for (int y = 0; y < grid.height; y++){ + for (int x = 0; x < grid.width; x++){ + cell_at(TilePos{x, y}, grid) = resolved_tile(map, TilePos{x, y}, state); + } + } + return grid; +} + +const MapGate* closed_card_key_gate_faced(const MapData& map, const TilePos& from, Direction direction, const GateState& state){ + const TilePos ahead = from.next(direction); + if (!map.tiles.contains(ahead) || map.tiles.at(ahead) != TileKind::GATE){ + return nullptr; + } + const MapGate* gate = gate_at(map, ahead); + if (gate == nullptr || gate->kind != GateKind::CARD_KEY || gate_is_open(map, *gate, state)){ + return nullptr; + } + return gate; +} + +const MapSwitch* switch_pressed(const MapData& map, const TilePos& from, Direction direction){ + for (const auto& [id, result] : map.switches){ + for (const MapStatue& statue : result.statues){ + if (statue.face_from == from && statue.facing == direction){ + return &result; + } + } + } + return nullptr; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.h new file mode 100644 index 0000000000..89a0c4fcd7 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateTiles.h @@ -0,0 +1,50 @@ +/* Gate Tiles + * + * From: https://github.com/PokemonAutomation/ + * + * What a gate state (Pokemon_GateState.h) makes of a map's tiles: a closed + * gate is a wall; an open one is the tile its `open_glyph` names. + * + */ + +#ifndef PokemonAutomation_Pokemon_GateTiles_H +#define PokemonAutomation_Pokemon_GateTiles_H + +#include "Pokemon_GateState.h" +#include "Pokemon_Grid.h" +#include "Pokemon_MapData.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The gate that has `pos`, or nullptr if no gate does. +const MapGate* gate_at(const MapData& map, const TilePos& pos); + +// Whether `gate` of `map` is open: a card-key gate is open at a new game, +// if the map says so, or once opened; a switch's gate is open while the +// switch is in its `open_when` state. +bool gate_is_open(const MapData& map, const MapGate& gate, const GateState& state); + +// The tile at `pos` for walking: a gate tile is a wall while its gate is +// closed and its `open_glyph` tile once open; any other tile is as it is. +// `pos` must be inside the map. +TileKind resolved_tile(const MapData& map, const TilePos& pos, const GateState& state); + +// All the map's tiles, resolved. +Grid resolve_tiles(const MapData& map, const GateState& state); + +// The closed card-key gate that a player standing on `from` and facing +// `direction` faces, or nullptr if there is none (a wall, an open gate, a +// switch's gate). +const MapGate* closed_card_key_gate_faced(const MapData& map, const TilePos& from, Direction direction, const GateState& state); + +// The switch with a statue that a player standing on `from` and facing +// `direction` presses with A, or nullptr if there is none. +const MapSwitch* switch_pressed(const MapData& map, const TilePos& from, Direction direction); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedPlanner.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedPlanner.h new file mode 100644 index 0000000000..183e3f8716 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedPlanner.h @@ -0,0 +1,220 @@ +/* Gated Planner + * + * From: https://github.com/PokemonAutomation/ + * + * Plans legs (Pokemon_LegPlanner.h) over maps with gates (Pokemon_GateState.h). + * The game's step model walks the maps with a gate state; this wraps it, so + * the search state is the game's state and the gate state: + * + * - a closed gate is a wall, so a route goes round it; + * - a closed card-key gate the player faces can be opened (an + * ACTION_OPEN_GATE leg: face it, press A), if the Card Key is held; the + * state after the leg has it open, and the route may go through; + * - a statue faced from its tile can be pressed (an ACTION_PRESS_SWITCH + * leg), which flips the switch, so every gate that follows it changes + * with it, on every floor. A route may flip it, and flip it back. + * + * The game's step model, as for plan_legs() but taking the gate state, and + * telling where its state is: + * + * using State = ...; + * using StateHash = ...; + * std::optional> press(const State&, Direction, const GateState&) const; + * bool held_at(const State&, Direction, const GateState&) const; + * MapPlace place_of(const State&) const; + * + * and may have open_stop_risk(const State&, Direction, const GateState&) + * const, as plan_legs()'s model may have it without the gates. + * + * press() reads each tile with resolved_tile(), which makes a closed gate a + * wall. One-way warps (MapWarp::one_way) are the game's to take as any warp: + * the model leads the player to the warp's arrival, and the maps give no way + * back from it, so a route takes it forward only. + * + */ + +#ifndef PokemonAutomation_Pokemon_GatedPlanner_H +#define PokemonAutomation_Pokemon_GatedPlanner_H + +#include +#include +#include +#include +#include "Pokemon_ConnectedMaps.h" +#include "Pokemon_GateTiles.h" +#include "Pokemon_GatedTypes.h" +#include "Pokemon_LegPlanner.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A step model that weighs an open stop (see the top of this file). +template +concept HasOpenStopRisk = requires (const Inner& inner, const typename Inner::State& state, const GateState& gates){ + { inner.open_stop_risk(state, Direction::NORTH, gates) } -> std::convertible_to; +}; + +// The game's step model, wrapped: see the top of this file. +template +class GatedModel{ +public: + using InnerState = typename Inner::State; + using State = GatedState; + + struct StateHash{ + size_t operator()(const State& state) const{ + return typename Inner::StateHash()(state.inner) * 31 + std::hash()(state.gates); + } + }; + + // `inner` and `world` must outlive the model. + GatedModel(const Inner& inner, const ConnectedMaps& world, const GateRules& rules) + : m_inner(inner) + , m_world(world) + , m_rules(rules) + {} + + std::optional> press(const State& state, Direction direction) const{ + if (std::optional> walked = m_inner.press(state.inner, direction, state.gates)){ + return carry(*walked, state.gates); + } + const MapPlace place = m_inner.place_of(state.inner); + const MapData& map = m_world.map(place.map); + if (m_rules.card_key_held){ + if (const MapGate* gate = closed_card_key_gate_faced(map, place.tile, direction, state.gates)){ + return open_gate(state, map, *gate, direction); + } + } + if (const MapSwitch* pressed = switch_pressed(map, place.tile, direction)){ + return press_switch(state, *pressed, direction); + } + return std::nullopt; + } + + bool held_at(const State& state, Direction direction) const{ + return m_inner.held_at(state.inner, direction, state.gates); + } + + // The inner model's risk of an open stop (see Pokemon_LegPlanner.h), if + // it has one, read through the gates the stop is made in. + int open_stop_risk(const State& state, Direction direction) const requires HasOpenStopRisk{ + return m_inner.open_stop_risk(state.inner, direction, state.gates); + } + +private: + static Step carry(const Step& walked, const GateState& gates){ + Step step; + step.next = State{walked.next, gates}; + step.action = walked.action; + step.starts_leg = walked.starts_leg; + step.ends_leg = walked.ends_leg; + step.warped = walked.warped; + step.facing = walked.facing; + step.extra_cost = walked.extra_cost; + step.wild = walked.wild; + return step; + } + + // The player stays where they are, facing the gate, which is open afterwards. + Step open_gate(const State& state, const MapData& map, const MapGate& gate, Direction direction) const{ + Step step; + step.next = state; + step.next.gates.opened.insert(gate_key(map.name, gate.id)); + step.action = ACTION_OPEN_GATE; + step.ends_leg = true; + step.facing = direction; + step.extra_cost = m_rules.open_gate_cost; + return step; + } + + Step press_switch(const State& state, const MapSwitch& pressed, Direction direction) const{ + Step step; + step.next = state; + const bool now_on = pressed.toggle ? !state.gates.switch_on(pressed.id) : true; + if (now_on){ + step.next.gates.switches_on.insert(pressed.id); + }else{ + step.next.gates.switches_on.erase(pressed.id); + } + step.action = ACTION_PRESS_SWITCH; + step.ends_leg = true; + step.facing = direction; + step.extra_cost = m_rules.press_switch_cost; + return step; + } + + const Inner& m_inner; + const ConnectedMaps& m_world; + GateRules m_rules; +}; + + +// Where a plan starts: the game's state, the gates, and the way the player faces if known. +template +struct GatedStart{ + InnerState state; + GateState gates; + std::optional facing = std::nullopt; +}; + +// Where a plan ends: a state of the game where `at_goal` holds, facing `facing` if given. +template +struct GatedGoal{ + std::function at_goal; + std::optional facing = std::nullopt; +}; + +// The cheapest legs from `start` to `goal` (as plan_legs()), or nothing. +// Each leg's start and end carry the gate state; gate_change_of() says what +// an ACTION leg did to it. +template +std::optional>>> plan_gated_legs( + const Inner& inner, const ConnectedMaps& world, const GateRules& rules, + const GatedStart& start, + const GatedGoal& goal, + const LegCosts& costs = LegCosts() +); + +// What a leg did to the gates: the gate it opened, the switch it flipped. +template +GateChange gate_change_of(const Leg>& leg); + +// The gate state after the last of `legs`, or `before` if there are none. +template +GateState gates_after(const GateState& before, const std::vector>>& legs); + + +template +std::optional>>> plan_gated_legs( + const Inner& inner, const ConnectedMaps& world, const GateRules& rules, + const GatedStart& start, + const GatedGoal& goal, + const LegCosts& costs +){ + using State = GatedState; + const GatedModel model(inner, world, rules); + return plan_legs( + model, State{start.state, start.gates}, start.facing, + std::function([&](const State& state){ + return goal.at_goal(state.inner); + }), + goal.facing, costs + ); +} + +template +GateChange gate_change_of(const Leg>& leg){ + return gate_change_between(leg.start.gates, leg.end.gates); +} + +template +GateState gates_after(const GateState& before, const std::vector>>& legs){ + return legs.empty() ? before : legs.back().end.gates; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedTypes.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedTypes.h new file mode 100644 index 0000000000..70d1b3a4e1 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GatedTypes.h @@ -0,0 +1,49 @@ +/* Gated Types + * + * From: https://github.com/PokemonAutomation/ + * + * What the gated planner (Pokemon_GatedPlanner.h) shares with the games + * that plan with it: its actions, rules, and search state. + * + */ + +#ifndef PokemonAutomation_Pokemon_GatedTypes_H +#define PokemonAutomation_Pokemon_GatedTypes_H + +#include "Pokemon_GateState.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// The Step::action of the legs the wrapper adds. A game's own actions must +// differ from these. +constexpr int ACTION_OPEN_GATE = 1000; +// See ACTION_OPEN_GATE: the leg that presses a statue. +constexpr int ACTION_PRESS_SWITCH = 1001; + +// What the story lets a plan do, and what it costs. +struct GateRules{ + // The story state says the player holds the Card Key: a plan may open card-key gates. + bool card_key_held = false; + // Cost of opening a gate or pressing a statue, on top of LegCosts::per_tile: + // the dialog, and for a statue its yes/no. + int open_gate_cost = 10; + int press_switch_cost = 20; +}; + + +// The game's state and the gate state. +template +struct GatedState{ + InnerState inner; + GateState gates; + + bool operator==(const GatedState& other) const = default; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.h index 29952d347e..6fda4044c8 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.h @@ -10,6 +10,7 @@ #ifndef PokemonAutomation_Pokemon_Grid_H #define PokemonAutomation_Pokemon_Grid_H +#include #include #include #include @@ -27,6 +28,8 @@ struct TilePos{ TilePos next(Direction direction) const; bool operator==(const TilePos& other) const = default; + // x, then y: an order for sets and maps of tiles, not a walking order. + auto operator<=>(const TilePos& other) const = default; }; // Formats a TilePos as "(x, y)". std::string to_string(const TilePos& pos); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp index 0d2db0642b..eea9549166 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegPlanner_Tests.cpp @@ -329,18 +329,18 @@ UnitTestResult test_unreachable(){ } -struct LegPlannerInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct LegPlannerTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct LegPlannerExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct LegPlannerTestCase{ - LegPlannerInput input; - LegPlannerExpectation expectation; + Input input; + Expectation expectation; }; class Test_LegPlanner : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h index c1a7401c3b..c8b79dc4e6 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegTypes.h @@ -2,7 +2,8 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_LegWalker.h, unchanged; it includes this header. + * A leg of a route walk: what to walk (LegSpec) and what the walk found (LegResult). + * Pokemon_LegWalker.h builds on it. * */ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h index 31be625cb4..c00ecc7910 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker.h @@ -68,8 +68,7 @@ LegResult walk_leg_with(const LegSpec& leg, const LegCalls& calls, size_t max_in // keeps whether it fired. A warp's fade can be over before the hold onto // the warp ends, so a wait for it that starts after the hold sees nothing: // the walk watches the hold with this, then waits on with the same watcher -// if it has not fired (FRLG 00.27, console B, 2026-11-09 01:41, the warp to -// CeruleanCity: the watch started 1.3 s into the hold and missed the fade). +// if it has not fired. class WatchAlong : public VisualInferenceCallback{ public: explicit WatchAlong(VisualInferenceCallback& watcher) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp index e676450cb0..10e2593ab0 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_LegWalker_Tests.cpp @@ -57,13 +57,13 @@ struct ScriptedLeg{ // An interrupt set off by step `step`, seen DELAY after it ends. HoldOutcome after_step(int step){ - return HoldOutcome{0, TILE * step + DELAY}; + return HoldOutcome{.interrupt = 0, .elapsed = TILE * step + DELAY}; } UnitTestResult test_hold_times(){ - const LegSpec open{Direction::EAST, 4, false, TILE}; - const LegSpec wall{Direction::EAST, 4, true, TILE}; + const LegSpec open{.direction = Direction::EAST, .tiles = 4, .to_wall = false, .tile_time = TILE}; + const LegSpec wall{.direction = Direction::EAST, .tiles = 4, .to_wall = true, .tile_time = TILE}; if (leg_hold(open, 4) != TILE * 3 + TILE / 2){ return std::format("Open leg: {}ms", leg_hold(open, 4).count()); } @@ -83,7 +83,7 @@ UnitTestResult test_hold_times(){ } UnitTestResult test_tiles_before_interrupt(){ - const LegSpec leg{Direction::EAST, 8, false, TILE}; + const LegSpec leg{.direction = Direction::EAST, .tiles = 8, .to_wall = false, .tile_time = TILE}; for (int step = 0; step <= 8; step++){ for (Milliseconds jitter : {-100ms, 0ms, 100ms}){ const int walked = tiles_before_interrupt(leg, TILE * step + DELAY + jitter, DELAY, 8); @@ -104,7 +104,7 @@ UnitTestResult test_tiles_before_interrupt(){ UnitTestResult test_wall_leg_walked_again(){ ScriptedLeg script; script.outcomes = {after_step(2)}; - const LegSpec leg{Direction::NORTH, 6, true, TILE}; + const LegSpec leg{.direction = Direction::NORTH, .tiles = 6, .to_wall = true, .tile_time = TILE}; const LegResult result = walk_leg_with(leg, script.calls(), 5); if (script.holds.size() != 2 || script.holds[1] != leg_hold(leg, 6)){ return "Expected the whole leg held again."; @@ -118,7 +118,7 @@ UnitTestResult test_wall_leg_walked_again(){ UnitTestResult test_open_leg_rest_walked(){ ScriptedLeg script; script.outcomes = {after_step(2)}; - const LegSpec leg{Direction::NORTH, 6, false, TILE}; + const LegSpec leg{.direction = Direction::NORTH, .tiles = 6, .to_wall = false, .tile_time = TILE}; const LegResult result = walk_leg_with(leg, script.calls(), 5); if (script.holds.size() != 2 || script.holds[1] != leg_hold(leg, 4)){ return "Expected the remaining 4 tiles held."; @@ -132,7 +132,7 @@ UnitTestResult test_open_leg_rest_walked(){ UnitTestResult test_open_leg_interrupted_at_end(){ ScriptedLeg script; script.outcomes = {after_step(6)}; - const LegSpec leg{Direction::NORTH, 6, false, TILE}; + const LegSpec leg{.direction = Direction::NORTH, .tiles = 6, .to_wall = false, .tile_time = TILE}; walk_leg_with(leg, script.calls(), 5); if (script.holds.size() != 1){ return "Nothing was left to walk after the last step."; @@ -145,7 +145,7 @@ UnitTestResult test_open_leg_interrupted_at_end(){ UnitTestResult test_open_leg_stops(){ ScriptedLeg script; script.outcomes = {after_step(2)}; - LegSpec leg{Direction::NORTH, 6, false, TILE}; + LegSpec leg{.direction = Direction::NORTH, .tiles = 6, .to_wall = false, .tile_time = TILE}; leg.stop_on_interrupt = true; const LegResult result = walk_leg_with(leg, script.calls(), 5); if (script.holds.size() != 1 || !result.stopped || result.exact || script.cleared.size() != 1){ @@ -157,12 +157,12 @@ UnitTestResult test_open_leg_stops(){ return true; } -// Console B, 2026-11-01, run 16: held south into a sign, the leg to a wall -// was interrupted by its message 600ms into every hold, six times. +// Held south into a sign: the leg to a wall is interrupted by the sign's +// message 600ms into every hold, again and again. UnitTestResult test_wall_leg_blocked(){ ScriptedLeg script; - script.outcomes = {HoldOutcome{0, 2200ms}, HoldOutcome{0, 600ms}, HoldOutcome{0, 600ms}}; - LegSpec leg{Direction::SOUTH, 23, true, TILE}; + script.outcomes = {HoldOutcome{.interrupt = 0, .elapsed = 2200ms}, HoldOutcome{.interrupt = 0, .elapsed = 600ms}, HoldOutcome{.interrupt = 0, .elapsed = 600ms}}; + LegSpec leg{.direction = Direction::SOUTH, .tiles = 23, .to_wall = true, .tile_time = TILE}; leg.stop_if_blocked = true; const LegResult result = walk_leg_with(leg, script.calls(), 5); if (script.holds.size() != 2 || !result.stopped){ @@ -176,7 +176,7 @@ UnitTestResult test_too_many_interruptions(){ for (int c = 0; c < 4; c++){ script.outcomes.push_back(after_step(0)); } - const LegSpec leg{Direction::NORTH, 6, true, TILE}; + const LegSpec leg{.direction = Direction::NORTH, .tiles = 6, .to_wall = true, .tile_time = TILE}; try{ walk_leg_with(leg, script.calls(), 3); }catch (std::runtime_error&){ @@ -224,18 +224,18 @@ UnitTestResult test_watch_along(){ } -struct LegWalkerInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct LegWalkerTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct LegWalkerExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct LegWalkerTestCase{ - LegWalkerInput input; - LegWalkerExpectation expectation; + Input input; + Expectation expectation; }; class Test_LegWalker : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp index 0f44118a9e..227ca7ffcd 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.cpp @@ -43,6 +43,7 @@ constexpr std::pair GLYPHS[] = { {'o', TileKind::STOP_SPIN}, {'H', TileKind::FALL_HOLE}, {'B', TileKind::STRENGTH_BUTTON}, + {'G', TileKind::GATE}, }; constexpr std::pair WARP_ENTRIES[] = { @@ -368,6 +369,7 @@ MapWarp read_warp(const JsonObject& object, const std::string& where){ warp.x = pos.x; warp.y = pos.y; warp.enter = read_warp_entry(object, where); + warp.one_way = optional_bool(object, "one_way", false, where); const bool has_map = object.get_value("to_map") != nullptr; const bool has_point = object.get_value("to_point") != nullptr; if (has_map != has_point){ @@ -487,6 +489,126 @@ MapPatch read_patch(const JsonObject& object, const std::string& where){ return patch; } +// The tiles of a gate or a coordinate pair, `[x, y]` each. +std::vector read_pair_list(const JsonObject& object, const std::string& key, const std::string& where){ + const JsonArray* array = optional_array(object, key, where); + if (array == nullptr || array->empty()){ + throw ParseException(std::format("{}{} is not a non-empty list of [x, y].", where, key)); + } + std::vector pairs; + for (size_t c = 0; c < array->size(); c++){ + pairs.push_back(read_pair((*array)[c], std::format("{}{}[{}]", where, key, c))); + } + return pairs; +} + +TilePos read_pair_field(const JsonObject& object, const std::string& key, const std::string& where){ + return read_pair(read_field(object, key, where), std::format("{}{}", where, key)); +} + +bool read_on_off(const JsonObject& object, const std::string& key, const std::string& where){ + const std::string text = read_string(object, key, where); + if (text != "on" && text != "off"){ + throw ParseException(std::format("{}{} \"{}\" is not on or off.", where, key, text)); + } + return text == "on"; +} + +// A gate is a card-key door (opens_by and flag) or follows a switch (switch +// and open_when); never both. +MapGate read_gate(const std::string& id, const JsonObject& object, const std::string& where){ + MapGate gate; + gate.id = id; + gate.tiles = read_pair_list(object, "tiles", where); + const std::string glyph = read_string(object, "open_glyph", where); + const std::optional open = glyph.size() == 1 ? tile_from_glyph(glyph[0]) : std::nullopt; + if (!open || *open == TileKind::GATE){ + throw ParseException(std::format("{}open_glyph \"{}\" is not a tile glyph other than G.", where, glyph)); + } + gate.open_tile = *open; + const std::string new_game = read_string(object, "new_game", where); + if (new_game != "open" && new_game != "closed"){ + throw ParseException(std::format("{}new_game \"{}\" is not open or closed.", where, new_game)); + } + gate.open_at_new_game = new_game == "open"; + const bool by_key = object.get_value("opens_by") != nullptr || object.get_value("flag") != nullptr; + const bool by_switch = object.get_value("switch") != nullptr || object.get_value("open_when") != nullptr; + if (by_key == by_switch){ + throw ParseException(std::format("{}needs opens_by and flag, or switch and open_when, and not both.", where)); + } + if (by_key){ + const std::string opens_by = read_string(object, "opens_by", where); + if (opens_by != "card_key_face_a"){ + throw ParseException(std::format("{}opens_by \"{}\" is not card_key_face_a.", where, opens_by)); + } + gate.kind = GateKind::CARD_KEY; + gate.flag = read_string(object, "flag", where); + }else{ + gate.kind = GateKind::SWITCH; + gate.switch_id = read_string(object, "switch", where); + gate.open_when_on = read_on_off(object, "open_when", where); + } + return gate; +} + +std::map read_gates(const JsonObject& root, const std::string& where){ + std::map gates; + const JsonObject* object = optional_object(root, "gates", where); + if (object == nullptr){ + return gates; + } + for (const auto& [id, value] : *object){ + const std::string gate_where = std::format("{}gates.{}", where, id); + gates[id] = read_gate(id, as_object(value, gate_where), gate_where + "."); + } + return gates; +} + +MapStatue read_statue(const JsonObject& object, const std::string& where){ + MapStatue statue; + statue.tile = read_pair_field(object, "coord", where); + statue.face_from = read_pair_field(object, "face_from", where); + statue.facing = read_direction(object, "facing", where); + return statue; +} + +MapSwitch read_switch(const std::string& id, const JsonObject& object, const std::string& where){ + MapSwitch result; + result.id = id; + result.flag = read_string(object, "flag", where); + const JsonValue* toggle = object.get_value("toggle"); + if (toggle != nullptr && !toggle->is_boolean()){ + throw ParseException(std::format("{}toggle is not true or false.", where)); + } + result.toggle = toggle == nullptr || toggle->to_boolean_default(true); + const JsonArray* floors = optional_array(object, "floors", where); + if (floors == nullptr || floors->empty()){ + throw ParseException(std::format("{}floors is not a non-empty list of map names.", where)); + } + for (size_t c = 0; c < floors->size(); c++){ + const std::string* floor = (*floors)[c].to_string(); + if (floor == nullptr){ + throw ParseException(std::format("{}floors[{}] is not a string.", where, c)); + } + result.floors.push_back(*floor); + } + result.statues = read_list(object, "statues", where, read_statue); + return result; +} + +std::map read_switches(const JsonObject& root, const std::string& where){ + std::map switches; + const JsonObject* object = optional_object(root, "switches", where); + if (object == nullptr){ + return switches; + } + for (const auto& [id, value] : *object){ + const std::string switch_where = std::format("{}switches.{}", where, id); + switches[id] = read_switch(id, as_object(value, switch_where), switch_where + "."); + } + return switches; +} + void check_inside(const Grid& tiles, const TilePos& pos, const std::string& where){ if (!tiles.contains(pos)){ @@ -527,6 +649,42 @@ void check_places(const MapData& map, const std::string& where){ } } +// Every gate tile is a G tile, in one gate only; every G tile is in a +// gate; a gate follows a switch the map lists; a statue stands on a wall +// and is faced from a tile inside the map. +void check_gates(const MapData& map, const std::string& where){ + std::set in_gate; + for (const auto& [id, gate] : map.gates){ + for (size_t c = 0; c < gate.tiles.size(); c++){ + const std::string tile_where = std::format("{}gates.{}.tiles[{}]", where, id, c); + check_inside(map.tiles, gate.tiles[c], tile_where); + if (map.tiles.at(gate.tiles[c]) != TileKind::GATE){ + throw ParseException(std::format("{} {} is not a G tile.", tile_where, to_string(gate.tiles[c]))); + } + if (!in_gate.insert(gate.tiles[c]).second){ + throw ParseException(std::format("{} {} is in another gate too.", tile_where, to_string(gate.tiles[c]))); + } + } + if (gate.kind == GateKind::SWITCH && !map.switches.contains(gate.switch_id)){ + throw ParseException(std::format("{}gates.{}.switch \"{}\" is not in switches.", where, id, gate.switch_id)); + } + } + for (int y = 0; y < map.tiles.height; y++){ + for (int x = 0; x < map.tiles.width; x++){ + if (map.tiles.at({x, y}) == TileKind::GATE && !in_gate.contains(TilePos{x, y})){ + throw ParseException(std::format("{}tiles has a G at {} that no gate lists.", where, to_string(TilePos{x, y}))); + } + } + } + for (const auto& [id, result] : map.switches){ + for (size_t c = 0; c < result.statues.size(); c++){ + const std::string statue_where = std::format("{}switches.{}.statues[{}]", where, id, c); + check_inside(map.tiles, result.statues[c].tile, statue_where); + check_inside(map.tiles, result.statues[c].face_from, statue_where); + } + } +} + } // namespace @@ -549,10 +707,13 @@ MapData parse_map(const JsonValue& json, const std::string& source_name){ map.flag_sets = read_flag_sets(root, where); map.connections = read_list(root, "connections", where, read_connection); map.patches = read_list(root, "patches", where, read_patch); + map.gates = read_gates(root, where); + map.switches = read_switches(root, where); check_places(map, where); for (const MapPatch& patch : map.patches){ cell_at(TilePos{patch.x, patch.y}, map.tiles) = patch.glyph; } + check_gates(map, where); return map; } diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h index 6b4d923fbf..35d485e577 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData.h @@ -26,9 +26,19 @@ * "triggers": [{"name": "mom_warning", "box": {"x0": 1, "y0": 2, "x1": 1, "y1": 2}, "when": "00.01"}, ...], * "flag_sets": {"after_00.01": ["FLAG_HIDE_MOM", ...], ...}, * "connections": [{"side": "east", "to_map": "Route 1", "offset": 0}, ...], - * "patches": [{"x": 2, "y": 1, "glyph": "#", "measured_by": "run 3, 2026-10-30"}, ...] + * "patches": [{"x": 2, "y": 1, "glyph": "#", "measured_by": "run 3, 2026-10-30"}, ...], + * "gates": {"door_1": {"tiles": [[7, 9], [7, 10]], "open_glyph": ".", "new_game": "closed", + * "opens_by": "card_key_face_a", "flag": "FLAG_SILPH_5F_DOOR_1"}, + * "barrier_1": {"tiles": [[22, 10]], "open_glyph": "~", "new_game": "closed", + * "switch": "mansion", "open_when": "on"}, ...}, + * "switches": {"mansion": {"flag": "FLAG_POKEMON_MANSION_SWITCH_STATE", "toggle": true, + * "floors": ["PokemonMansion_1F", ...], + * "statues": [{"coord": [5, 5], "face_from": [5, 6], "facing": "north"}]}} * } * + * A warp may carry "one_way": true (a drop). A map's tiles show each gate + * tile as 'G', and every 'G' tile is in a gate. + * * `name`, `source` and `tiles` are required; everything else may be left * out. Which game's planner reads these maps, and how, is the game's * business. @@ -47,6 +57,7 @@ #include "Common/Cpp/Json/JsonValue.h" #include "Pokemon_Grid.h" #include "Pokemon_MapFeatures.h" +#include "Pokemon_MapGates.h" namespace PokemonAutomation{ namespace Pokemon{ @@ -76,6 +87,12 @@ struct MapData{ std::map> flag_sets; std::vector connections; std::vector patches; + // The barriers the story opens, by id. Every GATE tile of `tiles` is in + // exactly one gate. + std::map gates; + // The switches (by id) that gates of this map follow or that have a + // statue on it. + std::map switches; }; // Reads legacy/unmarked v1 or compact pokesim-runtime-map/2 JSON. diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp index 2dbe86b27e..9e1b7b1d50 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp @@ -422,18 +422,18 @@ UnitTestResult test_built_in_maps(){ return true; } -struct MapDataTestInput{ - std::string name; - UnitTestResult (*test)(); -}; +struct MapDataTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; -struct MapDataTestExpectation{ - std::string_view description; -}; + struct Expectation{ + std::string_view description; + }; -struct MapDataTestCase{ - MapDataTestInput input; - MapDataTestExpectation expectation; + Input input; + Expectation expectation; }; class Test_MapData : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h index e7af9fd8be..fd44902707 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapFeatures.h @@ -2,7 +2,7 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_MapData.h, unchanged; it includes this header. + * The features a map's tiles can carry. Pokemon_MapData.h builds on it. * */ @@ -31,6 +31,9 @@ struct MapWarp{ int y = 0; WarpEntry enter = WarpEntry::WALK_INTO; std::optional to; + // A drop (a hole the player falls through): the landing has no way back + // up, so a route takes it forward only. + bool one_way = false; }; // Type classification for interactive map objects. diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapGates.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapGates.h new file mode 100644 index 0000000000..8c2ef63083 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapGates.h @@ -0,0 +1,70 @@ +/* Map Gates + * + * From: https://github.com/PokemonAutomation/ + * + * The barriers a map's story opens (card-key doors, switch-driven walls) and + * the statues that press the switches. Pokemon_MapData.h holds them in a + * map's `gates` and `switches`; Pokemon_GateState.h says which are open. + * + */ + +#ifndef PokemonAutomation_Pokemon_MapGates_H +#define PokemonAutomation_Pokemon_MapGates_H + +#include +#include +#include "Pokemon_Grid.h" +#include "Pokemon_MapTiles.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What opens a gate. +enum class GateKind{ + CARD_KEY, // "card_key_face_a": faced from a side tile and opened with A, once the player holds the Card Key + SWITCH, // a switch's state (MapSwitch): open while the switch is `open_when_on` +}; + +// A barrier the story opens or closes: some tiles of the map that are `G` +// in `tiles`. Open, they read as `open_tile`; closed, as a wall. +struct MapGate{ + std::string id; + std::vector tiles; + TileKind open_tile = TileKind::OPEN; + // Whether a new game has it open. + bool open_at_new_game = false; + GateKind kind = GateKind::CARD_KEY; + // CARD_KEY: the event flag the game sets once it is opened. + std::string flag = {}; + // SWITCH: the switch (a key of MapData::switches, shared by the + // maps in its `floors`), and the state in which this gate is open. + std::string switch_id = {}; + bool open_when_on = false; +}; + +// A statue that presses a switch: the player stands on `face_from`, faces +// `facing` and presses A. The statue is the wall tile `tile`. +struct MapStatue{ + TilePos tile; + TilePos face_from; + Direction facing = Direction::NORTH; +}; + +// A switch the map's gates follow. One state is shared by every map in +// `floors` (Pokemon Mansion's statue switch, an event flag): pressing a +// statue flips it, and each floor redraws its gates when it loads. +// `statues` are the statues on this map only. +struct MapSwitch{ + std::string id; + std::string flag; + bool toggle = true; + std::vector floors; + std::vector statues; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h index 2184680cdf..16500f1060 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h @@ -2,7 +2,7 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_MapData.h, unchanged; it includes this header. + * A map's tile grid. Pokemon_MapData.h builds on it. * */ @@ -47,6 +47,10 @@ enum class TileKind : uint8_t{ STOP_SPIN, // 'o' open; where a spin's slide stops FALL_HOLE, // 'H' open; a hole that drops the player a floor STRENGTH_BUTTON,// 'B' open; Victory Road's switch for a boulder + GATE, // 'G' a wall until the story opens it: the map's `gates` + // table names the gate, and Pokemon_GateState.h says + // whether it is open (a reader that ignores gates + // treats it as a wall) }; // The tile a glyph stands for, or nothing if it isn't one. std::optional tile_from_glyph(char glyph); diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h new file mode 100644 index 0000000000..2b7d734b88 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics.h @@ -0,0 +1,119 @@ +/* Move Mechanics + * + * From: https://github.com/PokemonAutomation/ + * + * How each game moves the player for a press, as measured on the console: + * one entry per game, read by that game's walker and by its sim. + * + */ + +#ifndef PokemonAutomation_Pokemon_MoveMechanics_H +#define PokemonAutomation_Pokemon_MoveMechanics_H + +#include +#include "Common/Cpp/Time.h" +#include "Pokemon_Grid.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// How the walker presses an open leg, one that ends short of a wall. +enum class OpenLegPress{ + STEP_TAPS, // a step tap a tile: the count is exact + TIMED_HOLD, // one hold, timed by the tile time +}; + +// Time per tile along each axis of the screen. +struct TileTime{ + Milliseconds across{}; // east or west + Milliseconds up_down{}; // north or south + + constexpr Milliseconds along(Direction direction) const{ + return direction == Direction::EAST || direction == Direction::WEST ? across : up_down; + } +}; + +// A tap that takes one step: the press, and the release before the next +// press. Their sum is the time per tapped tile. +struct StepTap{ + Milliseconds hold{}; + Milliseconds release{}; +}; + +// One way of moving: walking, running or riding. +struct Gait{ + TileTime tile; + // The step tap in this gait; a game's taps differ by gait (FRLG's + // Bicycle taps far faster than its walk). + StepTap tap; + OpenLegPress open_legs = OpenLegPress::STEP_TAPS; +}; + +// How one game moves the player: its turn tap, and a tile time and step +// tap per gait. +struct MoveMechanics{ + // A tap that turns a player facing another way, without a step. + Milliseconds turn_tap{}; + // From pressing, standing still, to the first step under way. + Milliseconds start_delay{}; + Gait walk; + // B held, once the player has the Running Shoes. + Gait run; + // None where the walker does not ride yet. + std::optional bike; +}; + + +// Brilliant Diamond and Shining Pearl, measured on console B. The camera +// tilts, so a row takes longer than a column. D-pad taps move exactly a +// tile each, while a held run overshoots about 3 tiles in 10 (2026-11-09, +// Jubilife), so open legs are tapped. Taps: PokemonBDSP_AutoStory_RouteInput.h; +// tile times: PokemonBDSP_AutoStory_RouteTiming.h. +inline constexpr MoveMechanics BDSP_MOVE_MECHANICS{ + .turn_tap = Milliseconds(50), + .start_delay = Milliseconds(250), + .walk = { + .tile = {.across = Milliseconds(160), .up_down = Milliseconds(240)}, + .tap = {.hold = Milliseconds(160), .release = Milliseconds(640)}, + .open_legs = OpenLegPress::STEP_TAPS, + }, + .run = { + .tile = {.across = Milliseconds(100), .up_down = Milliseconds(150)}, + .tap = {.hold = Milliseconds(160), .release = Milliseconds(640)}, + .open_legs = OpenLegPress::STEP_TAPS, + }, + .bike = std::nullopt, +}; + +// FireRed and LeafGreen, measured on console B: a walking tile is 16 +// frames, running 8, and a held leg stops where its time says, so open +// legs on foot are timed holds; on the Bicycle they are counted in taps, +// 40 ms at one per 100 ms (BIKE_TAP_PERIOD_WORKED; at a 60 ms period one +// tap in 12 drops). The walker's holds count no start delay. +// Measurements: PokemonFRLG_MovementMechanics.h and +// PokemonFRLG_BikeSpinMechanics.h. +inline constexpr MoveMechanics FRLG_MOVE_MECHANICS{ + .turn_tap = Milliseconds(40), + .start_delay = Milliseconds(0), + .walk = { + .tile = {.across = Milliseconds(267), .up_down = Milliseconds(267)}, + .tap = {.hold = Milliseconds(66), .release = Milliseconds(700)}, + .open_legs = OpenLegPress::TIMED_HOLD, + }, + .run = { + .tile = {.across = Milliseconds(133), .up_down = Milliseconds(133)}, + .tap = {.hold = Milliseconds(66), .release = Milliseconds(700)}, + .open_legs = OpenLegPress::TIMED_HOLD, + }, + .bike = Gait{ + .tile = {.across = Milliseconds(100), .up_down = Milliseconds(100)}, + .tap = {.hold = Milliseconds(40), .release = Milliseconds(60)}, + .open_legs = OpenLegPress::STEP_TAPS, + }, +}; + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp new file mode 100644 index 0000000000..fced1d74eb --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp @@ -0,0 +1,130 @@ +/* Move Mechanics Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon_MoveMechanics.h" +#include "Pokemon_MoveMechanics_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ +namespace{ + + +struct MoveMechanicsCase{ + struct Input{ + std::string_view game; + MoveMechanics mechanics; + }; + struct Expectation{ + // How the walker presses an open leg on foot (BDSP taps, FRLG + // timed holds). + OpenLegPress open_legs_on_foot; + }; + Input input; + Expectation expectation; +}; + +// Why `faster` is not faster than `slower` on both axes, if it is not. +std::optional not_faster(std::string_view faster_name, const Gait& faster, std::string_view slower_name, const Gait& slower){ + if (faster.tile.across >= slower.tile.across || faster.tile.up_down >= slower.tile.up_down){ + return std::format("{} ({}/{} ms) is not faster than {} ({}/{} ms).", + faster_name, faster.tile.across.count(), faster.tile.up_down.count(), + slower_name, slower.tile.across.count(), slower.tile.up_down.count()); + } + return std::nullopt; +} + +// Why the turn tap would step on foot in `gait`, if it would: a turn tap +// must be shorter than the gait's step tap. +std::optional turn_steps(std::string_view gait_name, const Gait& gait, Milliseconds turn_tap){ + if (turn_tap >= gait.tap.hold){ + return std::format("The turn tap ({} ms) is not shorter than the {} step tap ({} ms).", + turn_tap.count(), gait_name, gait.tap.hold.count()); + } + return std::nullopt; +} + +// Why a gait's step tap is unusable, if it is: both its press and its +// release must take time. +std::optional empty_tap(std::string_view gait_name, const Gait& gait){ + if (gait.tap.hold <= Milliseconds(0) || gait.tap.release <= Milliseconds(0)){ + return std::format("The {} step tap is {} ms pressed, {} ms released; both must be over 0.", + gait_name, gait.tap.hold.count(), gait.tap.release.count()); + } + return std::nullopt; +} + +std::string_view open_leg_press_name(OpenLegPress press){ + return press == OpenLegPress::STEP_TAPS ? "step taps" : "a timed hold"; +} + +// Why `gait` presses its open legs other than `expected`, if it does. +std::optional wrong_open_legs(std::string_view gait_name, const Gait& gait, OpenLegPress expected){ + if (gait.open_legs != expected){ + return std::format("Open legs {} are pressed as {}, expected {}.", + gait_name, open_leg_press_name(gait.open_legs), open_leg_press_name(expected)); + } + return std::nullopt; +} + +class Test_MoveMechanics : public UnitTest{ +public: + explicit Test_MoveMechanics(MoveMechanicsCase scenario) + : UnitTest(std::format("Pokemon::MoveMechanics - {}", scenario.input.game)), m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const MoveMechanics& game = m_scenario.input.mechanics; + const OpenLegPress expected = m_scenario.expectation.open_legs_on_foot; + const std::optional failures[] = { + empty_tap("walking", game.walk), + empty_tap("running", game.run), + game.bike ? empty_tap("bike", *game.bike) : std::nullopt, + turn_steps("walking", game.walk, game.turn_tap), + turn_steps("running", game.run, game.turn_tap), + not_faster("running", game.run, "walking", game.walk), + game.bike ? not_faster("the bike", *game.bike, "running", game.run) : std::nullopt, + wrong_open_legs("walking", game.walk, expected), + wrong_open_legs("running", game.run, expected), + }; + for (const std::optional& failure : failures){ + if (failure){ + return *failure; + } + } + return true; + } +private: + MoveMechanicsCase m_scenario; +}; + +const MoveMechanicsCase MOVE_MECHANICS_CASES[] = { + { + .input = {.game = "BDSP", .mechanics = BDSP_MOVE_MECHANICS}, + .expectation = {.open_legs_on_foot = OpenLegPress::STEP_TAPS}, + }, + { + .input = {.game = "FRLG", .mechanics = FRLG_MOVE_MECHANICS}, + .expectation = {.open_legs_on_foot = OpenLegPress::TIMED_HOLD}, + }, +}; + + +} // namespace + +void add_tests_MoveMechanics(UnitTestDatabase& database){ + for (const MoveMechanicsCase& scenario : MOVE_MECHANICS_CASES){ + database.add(scenario); + } +} + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.h new file mode 100644 index 0000000000..a545eae699 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.h @@ -0,0 +1,22 @@ +/* Move Mechanics Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_MoveMechanics_Tests_H +#define PokemonAutomation_Pokemon_MoveMechanics_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers the checks on each game's movement table. +void add_tests_MoveMechanics(UnitTestDatabase& database); + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp index 19ac59cf41..39889a01c1 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.cpp @@ -33,6 +33,10 @@ std::string to_string(const RouteLogLeg& leg){ return std::format("surf {}", direction); case RouteLegAction::FACE: return std::format("face {}", direction); + case RouteLegAction::OPEN_GATE: + return std::format("open gate {}", direction); + case RouteLegAction::PRESS_SWITCH: + return std::format("press switch {}", direction); case RouteLegAction::WALK: break; } diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h index 17cdaef020..4a907f056d 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog.h @@ -4,8 +4,7 @@ * * The log lines a route walk writes, shared by the games' walkers so that * every game's log reads the same and devtools/maps can draw any run's - * routes from it. These are BDSP AutoStory's route lines, lifted from - * PokemonBDSP_AutoStory_RouteWalk.cpp, with what the other games need: + * routes from it. These are BDSP AutoStory's route lines, with what the other games need: * * [Route] To the grass: plan from Route 202 (15, 25), Route 202 (16, 25): east 15 (to wall) to Route 202 (23, 25), Route 202 (30, 26); north 5 (to wall) to Route 202 (23, 24) * [Route] Leg 1/2: east 15 (to wall) to Route 202 (23, 25), Route 202 (30, 26) diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogLegs.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogLegs.h index bfe6778a8e..c1da9ce723 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogLegs.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogLegs.h @@ -2,7 +2,7 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_RouteLog.h, unchanged; it includes this header. + * The legs of a route as its log lines name them. Pokemon_RouteLog.h builds on it. * */ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h index c98a70d243..34258fc7e0 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h @@ -2,7 +2,7 @@ * * From: https://github.com/PokemonAutomation/ * - * Split out of Pokemon_RouteLog.h, unchanged; it includes this header. + * The types of a route log's lines. Pokemon_RouteLog.h builds on it. * */ @@ -38,6 +38,10 @@ enum class RouteLegAction{ WALK, SURF, FACE, + // Face a gate and press A: a card-key gate opens. + OPEN_GATE, + // Face a statue and press A, then Yes: a switch flips. + PRESS_SWITCH, }; // How a leg ends: at a wall, on a warp, or where it is timed to. diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp index 843fc32db0..5715211f01 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp @@ -22,16 +22,16 @@ namespace Pokemon{ namespace{ -struct RouteLogInput{ - std::string name; - std::string line; -}; -struct RouteLogExpectation{ - std::string expected; -}; struct RouteLogTestCase{ - RouteLogInput input; - RouteLogExpectation expectation; + struct Input{ + std::string name; + std::string line; + }; + struct Expectation{ + std::string expected; + }; + Input input; + Expectation expectation; }; class Test_RouteLog : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp index 343416ca4d..81a28b60e1 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp @@ -3,14 +3,15 @@ * From: https://github.com/PokemonAutomation/ */ #include -#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Json/JsonArray.h" #include "Common/Cpp/Json/JsonObject.h" #include "Pokemon_MapData.h" #include "Pokemon_RuntimeMap.h" -#ifndef PA_RUNTIME_MAP_STANDALONE +#ifdef PA_RUNTIME_MAP_STANDALONE +#include +#else #include "Pokemon_RuntimeMap_Tests.h" #endif @@ -18,19 +19,19 @@ namespace PokemonAutomation{ namespace Pokemon{ namespace{ -struct RuntimeMapInput{ - std::string_view name; - std::string_view fields; -}; - -struct RuntimeMapExpectation{ - std::string_view error = {}; - std::string_view normalized_fields = {}; -}; - struct RuntimeMapCase{ - RuntimeMapInput input; - RuntimeMapExpectation expectation; + struct Input{ + std::string_view name; + std::string_view fields; + }; + + struct Expectation{ + std::string_view error = {}; + std::string_view normalized_fields = {}; + }; + + Input input; + Expectation expectation; }; const std::string GOLDEN_V2 = R"( diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_WallRecovery_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_WallRecovery_Tests.cpp index f563a0f9aa..e3a68cfaa6 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_WallRecovery_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_WallRecovery_Tests.cpp @@ -69,21 +69,21 @@ std::string describe_holds(std::span holds){ } // Inputs and expectations are separate aggregates; each registered test owns one row. -struct CorridorInput{ - std::string name; - std::vector positions; - std::optional person; - size_t budget; -}; +struct CorridorTestCase{ + struct Input{ + std::string name; + std::vector positions; + std::optional person; + size_t budget; + }; -struct CorridorExpectation{ - std::optional first_anchor; - std::vector holds; -}; + struct Expectation{ + std::optional first_anchor; + std::vector holds; + }; -struct CorridorTestCase{ - CorridorInput input; - CorridorExpectation expectation; + Input input; + Expectation expectation; }; class Test_WallRecovery : public UnitTest{ @@ -187,20 +187,20 @@ class CornerPolicy{ } }; -struct CornerInput{ - std::string name; - std::array positions; - size_t budget; -}; +struct CornerTestCase{ + struct Input{ + std::string name; + std::array positions; + size_t budget; + }; -struct CornerExpectation{ - std::optional first_anchor; - std::vector holds; -}; + struct Expectation{ + std::optional first_anchor; + std::vector holds; + }; -struct CornerTestCase{ - CornerInput input; - CornerExpectation expectation; + Input input; + Expectation expectation; }; class Test_WallRecoveryCorner : public UnitTest{ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.cpp new file mode 100644 index 0000000000..6d0bf64fb4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.cpp @@ -0,0 +1,94 @@ +/* Sim Faults + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_SimFaults.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const std::vector& fault_classes(){ + static const std::vector classes{ + FaultClass::SCENE_END_POSE, + FaultClass::SCENE_EARLY, + FaultClass::BATTLE_OPENING, + FaultClass::WILD_BATTLES, + FaultClass::LATE_FADE, + FaultClass::SLOW_FADE_IN, + FaultClass::WARP_NO_OP, + FaultClass::DARK_CAVE, + FaultClass::LOST_TAP, + FaultClass::UNSEEN_STEP, + }; + return classes; +} + +std::string_view fault_class_name(FaultClass fault){ + switch (fault){ + case FaultClass::SCENE_END_POSE: + return "scene end pose"; + case FaultClass::SCENE_EARLY: + return "scene early"; + case FaultClass::BATTLE_OPENING: + return "battle opening"; + case FaultClass::WILD_BATTLES: + return "wild battles"; + case FaultClass::LATE_FADE: + return "late fade"; + case FaultClass::SLOW_FADE_IN: + return "slow fade-in"; + case FaultClass::WARP_NO_OP: + return "warp no-op"; + case FaultClass::DARK_CAVE: + return "dark cave"; + case FaultClass::LOST_TAP: + return "lost tap"; + case FaultClass::UNSEEN_STEP: + return "unseen step"; + } + return "?"; +} + + +FaultOccurrences::FaultOccurrences(std::set faulted) + : m_numbers(std::move(faulted)) +{} + +bool FaultOccurrences::next(){ + m_chances++; + if (!m_numbers.contains(m_chances)){ + return false; + } + m_faulted++; + return true; +} + + +SimFaults::SimFaults(std::map> faulted){ + for (auto& [fault, numbers] : faulted){ + m_classes.emplace(fault, FaultOccurrences(std::move(numbers))); + } +} + +bool SimFaults::next(FaultClass fault){ + return m_classes[fault].next(); +} + +int SimFaults::chances(FaultClass fault) const{ + const auto iter = m_classes.find(fault); + return iter == m_classes.end() ? 0 : iter->second.chances(); +} + +int SimFaults::faulted(FaultClass fault) const{ + const auto iter = m_classes.find(fault); + return iter == m_classes.end() ? 0 : iter->second.faulted(); +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.h b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.h new file mode 100644 index 0000000000..f58b09b854 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.h @@ -0,0 +1,109 @@ +/* Sim Faults + * + * From: https://github.com/PokemonAutomation/ + * + * The faults the games' overworld simulations inject, shared by BDSP's + * and FRLG's: the classes of failure the consoles showed, and a counter + * per class that says which of a fault's chances to fault. A chance is + * each time the sim reaches a point where the game could fail that way + * (a tap, a warp, a step's end); a test names the chances it faults by + * number, from 1 in the order the sim reaches them. + * + * How a class is injected is each game's (its sim's knobs and its fault + * sweep); a game may inject only some of the classes. + * + */ + +#ifndef PokemonAutomation_Pokemon_SimFaults_H +#define PokemonAutomation_Pokemon_SimFaults_H + +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// A class of failure a console showed, which a sim can inject. +enum class FaultClass{ + // A step whose end the game sets (a talk, a scene, a battle) leaves the + // player on another walkable tile next to the expected one. + SCENE_END_POSE, + // A scene starts on the last tiles of the walk before it. + SCENE_EARLY, + // A battle's opening is still playing when a step starts. + BATTLE_OPENING, + // Wild battles while walking, more than a clean run meets. + WILD_BATTLES, + // A warp's fade shows late. + LATE_FADE, + // Every warp's fade-in runs long: a move right after it goes nowhere. + SLOW_FADE_IN, + // A step onto a warp shows the fade's black but does not warp. + WARP_NO_OP, + // A dark cave walked without Flash. + DARK_CAVE, + // A tap the game drops. + LOST_TAP, + // A step tap that moved the player, read as not moved. + UNSEEN_STEP, +}; + +// Every fault class, in the enum's order. +const std::vector& fault_classes(); + +// The class's name for logs: "scene end pose". +std::string_view fault_class_name(FaultClass fault); + + +// Which chances of one fault to fault: those numbered in `faulted`, +// counted from 1 as next() reaches them. +class FaultOccurrences{ +public: + FaultOccurrences() = default; + explicit FaultOccurrences(std::set faulted); + + // Counts one more chance: whether it is one to fault. + bool next(); + + // The chances counted so far. + int chances() const{ + return m_chances; + } + // How many of them were faulted. + int faulted() const{ + return m_faulted; + } + +private: + std::set m_numbers; + int m_chances = 0; + int m_faulted = 0; +}; + + +// A FaultOccurrences per fault class: a class not given counts its +// chances and faults none. +class SimFaults{ +public: + SimFaults() = default; + explicit SimFaults(std::map> faulted); + + // Counts one more chance of `fault`: whether it is one to fault. + bool next(FaultClass fault); + + // The chances of `fault` counted so far, and how many were faulted. + int chances(FaultClass fault) const; + int faulted(FaultClass fault) const; + +private: + std::map m_classes; +}; + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp new file mode 100644 index 0000000000..73b884ff6f --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp @@ -0,0 +1,182 @@ +/* Sim Faults Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The fault counters on their own: which chances a counter faults, what + * it counts, that each class counts apart, and the classes' names. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon_SimFaults.h" +#include "Pokemon_SimFaults_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +struct SimFaultsTestCase{ + struct Input{ + std::string name; + UnitTestResult (*body)(); + }; + + struct Expectation{ + std::string_view description; + }; + + Input input; + Expectation expectation; +}; + +class Test_SimFaults : public UnitTest{ +public: + explicit Test_SimFaults(SimFaultsTestCase scenario) + : UnitTest("Pokemon::Navigation - Sim faults: " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.input.body(); + } + +private: + SimFaultsTestCase m_scenario; +}; + +// What `chances` chances of FaultClass::LOST_TAP did with `faulted` +// named, taken as a game's sim takes them, a chance of +// FaultClass::WARP_NO_OP (none named) after each. +struct Counted{ + std::vector faulted_at; + int chances = 0; + int faulted = 0; + int other_chances = 0; + int other_faulted = 0; + int never_reached = 0; +}; + +Counted count(const std::set& faulted, int chances){ + SimFaults faults({{FaultClass::LOST_TAP, faulted}}); + Counted out; + for (int chance = 1; chance <= chances; chance++){ + if (faults.next(FaultClass::LOST_TAP)){ + out.faulted_at.push_back(chance); + } + faults.next(FaultClass::WARP_NO_OP); + } + out.chances = faults.chances(FaultClass::LOST_TAP); + out.faulted = faults.faulted(FaultClass::LOST_TAP); + out.other_chances = faults.chances(FaultClass::WARP_NO_OP); + out.other_faulted = faults.faulted(FaultClass::WARP_NO_OP); + out.never_reached = faults.chances(FaultClass::DARK_CAVE); + return out; +} + +// "[1, 3]". +std::string numbers_text(const std::vector& numbers){ + std::string out; + for (int number : numbers){ + if (!out.empty()){ + out += ", "; + } + out += std::format("{}", number); + } + return std::format("[{}]", out); +} + +UnitTestResult expect_counted(const std::set& faulted, int chances, const std::vector& faulted_at){ + const Counted counted = count(faulted, chances); + if (counted.faulted_at != faulted_at){ + return std::format("Faulted chances {}, expected {}.", numbers_text(counted.faulted_at), numbers_text(faulted_at)); + } + if (counted.chances != chances || counted.faulted != static_cast(faulted_at.size())){ + return std::format("Counted {} chances, {} faulted; expected {}, {}.", counted.chances, counted.faulted, chances, faulted_at.size()); + } + if (counted.other_chances != chances || counted.other_faulted != 0){ + return std::format("The other class counted {} chances, {} faulted; expected {}, 0.", counted.other_chances, counted.other_faulted, chances); + } + if (counted.never_reached != 0){ + return std::format("A class never reached counted {} chances.", counted.never_reached); + } + return true; +} + +UnitTestResult test_none_named(){ + return expect_counted({}, 3, {}); +} + +UnitTestResult test_named_from_one(){ + return expect_counted({1, 3}, 4, {1, 3}); +} + +UnitTestResult test_never_reached(){ + return expect_counted({2, 9}, 3, {2}); +} + +UnitTestResult test_no_chances(){ + return expect_counted({1}, 0, {}); +} + +UnitTestResult test_class_names(){ + std::map seen; + for (FaultClass fault : fault_classes()){ + const std::string_view name = fault_class_name(fault); + if (name == "?" || !seen.emplace(name, fault).second){ + return std::format("Fault class {} has no name of its own: {}", static_cast(fault), name); + } + } + return true; +} + +// fault_classes() restates the enum, so it must list every value: the +// names stop at the first value past the enum's last (fault_class_name() +// is a switch, so a value with no name fails to build). +UnitTestResult test_classes_match_enum(){ + const std::vector& classes = fault_classes(); + size_t named = 0; + while (fault_class_name(static_cast(named)) != "?"){ + named++; + } + if (named != classes.size()){ + return std::format("The enum has {} classes, fault_classes() lists {}.", named, classes.size()); + } + for (size_t c = 0; c < classes.size(); c++){ + if (classes[c] != static_cast(c)){ + return std::format("fault_classes() lists {} at position {}, not in the enum's order.", static_cast(classes[c]), c); + } + } + return true; +} + +const SimFaultsTestCase SIM_FAULTS_CASES[] = { + {.input = {.name = "none named faults none", .body = test_none_named}, .expectation = {.description = "3 chances, none faulted"}}, + {.input = {.name = "the named chances are faulted, from 1", .body = test_named_from_one}, .expectation = {.description = "1 and 3 of 4 faulted"}}, + {.input = {.name = "a chance never reached is not faulted", .body = test_never_reached}, .expectation = {.description = "2 of 3 faulted, 9 never reached"}}, + {.input = {.name = "no chances, nothing counted", .body = test_no_chances}, .expectation = {.description = "0 chances, none faulted"}}, + {.input = {.name = "each class has its own name", .body = test_class_names}, .expectation = {.description = "no two classes share a name"}}, + {.input = {.name = "fault_classes() lists every class in order", .body = test_classes_match_enum}, .expectation = {.description = "the list is the enum's values, in order"}}, +}; + +} // namespace + + +void add_tests_SimFaults(UnitTestDatabase& database){ + for (const SimFaultsTestCase& scenario : SIM_FAULTS_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h new file mode 100644 index 0000000000..000b660a23 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h @@ -0,0 +1,23 @@ +/* Sim Faults Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_SimFaults_Tests_H +#define PokemonAutomation_Pokemon_SimFaults_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers the sim fault counter tests. +void add_tests_SimFaults(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp new file mode 100644 index 0000000000..0ab221c99e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp @@ -0,0 +1,132 @@ +/* Sim Golden + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Filesystem/FileIO.h" +#include "Pokemon_SimGolden.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +// Line `begin` of `text` up to its "\n", without a "\r" at its end. +std::string_view line_at(std::string_view text, size_t begin){ + if (begin >= text.size()){ + return {}; + } + const size_t end = std::min(text.find('\n', begin), text.size()); + std::string_view line = text.substr(begin, end - begin); + if (line.ends_with('\r')){ + line.remove_suffix(1); + } + return line; +} + +// Where the line after the one at `begin` starts; past the end if none. +size_t next_line(std::string_view text, size_t begin){ + if (begin >= text.size()){ + return text.size() + 1; + } + const size_t end = text.find('\n', begin); + return end == std::string_view::npos ? text.size() + 1 : end + 1; +} + +} // namespace + + +std::string with_crlf(std::string_view text){ + std::string out; + out.reserve(text.size() + text.size() / 16); + for (char ch : text){ + if (ch == '\r'){ + continue; + } + if (ch == '\n'){ + out += '\r'; + } + out += ch; + } + return out; +} + +bool sim_golden_update_requested(){ + // code-health: allow char_pointer -- std::getenv returns a const char pointer + const char* value = std::getenv(std::string(SIM_GOLDEN_UPDATE_VARIABLE).c_str()); + return value != nullptr && value[0] != '\0' && std::string_view(value) != "0"; +} + +std::string sim_golden_path(std::string_view source_file, std::string_view name){ + const size_t slash = source_file.find_last_of("/\\"); + std::string out = slash == std::string_view::npos ? std::string() : std::string(source_file.substr(0, slash + 1)); + out += name; + return out; +} + +std::string sim_golden_text(std::string_view about, const std::vector& lines){ + std::string out = "# "; + out += about; + out += "\n"; + for (const std::string& line : lines){ + out += line; + out += "\n"; + } + return out; +} + +std::optional first_golden_difference(std::string_view golden, std::string_view actual){ + size_t a = 0; + size_t b = 0; + for (size_t line = 1; a < golden.size() || b < actual.size(); line++){ + const std::string_view golden_line = line_at(golden, a); + const std::string_view actual_line = line_at(actual, b); + const bool golden_ended = a >= golden.size(); + const bool actual_ended = b >= actual.size(); + if (golden_line != actual_line || golden_ended != actual_ended){ + return std::format( + "line {}:\n--- golden: {}\n+++ actual: {}", line, + golden_ended ? "(end of file)" : golden_line, + actual_ended ? "(end of file)" : actual_line + ); + } + a = next_line(golden, a); + b = next_line(actual, b); + } + return std::nullopt; +} + +UnitTestResult check_sim_golden(Logger& logger, const std::string& path, const std::string& text){ + if (sim_golden_update_requested()){ + const std::string crlf = with_crlf(text); + 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 std::format("No golden at {}: run with {}=1 to write it.", path, SIM_GOLDEN_UPDATE_VARIABLE); + } + const std::optional difference = first_golden_difference(golden, text); + if (difference.has_value()){ + return std::format( + "{} differs from the simulation at {}\nRun with {}=1 to rewrite it if the change is meant.", + path, *difference, SIM_GOLDEN_UPDATE_VARIABLE + ); + } + return true; +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h new file mode 100644 index 0000000000..23486fe72e --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h @@ -0,0 +1,63 @@ +/* Sim Golden + * + * From: https://github.com/PokemonAutomation/ + * + * Golden files for the games' overworld simulations: what a simulation + * observably does (the legs it walks, where steps end, the events it + * shows, how injected faults turn out), written as text a line per fact + * and checked in beside the test that writes it. A refactor of a + * simulation that should change nothing must leave its golden as it is; + * a change that should, shows as the golden's diff in review. + * + * A golden test builds its text and hands it to check_sim_golden(). With + * SIM_GOLDEN_UPDATE_VARIABLE set to anything but "" or "0", the golden is + * rewritten instead, with CRLF line endings as the source tree keeps. + * + */ + +#ifndef PokemonAutomation_Pokemon_SimGolden_H +#define PokemonAutomation_Pokemon_SimGolden_H + +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Set it to rewrite the golden files instead of checking them. +inline constexpr std::string_view SIM_GOLDEN_UPDATE_VARIABLE = "PA_UPDATE_SIM_GOLDENS"; + +// Whether SIM_GOLDEN_UPDATE_VARIABLE asks for the goldens to be rewritten. +bool sim_golden_update_requested(); + +// The file `name` in the directory of `source_file`, a test's __FILE__. +std::string sim_golden_path(std::string_view source_file, std::string_view name); + +// The golden text: `about` as a "# " comment line, then `lines`, each +// ended by "\n". +std::string sim_golden_text(std::string_view about, const std::vector& lines); + +// `text` with every "\n" made "\r\n" and no "\r" of its own: the line +// endings the goldens are written with. +std::string with_crlf(std::string_view text); + +// The first line where `golden` and `actual` differ, carriage returns +// ignored: "line N:\n--- golden: ...\n+++ actual: ...". None if they are +// the same. +std::optional first_golden_difference(std::string_view golden, std::string_view actual); + +// Checks `text` against the golden file at `path`, or rewrites the file +// with it when SIM_GOLDEN_UPDATE_VARIABLE is set. Fails with the first +// difference, or with how to write a golden that is missing. +UnitTestResult check_sim_golden(Logger& logger, const std::string& path, const std::string& text); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp new file mode 100644 index 0000000000..552dcd42cb --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp @@ -0,0 +1,151 @@ +/* Sim Golden Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The golden file plumbing on its own: paths beside a test, the text, and + * the first difference a check reports. + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon_SimGolden.h" +#include "Pokemon_SimGolden_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +namespace{ + +struct SimGoldenTestCase{ + struct Input{ + std::string name; + UnitTestResult (*body)(Logger& logger); + }; + + struct Expectation{ + std::string_view description; + }; + + Input input; + Expectation expectation; +}; + +class Test_SimGolden : public UnitTest{ +public: + explicit Test_SimGolden(SimGoldenTestCase scenario) + : UnitTest("Pokemon::Navigation - Sim golden: " + scenario.input.name) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + return m_scenario.input.body(logger); + } + +private: + SimGoldenTestCase m_scenario; +}; + +UnitTestResult expect_equal(std::string_view what, std::string_view actual, std::string_view expected){ + if (actual == expected){ + return true; + } + return std::string(what) + ": expected \"" + std::string(expected) + "\", got \"" + std::string(actual) + "\"."; +} + +// The difference as text for expect_equal(): "(none)" when the texts match. +std::string difference_of(std::string_view golden, std::string_view actual){ + return first_golden_difference(golden, actual).value_or("(none)"); +} + +UnitTestResult test_path_beside_source(Logger&){ + UnitTestResult result = expect_equal("posix", sim_golden_path("/a/b/Test.cpp", "x.golden.txt"), "/a/b/x.golden.txt"); + if (result.result != UnitTestResult::PASSED){ + return result; + } + result = expect_equal("windows", sim_golden_path("C:\\a\\Test.cpp", "x.txt"), "C:\\a\\x.txt"); + if (result.result != UnitTestResult::PASSED){ + return result; + } + return expect_equal("no directory", sim_golden_path("Test.cpp", "x.txt"), "x.txt"); +} + +UnitTestResult test_text(Logger&){ + return expect_equal("text", sim_golden_text("about", {"a", "b"}), "# about\na\nb\n"); +} + +UnitTestResult test_same_text_ignoring_crlf(Logger&){ + return expect_equal("difference", difference_of("# x\r\na\r\nb\r\n", "# x\na\nb\n"), "(none)"); +} + +UnitTestResult test_first_differing_line(Logger&){ + return expect_equal( + "difference", difference_of("# x\r\na\r\nb\r\n", "# x\na\nc\n"), + "line 3:\n--- golden: b\n+++ actual: c" + ); +} + +UnitTestResult test_extra_line(Logger&){ + UnitTestResult result = expect_equal( + "longer actual", difference_of("a\n", "a\nb\n"), + "line 2:\n--- golden: (end of file)\n+++ actual: b" + ); + if (result.result != UnitTestResult::PASSED){ + return result; + } + return expect_equal( + "shorter actual", difference_of("a\nb\n", "a\n"), + "line 2:\n--- golden: b\n+++ actual: (end of file)" + ); +} + +UnitTestResult test_with_crlf(Logger&){ + UnitTestResult result = expect_equal("bare LF", with_crlf("a\nb\n"), "a\r\nb\r\n"); + if (result.result != UnitTestResult::PASSED){ + return result; + } + result = expect_equal("CRLF", with_crlf("a\r\nb\r\n"), "a\r\nb\r\n"); + if (result.result != UnitTestResult::PASSED){ + return result; + } + return expect_equal("mixed and a stray CR", with_crlf("a\r\nb\rc\n"), "a\r\nbc\r\n"); +} + +UnitTestResult test_missing_golden_fails(Logger& logger){ + if (sim_golden_update_requested()){ + return UnitTestResult(UnitTestResult::SKIPPED, "the goldens are being rewritten"); + } + const UnitTestResult result = check_sim_golden(logger, sim_golden_path(__FILE__, "no_such.golden.txt"), "x\n"); + if (result.result == UnitTestResult::PASSED){ + return "Expected a missing golden to fail the check."; + } + return true; +} + +const SimGoldenTestCase SIM_GOLDEN_CASES[] = { + {.input = {.name = "the golden's path is beside the test's source", .body = test_path_beside_source}, .expectation = {}}, + {.input = {.name = "the text is a comment line, then a line each", .body = test_text}, .expectation = {}}, + {.input = {.name = "CRLF and LF text compare the same", .body = test_same_text_ignoring_crlf}, .expectation = {}}, + {.input = {.name = "the first differing line is reported", .body = test_first_differing_line}, .expectation = {}}, + {.input = {.name = "a line more or less is reported", .body = test_extra_line}, .expectation = {}}, + {.input = {.name = "goldens are written with exactly one CRLF a line", .body = test_with_crlf}, .expectation = {}}, + {.input = {.name = "a missing golden fails", .body = test_missing_golden_fails}, .expectation = {}}, +}; + +} // namespace + + +void add_tests_SimGolden(UnitTestDatabase& database){ + for (const SimGoldenTestCase& scenario : SIM_GOLDEN_CASES){ + database.add(scenario); + } +} + + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.h b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.h new file mode 100644 index 0000000000..3119fb8b6a --- /dev/null +++ b/SerialPrograms/Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.h @@ -0,0 +1,23 @@ +/* Sim Golden Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_SimGolden_Tests_H +#define PokemonAutomation_Pokemon_SimGolden_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers the sim golden file tests. +void add_tests_SimGolden(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp index 4cd40b9e7e..a0f621aafa 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StoryRangeOptions_Tests.cpp @@ -47,25 +47,25 @@ const StringSelectDatabase& main_story_database(){ return database; } -// The start and end set by slug, as saved settings load them; empty -// leaves the default. -struct StoryRangeInput{ - std::string name; - std::string start_slug; - std::string end_slug; -}; - -// The indexes in the dropdown, and whether the range is valid. -struct StoryRangeExpectation{ - size_t start; - size_t end; - bool valid; -}; - // A range chosen in the main story's dropdowns and what the group reads from it. struct StoryRangeCase{ - StoryRangeInput input; - StoryRangeExpectation expectation; + // The start and end set by slug, as saved settings load them; empty + // leaves the default. + struct Input{ + std::string name; + std::string start_slug; + std::string end_slug; + }; + + // The indexes in the dropdown, and whether the range is valid. + struct Expectation{ + size_t start; + size_t end; + bool valid; + }; + + Input input; + Expectation expectation; }; class Test_StoryRange : public UnitTest{ @@ -83,7 +83,7 @@ class Test_StoryRange : public UnitTest{ if (!m_case.input.end_slug.empty()){ range.END_CHECKPOINT.set_by_slug(m_case.input.end_slug); } - const StoryRangeExpectation& expected = m_case.expectation; + const StoryRangeCase::Expectation& expected = m_case.expectation; if (range.start_index() != expected.start || range.end_index() != expected.end){ return std::format( "Expected indexes {} to {}, got {} to {}", diff --git a/SerialPrograms/Source/Tests/CommandLineTests.cpp b/SerialPrograms/Source/Tests/CommandLineTests.cpp index bed7f8997e..90a9830510 100644 --- a/SerialPrograms/Source/Tests/CommandLineTests.cpp +++ b/SerialPrograms/Source/Tests/CommandLineTests.cpp @@ -18,7 +18,7 @@ using std::endl; namespace PokemonAutomation{ -int run_command_line_tests(bool augment_color_distortions){ +int run_command_line_tests(bool augment_color_distortions, const std::string& test_substring){ install_crash_backtrace_handlers(); // Keep stdout line-buffered: when piped, stdio defaults to full // buffering, and the last few KB of test output - including the lines @@ -26,9 +26,13 @@ int run_command_line_tests(bool augment_color_distortions){ // explicit buffer size is required: with 0, MSVC's ucrt can end up with // a zero-size buffer, which corrupts the next stdout write. setvbuf(stdout, nullptr, _IOLBF, 8192); - cout << "Running parallel unit tests..." << endl; + if (test_substring.empty()){ + cout << "Running parallel unit tests..." << endl; + }else{ + cout << "Running parallel unit tests matching substring \"" << test_substring << "\"..." << endl; + } ComputerPrograms::CommandLineUnitTestRunner runner(global_logger_command_line()); - if (runner.run(augment_color_distortions)){ + if (runner.run(augment_color_distortions, test_substring)){ return 1; } cout << "Running parallel unit tests... Done!" << endl; diff --git a/SerialPrograms/Source/Tests/CommandLineTests.h b/SerialPrograms/Source/Tests/CommandLineTests.h index 010de0c81f..bea6858b51 100644 --- a/SerialPrograms/Source/Tests/CommandLineTests.h +++ b/SerialPrograms/Source/Tests/CommandLineTests.h @@ -32,6 +32,11 @@ * loaded, no test runs and the program returns 1. See SerialPrograms/Source/Tests/ImageUnitTest.h * and Common/Cpp/TestRunners/TestImageDistortionManager.h. * + * Substring filter: + * Pass "--test-substring " to only run the tests whose name contains (case + * sensitive, the same matching as the GUI's "Run All Tests Containing This Substring" mode). + * Without it, all the tests are run. An empty value runs all the tests too. + * * The same tests can also be run from the GUI with the "Unit Test Runner" program, which can * run a single test, the tests matching a substring, or all tests. */ @@ -41,6 +46,9 @@ #define PokemonAutomation_Tests_CommandLineTests_H +#include + + namespace PokemonAutomation{ @@ -48,8 +56,10 @@ namespace PokemonAutomation{ // This function is only called when GlobalSettings::COMMAND_LINE_TEST_MODE is true. // `augment_color_distortions` is set by the "--augment-color-distortions" argument: also run image tests // with color distortion augmentation, using the distortion data from the test repo. +// `test_substring` is set by the "--test-substring " argument: only run the tests whose name +// contains that substring. An empty string runs all the tests. // Return 0 if all tests are passed, and 1 if any test failed or the distortion data can't be loaded. -int run_command_line_tests(bool augment_color_distortions); +int run_command_line_tests(bool augment_color_distortions, const std::string& test_substring); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGateMaps_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGateMaps_Tests.cpp new file mode 100644 index 0000000000..72bae96f3a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGateMaps_Tests.cpp @@ -0,0 +1,535 @@ +/* Overworld Gate Maps Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The real maps, pinned PokemonSimulation resources: SilphCo_5F (card-key + * doors) and PokemonMansion_1F and _3F (statue switch, barriers, holes). + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/Navigation/Pokemon_GatedPlanner.h" +#include "PokemonFRLG_OverworldGateMaps_Tests.h" +#include "PokemonFRLG_OverworldMaps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using namespace Pokemon; + +namespace{ + + +// Silph 5F, Mansion 1F and 3F, in that order. +const std::vector& maps(){ + static const std::vector loaded{ + load_map("SilphCo_5F"), + load_map("PokemonMansion_1F"), + load_map("PokemonMansion_3F"), + }; + return loaded; +} +constexpr size_t SILPH = 0; +constexpr size_t MANSION_1F = 1; +constexpr size_t MANSION_3F = 2; + +const ConnectedMaps& world(){ + static const ConnectedMaps connected(maps()); + return connected; +} + + +// Walks the maps with the gates as the state says; a step onto a step-on +// warp takes it. Walk-into warps are not modeled: they are not the topic. +class GateGame{ +public: + using State = MapPlace; + using StateHash = std::hash; + + std::optional> press(const State& state, Direction direction, const GateState& gates) const{ + const MapData& map = world().map(state.map); + const TilePos next = state.tile.next(direction); + if (!map.tiles.contains(next) || !walkable(resolved_tile(map, next, gates))){ + return std::nullopt; + } + Step step; + step.next = {state.map, next}; + step.facing = direction; + for (const MapWarp& warp : map.warps){ + if (warp.enter != WarpEntry::STEP_ON || warp.x != next.x || warp.y != next.y){ + continue; + } + const std::optional arrival = warp.to ? world().warp_arrival(warp) : std::nullopt; + if (!arrival){ + return std::nullopt; + } + step.next = *arrival; + step.warped = true; + step.ends_leg = true; + } + return step; + } + bool held_at(const State& state, Direction direction, const GateState& gates) const{ + const MapData& map = world().map(state.map); + const TilePos next = state.tile.next(direction); + return !map.tiles.contains(next) || !walkable(resolved_tile(map, next, gates)); + } + MapPlace place_of(const State& state) const{ + return state; + } + +private: + static bool walkable(TileKind tile){ + return tile == TileKind::OPEN || tile == TileKind::TALL_GRASS || tile == TileKind::FALL_HOLE; + } +}; + +using GatedLegs = std::vector>>; + +std::optional plan( + const MapPlace& from, const MapPlace& to, const GateState& gates, bool card_key_held +){ + GateRules rules; + rules.card_key_held = card_key_held; + return plan_gated_legs( + GateGame(), world(), rules, GatedStart{from, gates}, + GatedGoal{std::function([to](const MapPlace& place){ return place == to; })} + ); +} + +int count_actions(const GatedLegs& legs, int action){ + int count = 0; + for (const auto& leg : legs){ + if (leg.kind == LegKind::ACTION && leg.action == action){ + count++; + } + } + return count; +} + + +// Reader + +UnitTestResult test_reads_card_key_doors(){ + const MapData& silph = maps()[SILPH]; + if (silph.gates.size() != 3 || !silph.switches.empty()){ + return std::format("Expected 3 gates and no switches, got {} and {}.", silph.gates.size(), silph.switches.size()); + } + const auto found = silph.gates.find("door_1"); + if (found == silph.gates.end()){ + return "No door_1."; + } + const MapGate& door = found->second; + if (door.kind != GateKind::CARD_KEY || door.flag != "FLAG_SILPH_5F_DOOR_1" || door.open_at_new_game || + door.open_tile != TileKind::OPEN || door.tiles.size() != 4 + ){ + return "door_1 is not a closed card-key door of 4 tiles opening to floor with its flag."; + } + if (silph.tiles.at(TilePos{7, 9}) != TileKind::GATE){ + return "Tile (7, 9) is not a gate."; + } + return true; +} + +UnitTestResult test_reads_switches(){ + const MapData& first = maps()[MANSION_1F]; + if (first.gates.size() != 4 || first.switches.size() != 1){ + return std::format("Expected 4 gates and 1 switch, got {} and {}.", first.gates.size(), first.switches.size()); + } + const MapGate& open_first = first.gates.at("barrier_2"); + if (open_first.kind != GateKind::SWITCH || open_first.switch_id != "mansion" || open_first.open_when_on || !open_first.open_at_new_game){ + return "1F barrier_2 should open when the switch is off."; + } + if (!first.gates.at("barrier_1").open_when_on){ + return "1F barrier_1 should open when the switch is on."; + } + const MapSwitch& pressing = first.switches.at("mansion"); + if (!pressing.toggle || pressing.floors.size() != 4 || pressing.flag != "FLAG_POKEMON_MANSION_SWITCH_STATE"){ + return "The switch is a toggle on 4 floors with its flag."; + } + if (pressing.statues.size() != 1 || pressing.statues[0].tile != TilePos{5, 5} || + pressing.statues[0].face_from != TilePos{5, 6} || pressing.statues[0].facing != Direction::NORTH + ){ + return "1F statue should be (5, 5), pressed from (5, 6) facing north."; + } + return true; +} + +UnitTestResult test_reads_one_way_warps(){ + int drops = 0; + for (const MapWarp& warp : maps()[MANSION_3F].warps){ + drops += warp.one_way ? 1 : 0; + } + if (drops != 5){ + return std::format("Expected 5 one-way warps on 3F, got {}.", drops); + } + for (const MapWarp& warp : maps()[MANSION_1F].warps){ + if (warp.one_way){ + return "A 1F warp is one-way."; + } + } + return true; +} + +// A 3x3 map with `gates` and `switches` (JSON object text) on tiles "G..". +std::string parse_error(const std::string& rows, const std::string& gates, const std::string& switches){ + const std::string text = std::format(R"({{ + "format": "pokesim-runtime-map/2", "name": "T", + "source": {{"decomp_file": "x", "revision": "y", "date": "z"}}, + "tiles": [{}], "points": {{}}, "warps": [], "connections": [], + "gates": {}, "switches": {} + }})", rows, gates, switches); + try{ + Pokemon::parse_map(parse_json(text), "T.json"); + }catch (ParseException& e){ + return e.message(); + } + return ""; +} + +UnitTestResult test_gate_errors(){ + const std::string rows = R"("G..", "...", "...")"; + const std::string door = R"({"d": {"tiles": [[0, 0]], "open_glyph": ".", "new_game": "closed", "opens_by": "card_key_face_a", "flag": "F"}})"; + if (!parse_error(rows, door, "{}").empty()){ + return "A valid gate failed to parse."; + } + if (parse_error(rows, "{}", "{}").empty()){ + return "A G tile in no gate was accepted."; + } + if (parse_error(R"("...", "...", "...")", door, "{}").empty()){ + return "A gate on a tile that is not G was accepted."; + } + const std::string unknown_switch = R"({"d": {"tiles": [[0, 0]], "open_glyph": ".", "new_game": "closed", "switch": "nope", "open_when": "on"}})"; + if (parse_error(rows, unknown_switch, "{}").empty()){ + return "A gate on an unlisted switch was accepted."; + } + const std::string far_statue = R"({"s": {"flag": "F", "toggle": true, "floors": ["T"], "statues": [{"coord": [9, 9], "face_from": [1, 1], "facing": "north"}]}})"; + if (parse_error(rows, door, far_statue).empty()){ + return "A statue outside the map was accepted."; + } + return true; +} + + +// Victory Road: each floor's boulder-fed floor switch opens its barrier, a +// top and a bottom tile. The boulder is not modelled: the switch has no +// statue to press, only its flag, which the game sets for good. +UnitTestResult test_victory_road_barriers(){ + struct Floor{ + std::string_view name; + size_t gates; + size_t switches; + std::string_view switch_id; + std::string_view barrier; + std::string_view flag; + TilePos top; + }; + const Floor floors[] = { + {"VictoryRoad_1F", 2, 1, "floor_switch_1", "barrier_1_top", "VAR_MAP_SCENE_VICTORY_ROAD_1F", {12, 14}}, + {"VictoryRoad_2F", 4, 2, "floor_switch_2", "barrier_2_top", "VAR_MAP_SCENE_VICTORY_ROAD_2F_BOULDER2", {33, 16}}, + {"VictoryRoad_3F", 2, 1, "floor_switch_1", "barrier_1_top", "VAR_MAP_SCENE_VICTORY_ROAD_3F", {12, 12}}, + }; + for (const Floor& floor : floors){ + const MapData map = load_map(std::string(floor.name)); + if (map.gates.size() != floor.gates || map.switches.size() != floor.switches){ + return std::format("{}: expected {} gates and {} switches, got {} and {}.", + floor.name, floor.gates, floor.switches, map.gates.size(), map.switches.size()); + } + const auto found = map.switches.find(std::string(floor.switch_id)); + if (found == map.switches.end() || found->second.toggle || found->second.flag != floor.flag || !found->second.statues.empty()){ + return std::format("{}: {} should be a one-way flag switch with no statue.", floor.name, floor.switch_id); + } + const MapGate& top = map.gates.at(std::string(floor.barrier)); + if (top.kind != GateKind::SWITCH || top.switch_id != floor.switch_id || !top.open_when_on || top.open_at_new_game){ + return std::format("{}: the barrier should be closed at new game and open with {}.", floor.name, floor.switch_id); + } + GateState off; + GateState on; + on.switches_on.insert(std::string(floor.switch_id)); + if (resolved_tile(map, floor.top, off) != TileKind::WALL || resolved_tile(map, floor.top, on) == TileKind::WALL){ + return std::format("{}: the barrier at ({}, {}) should be a wall until {} is on.", floor.name, floor.top.x, floor.top.y, floor.switch_id); + } + } + return true; +} + +// State and tiles + +UnitTestResult test_tiles_follow_state(){ + const MapData& silph = maps()[SILPH]; + GateState state; + if (resolved_tile(silph, TilePos{7, 9}, state) != TileKind::WALL){ + return "A closed door is not a wall."; + } + state.opened.insert(gate_key("SilphCo_5F", "door_1")); + if (resolved_tile(silph, TilePos{7, 9}, state) != TileKind::OPEN || resolved_tile(silph, TilePos{7, 18}, state) != TileKind::WALL){ + return "Only door_1 should be open."; + } + if (resolve_tiles(silph, state).at(TilePos{8, 10}) != TileKind::OPEN){ + return "resolve_tiles disagrees."; + } + + // The Mansion's gates follow the one switch on every floor. + const MapData& first = maps()[MANSION_1F]; + const MapData& third = maps()[MANSION_3F]; + GateState off; + GateState on; + on.switches_on.insert("mansion"); + if (resolved_tile(first, TilePos{22, 10}, off) != TileKind::WALL || resolved_tile(first, TilePos{22, 10}, on) != TileKind::TALL_GRASS){ + return "1F barrier_1 should open with the switch on."; + } + if (resolved_tile(third, TilePos{21, 6}, off) != TileKind::TALL_GRASS || resolved_tile(third, TilePos{21, 6}, on) != TileKind::WALL){ + return "3F barrier_1 should close with the switch on."; + } + return true; +} + +UnitTestResult test_gate_change(){ + GateState state; + GateChange change; + change.opened.insert("SilphCo_5F/door_1"); + change.switches["mansion"] = true; + apply_gate_change(state, change); + if (!state.opened.contains("SilphCo_5F/door_1") || !state.switch_on("mansion")){ + return "The change was not applied."; + } + GateChange off; + off.switches["mansion"] = false; + GateState after = state; + apply_gate_change(after, off); + if (after.switch_on("mansion") || !after.opened.contains("SilphCo_5F/door_1")){ + return "Turning the switch off changed more, or nothing."; + } + GateState rebuilt; + apply_gate_change(rebuilt, gate_change_between(GateState(), state)); + if (!(rebuilt == state)){ + return "gate_change_between from nothing does not rebuild the state."; + } + apply_gate_change(rebuilt, gate_change_between(state, after)); + if (!(rebuilt == after)){ + return "gate_change_between does not carry state to state."; + } + const GateState copy = after; + if (std::hash()(copy) != std::hash()(rebuilt)){ + return "Equal states hash differently."; + } + return true; +} + + +// Planner + +UnitTestResult test_silph_door_needs_key(){ + const MapPlace from{SILPH, {10, 9}}; + const MapPlace to{SILPH, {5, 9}}; + if (plan(from, to, GateState(), false)){ + return "Planned into the room without the Card Key."; + } + const auto legs = plan(from, to, GateState(), true); + if (!legs){ + return "No route with the Card Key."; + } + if (count_actions(*legs, ACTION_OPEN_GATE) != 1){ + return std::format("Expected one open-gate leg, got {}.", count_actions(*legs, ACTION_OPEN_GATE)); + } + GateChange expected; + expected.opened.insert("SilphCo_5F/door_1"); + for (const auto& leg : *legs){ + if (leg.kind == LegKind::ACTION){ + if (!(gate_change_of(leg) == expected)){ + return "The open-gate leg did not open door_1 alone."; + } + if (leg.direction != Direction::WEST || !(leg.start.inner == MapPlace{SILPH, {9, 9}})){ + return "Expected to open it facing west from (9, 9)."; + } + } + } + if (!gates_after(GateState(), *legs).opened.contains("SilphCo_5F/door_1")){ + return "The state after the plan does not have door_1 open."; + } + return true; +} + +UnitTestResult test_silph_open_door_needs_no_key(){ + GateState opened; + opened.opened.insert(gate_key("SilphCo_5F", "door_1")); + const auto legs = plan({SILPH, {10, 9}}, {SILPH, {5, 9}}, opened, false); + if (!legs){ + return "No route through an open door."; + } + if (count_actions(*legs, ACTION_OPEN_GATE) != 0){ + return "Opened a door that was open."; + } + return true; +} + +UnitTestResult test_mansion_press_opens_barrier(){ + // (19, 13) lies behind barrier_1 and barrier_2 of 1F, which open with the switch on. + const MapPlace from{MANSION_1F, {5, 8}}; + const MapPlace to{MANSION_1F, {19, 13}}; + const auto legs = plan(from, to, GateState(), false); + if (!legs){ + return "No route."; + } + if (count_actions(*legs, ACTION_PRESS_SWITCH) != 1){ + return std::format("Expected one statue press, got {}.", count_actions(*legs, ACTION_PRESS_SWITCH)); + } + if (!gates_after(GateState(), *legs).switch_on("mansion")){ + return "The switch is not on after the plan."; + } + for (const auto& leg : *legs){ + if (leg.kind == LegKind::ACTION && (leg.direction != Direction::NORTH || !(leg.start.inner == MapPlace{MANSION_1F, {5, 6}}))){ + return "Expected to press the statue from (5, 6) facing north."; + } + } + return true; +} + +UnitTestResult test_mansion_press_again(){ + // Switch already on; (25, 21) is reachable only with it off. + GateState on; + on.switches_on.insert("mansion"); + const auto legs = plan({MANSION_1F, {5, 6}}, {MANSION_1F, {25, 21}}, on, false); + if (!legs){ + return "No route."; + } + if (count_actions(*legs, ACTION_PRESS_SWITCH) != 1 || gates_after(on, *legs).switch_on("mansion")){ + return "Expected one press, ending with the switch off."; + } + return true; +} + +UnitTestResult test_mansion_no_press_needed(){ + // Reachable with the switch as it is: no press. + const auto legs = plan({MANSION_1F, {5, 6}}, {MANSION_1F, {5, 8}}, GateState(), false); + if (!legs || count_actions(*legs, ACTION_PRESS_SWITCH) != 0){ + return "Pressed a statue that was not needed."; + } + return true; +} + +UnitTestResult test_hole_one_way(){ + // The 3F hole at (18, 18) drops to 1F's (19, 22); nothing leads back up. + const auto down = plan({MANSION_3F, {18, 17}}, {MANSION_1F, {19, 22}}, GateState(), false); + if (!down){ + return "No route down the hole."; + } + bool warped = false; + for (const auto& leg : *down){ + warped = warped || leg.warps; + } + if (!warped){ + return "The route does not take the warp."; + } + if (plan({MANSION_1F, {19, 22}}, {MANSION_3F, {18, 17}}, GateState(), false)){ + return "Planned back up a hole."; + } + return true; +} + + +struct GatesTestCase{ + struct Input{ + std::string name; + UnitTestResult (*test)(); + }; + + struct Expectation{ + std::string_view description; + }; + + Input input; + Expectation expectation; +}; + +class Test_Gates : public UnitTest{ +public: + explicit Test_Gates(GatesTestCase scenario) + : UnitTest(std::format("PokemonFRLG::OverworldGateMaps - {}", scenario.input.name)) + , m_scenario(std::move(scenario)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + return m_scenario.input.test(); + } + +private: + GatesTestCase m_scenario; +}; + +const GatesTestCase GATES_CASES[] = { + { + .input = {.name = "reads card-key doors", .test = test_reads_card_key_doors}, + .expectation = {.description = "Silph 5F doors parse with tiles, flag, open glyph"}, + }, + { + .input = {.name = "reads switches and statues", .test = test_reads_switches}, + .expectation = {.description = "Mansion gates follow the switch; statue tile and press spot"}, + }, + { + .input = {.name = "reads one-way warps", .test = test_reads_one_way_warps}, + .expectation = {.description = "3F holes are one-way"}, + }, + { + .input = {.name = "gate errors", .test = test_gate_errors}, + .expectation = {.description = "bad gates fail to parse"}, + }, + { + .input = {.name = "tiles follow the state", .test = test_tiles_follow_state}, + .expectation = {.description = "closed gate is a wall, open is its glyph, Mansion follows the switch"}, + }, + { + .input = {.name = "gate change", .test = test_gate_change}, + .expectation = {.description = "apply and between agree"}, + }, + { + .input = {.name = "a card-key door needs the key", .test = test_silph_door_needs_key}, + .expectation = {.description = "open-gate leg only with the Card Key held"}, + }, + { + .input = {.name = "an open door needs no key", .test = test_silph_open_door_needs_no_key}, + .expectation = {.description = "no open-gate leg when the state has it open"}, + }, + { + .input = {.name = "a statue press opens a barrier", .test = test_mansion_press_opens_barrier}, + .expectation = {.description = "one press-switch leg; switch on afterwards"}, + }, + { + .input = {.name = "a press again closes it", .test = test_mansion_press_again}, + .expectation = {.description = "switch is part of the search state"}, + }, + { + .input = {.name = "no press when not needed", .test = test_mansion_no_press_needed}, + .expectation = {.description = "does not toggle without reason"}, + }, + { + .input = {.name = "a hole is one-way", .test = test_hole_one_way}, + .expectation = {.description = "down yes, back up no"}, + }, + { + .input = {.name = "Victory Road barriers", .test = test_victory_road_barriers}, + .expectation = {.description = "floor switches open the barriers; boulders are not modelled"}, + }, +}; + +} // namespace + + +void add_tests_OverworldGateMaps(UnitTestDatabase& database){ + for (const auto& scenario : GATES_CASES){ + database.add(scenario); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGateMaps_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGateMaps_Tests.h new file mode 100644 index 0000000000..8d5d15317b --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGateMaps_Tests.h @@ -0,0 +1,26 @@ +/* Overworld Gate Maps Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldGateMaps_Tests_H +#define PokemonAutomation_PokemonFRLG_OverworldGateMaps_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Registers the gate tests on the real Silph Co. and Mansion maps: the map reader's gates, switches and one-way +// warps, the gate state, and the gated planner. +void add_tests_OverworldGateMaps(UnitTestDatabase& database); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGatedRoute.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGatedRoute.h new file mode 100644 index 0000000000..a4401abd1e --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGatedRoute.h @@ -0,0 +1,56 @@ +/* Overworld Gated Route + * + * From: https://github.com/PokemonAutomation/ + * + * Plans a route over FRLG maps that have gates (Pokemon_GateState.h): Silph + * Co.'s card-key doors and Pokemon Mansion's statue switch. The game's + * step rules (plan_overworld_route()) are wrapped by the shared gated + * planner (Pokemon_GatedPlanner.h), so a closed gate is a wall, and a route + * may open a card-key gate (RouteAction::OPEN_GATE) when the story says the + * player holds the Card Key, or press a statue (RouteAction::PRESS_SWITCH). + * The gates after the route are gates_after_route(). + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldGatedRoute_H +#define PokemonAutomation_PokemonFRLG_OverworldGatedRoute_H + +#include +#include +#include "Pokemon/Navigation/Pokemon_GatedTypes.h" +#include "PokemonFRLG_OverworldRoute.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// plan_overworld_route() with the gates as `gates` says and `rules` allows. +// Without gates in `maps` the route is the same. +std::optional> plan_overworld_route_gated( + const std::vector& maps, + const MapPosition& start, + const RouteGoal& goal, + const Pokemon::GateState& gates, + const Pokemon::GateRules& rules, + const RouteCosts& costs = default_route_costs(), + std::optional start_facing = std::nullopt +); + +// `before` with the gates `route` opens and the switches it flips. +Pokemon::GateState gates_after_route(const Pokemon::GateState& before, const std::vector& route); + +// Whether any of `maps` has a gate (MapData::gates). +bool has_gates(const std::vector& maps); + +// `maps` with the gate tiles of each as `gates` makes them: a closed gate +// is a wall (a GATE tile), an open one its open tile. What a walk reads +// its tiles from, as the maps stay as loaded. +std::vector resolve_maps(const std::vector& maps, const Pokemon::GateState& gates); + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGates_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGates_Tests.cpp new file mode 100644 index 0000000000..0180b7b473 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGates_Tests.cpp @@ -0,0 +1,308 @@ +/* Overworld Gates Tests + * + * From: https://github.com/PokemonAutomation/ + * + * FRLG's step rules under the gated planner, and the sim walking the routes + * that open a card-key gate and press a statue. + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_OverworldGatedRoute.h" +#include "PokemonFRLG_OverworldMaps.h" +#include "PokemonFRLG_OverworldSim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +using Pokemon::GateRules; +using Pokemon::GateState; + +namespace{ + +struct GatesInput{ + std::string name; + std::function body; +}; +struct GatesExpectation{ +}; +struct GatesCase{ + GatesInput input; + GatesExpectation expectation; +}; + +class Test_OverworldGates : public UnitTest{ +public: + explicit Test_OverworldGates(GatesCase test_case) + : UnitTest("PokemonFRLG::OverworldGates - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_case.input.body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + GatesCase m_case; +}; + +// A corridor with a Silph Co. card-key door at (4, 1). +const std::vector& door_maps(){ + static const std::vector MAPS{parse_map(R"({ + "format": "pokesim-runtime-map/2", "name": "GateHall", "points": {}, "warps": [], "connections": [], "source": {"decomp_file": "", "revision": "test", "date": "2026-11-12"}, + "tiles": ["#########", "#...G...#", "#########"], + "gates": {"door_1": {"tiles": [[4, 1]], "open_glyph": ".", "new_game": "closed", "opens_by": "card_key_face_a", "flag": "FLAG_TEST"}} + })", "GateHall")}; + return MAPS; +} + +// The same corridor with a Mansion statue at (1, 0), above the start, and a +// barrier at (4, 1) that is open while the switch is on. +const std::vector& statue_maps(){ + static const std::vector MAPS{parse_map(R"({ + "format": "pokesim-runtime-map/2", "name": "GateStatue", "points": {}, "warps": [], "connections": [], "source": {"decomp_file": "", "revision": "test", "date": "2026-11-12"}, + "tiles": ["#########", "#...G...#", "#########"], + "gates": {"barrier_1": {"tiles": [[4, 1]], "open_glyph": ".", "new_game": "closed", "switch": "mansion", "open_when": "on"}}, + "switches": {"mansion": {"flag": "FLAG_TEST_SWITCH", "toggle": true, "floors": ["GateStatue"], + "statues": [{"coord": [1, 0], "face_from": [1, 1], "facing": "north"}]}} + })", "GateStatue")}; + return MAPS; +} + +const MapPosition HALL_START{"GateHall", {1, 1}}; +const MapPosition HALL_GOAL{"GateHall", {6, 1}}; +const MapPosition STATUE_START{"GateStatue", {1, 1}}; +const MapPosition STATUE_GOAL{"GateStatue", {6, 1}}; + +GateRules with_card_key(bool held){ + GateRules rules; + rules.card_key_held = held; + return rules; +} + +int count_steps(const std::vector& route, RouteAction action){ + return (int)std::count_if(route.begin(), route.end(), [&](const RouteStep& step){ return step.action == action; }); +} + +std::string describe(const std::vector& route){ + std::string text; + for (const RouteStep& step : route){ + text += "\n " + to_string(step); + } + return text; +} + + +// The game's step rules read a gate tile a map has not resolved as a wall. +UnitTestResult test_plain_route_stops_at_gate(){ + if (plan_overworld_route(door_maps(), HALL_START, RouteGoal{HALL_GOAL, std::nullopt})){ + return "The plain planner walked through a closed gate."; + } + return true; +} + +UnitTestResult test_route_opens_gate(){ + const auto route = plan_overworld_route_gated( + door_maps(), HALL_START, RouteGoal{HALL_GOAL, std::nullopt}, GateState(), with_card_key(true) + ); + if (!route){ + return "No route to the far side of the door with the Card Key."; + } + if (count_steps(*route, RouteAction::OPEN_GATE) != 1 || !(route->back().end == HALL_GOAL)){ + return "Expected one open-gate step and the goal reached:" + describe(*route); + } + const auto opens = std::find_if(route->begin(), route->end(), [](const RouteStep& step){ return step.action == RouteAction::OPEN_GATE; }); + if (opens->direction != Direction::EAST || !opens->gate_change.opened.contains("GateHall/door_1")){ + return "The open-gate step does not face east and open GateHall/door_1:" + describe(*route); + } + if (!gates_after_route(GateState(), *route).opened.contains("GateHall/door_1")){ + return "gates_after_route() does not have the door open."; + } + return true; +} + +UnitTestResult test_route_needs_card_key(){ + if (plan_overworld_route_gated(door_maps(), HALL_START, RouteGoal{HALL_GOAL, std::nullopt}, GateState(), with_card_key(false))){ + return "A route opened a card-key door without the Card Key."; + } + return true; +} + +UnitTestResult test_route_through_open_gate(){ + GateState open; + open.opened.insert(Pokemon::gate_key("GateHall", "door_1")); + const auto route = plan_overworld_route_gated( + door_maps(), HALL_START, RouteGoal{HALL_GOAL, std::nullopt}, open, with_card_key(false) + ); + if (!route || count_steps(*route, RouteAction::OPEN_GATE) != 0){ + return "Expected a plain walk through the open door."; + } + return true; +} + +UnitTestResult test_route_presses_statue(){ + const auto route = plan_overworld_route_gated( + statue_maps(), STATUE_START, RouteGoal{STATUE_GOAL, std::nullopt}, GateState(), with_card_key(false) + ); + if (!route){ + return "No route past the barrier by pressing the statue."; + } + if (count_steps(*route, RouteAction::PRESS_SWITCH) != 1 || !(route->back().end == STATUE_GOAL)){ + return "Expected one press-switch step and the goal reached:" + describe(*route); + } + if (!gates_after_route(GateState(), *route).switch_on("mansion")){ + return "gates_after_route() does not have the switch on."; + } + return true; +} + + +// A room with a sign on its north wall, above the third column, and a +// card-key door, open, in a corner out of the way. +const std::vector& sign_maps(){ + static const std::vector MAPS{parse_map(R"({ + "format": "pokesim-runtime-map/2", "name": "GateSign", "points": {}, "warps": [], "connections": [], "source": {"decomp_file": "", "revision": "test", "date": "2026-11-12"}, + "tiles": ["##S####", "#.....#", "#.....#", "#...G.#", "#######"], + "gates": {"door_1": {"tiles": [[4, 3]], "open_glyph": ".", "new_game": "closed", "opens_by": "card_key_face_a", "flag": "FLAG_TEST"}} + })", "GateSign")}; + return MAPS; +} + +// A route over gated maps weighs a stop under a sign as one over maps +// without gates does: with the sign's overshoot dear, the walk to the tile +// under it comes from the side, not north from below. +UnitTestResult test_gated_plan_keeps_stop_risk(){ + RouteCosts costs = default_route_costs(); + costs[RouteCost::SIGN_OVERSHOOT] = 1000; + GateState open; + open.opened.insert(Pokemon::gate_key("GateSign", "door_1")); + const MapPosition start{"GateSign", {2, 3}}; + const RouteGoal goal{{"GateSign", {2, 1}}, std::nullopt}; + + const auto plain = plan_overworld_route(resolve_maps(sign_maps(), open), start, goal, costs); + const auto gated = plan_overworld_route_gated(sign_maps(), start, goal, open, GateRules(), costs); + if (!plain || !gated){ + return "No route to the tile under the sign."; + } + if (plain->back().direction == Direction::NORTH){ + return "The plain plan ends going north under the sign, so the test shows nothing:" + describe(*plain); + } + if (describe(*gated) != describe(*plain)){ + return "The gated plan differs from the plain one, which weighs the stop under the sign:" + describe(*gated) + "\n against" + describe(*plain); + } + return true; +} + +// Walks `route` in the sim from `start`, with the Card Key as `card_key`. +struct SimRun{ + std::string failure; + GateState gates; + MapPosition position; + std::vector log; +}; +SimRun walk_in_sim(const std::vector& maps, const MapPosition& start, const std::vector& route, bool card_key){ + SimScript script; + script.card_key_held = card_key; + OverworldSim sim(maps, start, Direction::EAST, script); + OverworldSimWalker walker(sim, SimWalkerRules{}); + const RoutePlanning planning{.maps = &maps, .costs = default_route_costs(), .start = start, .label = "Sim"}; + SimRun run; + run.failure = walker.run(route, planning); + run.gates = sim.state().gates; + run.position = sim.state().position; + run.log = sim.state().log; + run.log.insert(run.log.end(), walker.log().begin(), walker.log().end()); + return run; +} + +std::string joined(const std::vector& lines){ + std::string text; + for (const std::string& line : lines){ + text += "\n " + line; + } + return text; +} + +// The leg to the sim's command: face the door, A; the door is open and the +// rest of the route walks through it. +UnitTestResult test_sim_opens_gate(){ + const auto route = plan_overworld_route_gated( + door_maps(), HALL_START, RouteGoal{HALL_GOAL, std::nullopt}, GateState(), with_card_key(true) + ); + if (!route){ + return "No route."; + } + const SimRun run = walk_in_sim(door_maps(), HALL_START, *route, true); + if (!run.failure.empty() || !(run.position == HALL_GOAL) || !run.gates.opened.contains("GateHall/door_1")){ + return std::format("Expected the door opened and the goal reached, ended at {}: \"{}\"", to_string(run.position), run.failure) + + describe(*route) + joined(run.log); + } + return true; +} + +UnitTestResult test_sim_presses_statue(){ + const auto route = plan_overworld_route_gated( + statue_maps(), STATUE_START, RouteGoal{STATUE_GOAL, std::nullopt}, GateState(), with_card_key(false) + ); + if (!route){ + return "No route."; + } + const SimRun run = walk_in_sim(statue_maps(), STATUE_START, *route, false); + if (!run.failure.empty() || !(run.position == STATUE_GOAL) || !run.gates.switch_on("mansion")){ + return std::format("Expected the switch on and the goal reached, ended at {}: \"{}\"", to_string(run.position), run.failure) + + describe(*route) + joined(run.log); + } + return true; +} + +// The sim, like the game, does not open a card-key door for a player +// without the Card Key. +UnitTestResult test_sim_door_stays_shut_without_card_key(){ + const auto route = plan_overworld_route_gated( + door_maps(), HALL_START, RouteGoal{HALL_GOAL, std::nullopt}, GateState(), with_card_key(true) + ); + if (!route){ + return "No route."; + } + const SimRun run = walk_in_sim(door_maps(), HALL_START, *route, false); + if (run.failure.empty() || run.gates.opened.contains("GateHall/door_1")){ + return "The door opened for a player without the Card Key." + joined(run.log); + } + return true; +} + +const std::vector GATES_CASES{ + {.input = {.name = "the plain planner: a closed gate is a wall", .body = test_plain_route_stops_at_gate}, .expectation = {}}, + {.input = {.name = "the route opens a card-key gate with the Card Key", .body = test_route_opens_gate}, .expectation = {}}, + {.input = {.name = "no route through a card-key gate without the Card Key", .body = test_route_needs_card_key}, .expectation = {}}, + {.input = {.name = "an open gate is walked through", .body = test_route_through_open_gate}, .expectation = {}}, + {.input = {.name = "the route presses a statue for a switch's barrier", .body = test_route_presses_statue}, .expectation = {}}, + {.input = {.name = "a gated plan keeps the stop-risk costs", .body = test_gated_plan_keeps_stop_risk}, .expectation = {}}, + {.input = {.name = "sim: face the door, A, walk through", .body = test_sim_opens_gate}, .expectation = {}}, + {.input = {.name = "sim: face the statue, A, YES, walk through", .body = test_sim_presses_statue}, .expectation = {}}, + {.input = {.name = "sim: the door stays shut without the Card Key", .body = test_sim_door_stays_shut_without_card_key}, .expectation = {}}, +}; + +} // namespace + + +void add_tests_OverworldGates(UnitTestDatabase& database){ + for (const GatesCase& item : GATES_CASES){ + database.add(item); + } +} + + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.cpp index 8a623e2745..13783ea074 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.cpp @@ -30,7 +30,7 @@ uint8_t elevation_at(const MapData& map, const TilePos& point){ bool is_wall(const MapData& map, const TilePos& point){ const TileKind tile = tile_at(map, point); - return tile == TileKind::WALL || tile == TileKind::DOOR || tile == TileKind::SIGN || is_ledge(map, point); + return tile == TileKind::WALL || tile == TileKind::GATE || tile == TileKind::DOOR || tile == TileKind::SIGN || is_ledge(map, point); } bool is_ledge(const MapData& map, const TilePos& point){ switch (tile_at(map, point)){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp index 7a71b90d1c..8b1ba24d7b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.cpp @@ -35,6 +35,10 @@ Pokemon::RouteLogLeg route_log_leg(const RouteStep& step){ leg.action = Pokemon::RouteLegAction::SURF; }else if (step.action == RouteAction::FACE){ leg.action = Pokemon::RouteLegAction::FACE; + }else if (step.action == RouteAction::OPEN_GATE){ + leg.action = Pokemon::RouteLegAction::OPEN_GATE; + }else if (step.action == RouteAction::PRESS_SWITCH){ + leg.action = Pokemon::RouteLegAction::PRESS_SWITCH; }else if (step.warps){ leg.end = Pokemon::RouteLegEnd::WARP; }else if (step.to_wall){ @@ -220,7 +224,12 @@ class RouteRun{ , m_plan(with_warp_slack(route)) , m_at(planning != nullptr ? planning->start : std::nullopt) , m_facing(facing) - {} + { + if (planning != nullptr && planning->maps != nullptr){ + m_gates = planning->gates; + read_gates(); + } + } void run(){ m_lines.plan(m_at, m_plan); @@ -230,6 +239,20 @@ class RouteRun{ // Where a hold that finds the player starts isn't known. const std::optional crossing = m_next >= m_holds ? crossing_here(step) : std::nullopt; const StepOutcome outcome = m_steps.walk(step, m_facing, crossing); + if (is_gate_step(step)){ + // The player stays on their tile: nothing to find again if + // the gate didn't open, so the route fails. + if (outcome.end != StepEnd::DONE){ + m_calls.fail("walk_overworld_route(): " + to_string(step) + " did not finish."); + return; + } + m_walked.reset(); + Pokemon::apply_gate_change(m_gates, step.gate_change); + read_gates(); + m_facing = step.facing_after; + m_lines.done(step, ++m_next, m_holds); + continue; + } if (outcome.end == StepEnd::DONE){ const std::optional start = m_next >= m_unchecked ? m_at : std::nullopt; remember_walked(step); @@ -259,8 +282,25 @@ class RouteRun{ } private: + static bool is_gate_step(const RouteStep& step){ + return step.action == RouteAction::OPEN_GATE || step.action == RouteAction::PRESS_SWITCH; + } + + // The maps through the gates as they are now. The planning's own maps + // while none of them has a gate. const std::vector* maps() const{ - return m_planning != nullptr ? m_planning->maps : nullptr; + if (m_planning == nullptr || m_planning->maps == nullptr){ + return nullptr; + } + return m_resolved ? &*m_resolved : m_planning->maps; + } + + // A route run without maps (a replay's) keeps none through its gates. + void read_gates(){ + if (m_planning == nullptr || m_planning->maps == nullptr){ + return; + } + m_resolved = has_gates(*m_planning->maps) ? std::optional(resolve_maps(*m_planning->maps, m_gates)) : std::nullopt; } std::optional crossing_here(const RouteStep& step) const{ @@ -569,6 +609,8 @@ class RouteRun{ std::vector m_plan; std::optional m_at; std::optional m_facing; + Pokemon::GateState m_gates; + std::optional> m_resolved; size_t m_next = 0; size_t m_stops = 0; size_t m_holds = 0; // of the plan, holds to walls that find the player diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h index 3b0f02b2b9..b215e3f524 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h @@ -43,6 +43,7 @@ #include #include #include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonFRLG_OverworldGatedRoute.h" #include "PokemonFRLG_OverworldReanchor.h" #include "PokemonFRLG_OverworldRoute.h" #include "PokemonFRLG_OverworldTrainerCrossing.h" @@ -57,7 +58,11 @@ namespace PokemonFRLG{ // (with the event flags the caller set) and the costs; and, for the route // log (Pokemon_RouteLog.h), where it starts and what the caller calls it. struct RoutePlanning{ + // The maps as loaded: a gate tile is a wall until `gates` has it open. + // The run reads them through the gates, which each OPEN_GATE or + // PRESS_SWITCH step it walks changes. const std::vector* maps = nullptr; + Pokemon::GateState gates; RouteCosts costs = default_route_costs(); std::optional start; std::string label = "Route"; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp index 47639d1887..d2c4e322db 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.cpp @@ -22,6 +22,7 @@ #include "PokemonFRLG_OverworldBikeTaps.h" #include "PokemonFRLG_OverworldLateBattle.h" #include "PokemonFRLG_OverworldRecoveryWalk.h" +#include "PokemonFRLG_OverworldWalkGates.h" #include "PokemonFRLG_BikeSpinPresses.h" #include "PokemonFRLG_OverworldBike.h" #include "PokemonFRLG_OverworldMaps.h" @@ -197,54 +198,71 @@ bool on_dark_cave(ConsoleHandle& console){ return screen && dark_cave_screen(*screen.frame); } -// One step of a route, for a player facing `facing`. -StepWalk walk_step( +// One WALK step: turned first when it should, then its hold, and the warp it ends on. +StepWalk walk_hold_step( ConsoleHandle& console, ProControllerContext& context, const RouteStep& step, std::optional facing, const OverworldInterruptSet& interrupts, MoveSpeed speed, PlayerGender player ){ StepWalk out{std::nullopt, current_time(), false, false}; - switch (step.action){ - case RouteAction::WALK:{ - // Turning first, with a tap, starts the hold from a standstill facing - // the right way: exact over 15 tiles, where a turn lost one. - if (turns_first(step, speed, facing)){ - turn_to(console, context, step.direction, player); - } - if (const std::string note = speed_note(step, speed); !note.empty()){ - console.log(note); - } - context.wait_for_all_requests(); - out.dark = on_dark_cave(console); - const VideoSnapshot before = console.video().snapshot(); - out.hold_start = current_time(); - BlackScreenOverWatcher arrival(COLOR_RED); - Pokemon::WatchAlong fade(arrival); - const Pokemon::LegResult result = Pokemon::walk_leg( - console, context, leg_mover(step, speed), step.wild ? interrupts.wild : interrupts.other, - leg_spec(step, speed), MAX_INTERRUPTIONS_PER_LEG, warp_hold_watchers(step, fade) - ); - if (result.stopped){ - out.stopped = logged_stop_tiles(console, step, out.dark, walked_near(step, result.tiles, tile_time(step, speed))); + // Turning first, with a tap, starts the hold from a standstill facing + // the right way: exact over 15 tiles, where a turn lost one. + if (turns_first(step, speed, facing)){ + turn_to(console, context, step.direction, player); + } + if (const std::string note = speed_note(step, speed); !note.empty()){ + console.log(note); + } + context.wait_for_all_requests(); + out.dark = on_dark_cave(console); + const VideoSnapshot before = console.video().snapshot(); + out.hold_start = current_time(); + BlackScreenOverWatcher arrival(COLOR_RED); + Pokemon::WatchAlong fade(arrival); + const Pokemon::LegResult result = Pokemon::walk_leg( + console, context, leg_mover(step, speed), step.wild ? interrupts.wild : interrupts.other, + leg_spec(step, speed), MAX_INTERRUPTIONS_PER_LEG, warp_hold_watchers(step, fade) + ); + if (result.stopped){ + out.stopped = logged_stop_tiles(console, step, out.dark, walked_near(step, result.tiles, tile_time(step, speed))); + return out; + } + if (step.warps){ + wait_out_warp(console, context, step, fade, before); + static_assert(AFTER_WARP_BATTLE_WATCH >= AFTER_WARP); + if (run_from_battle_after_warp(console, context)){ + console.log("Route: a wild battle, not the warp to " + step.end.map + "; the player is on " + to_string(step) + " before the warp.", COLOR_ORANGE); + out.stopped = walked_before_warp(step); return out; } - if (step.warps){ - wait_out_warp(console, context, step, fade, before); - static_assert(AFTER_WARP_BATTLE_WATCH >= AFTER_WARP); - if (run_from_battle_after_warp(console, context)){ - console.log("Route: a wild battle, not the warp to " + step.end.map + "; the player is on " + to_string(step) + " before the warp.", COLOR_ORANGE); - out.stopped = walked_before_warp(step); - return out; - } - } - break; } + return out; +} + +// One step of a route, for a player facing `facing`. +StepWalk walk_step( + ConsoleHandle& console, ProControllerContext& context, + const RouteStep& step, std::optional facing, + const OverworldInterruptSet& interrupts, MoveSpeed speed, PlayerGender player +){ + StepWalk out{std::nullopt, current_time(), false, false}; + switch (step.action){ + case RouteAction::WALK: + return walk_hold_step(console, context, step, facing, interrupts, speed, player); case RouteAction::SURF: start_surf(console, context, step.direction, facing == step.direction); break; case RouteAction::FACE: turn_to(console, context, step.direction, player); break; + case RouteAction::OPEN_GATE: + turn_to(console, context, step.direction, player); + open_gate(console, context, step.direction, true); + break; + case RouteAction::PRESS_SWITCH: + turn_to(console, context, step.direction, player); + press_switch(console, context, step.direction, true); + break; } return out; } @@ -324,7 +342,7 @@ StepOutcome walk_and_watch( if (walked.stopped){ return StepOutcome{.end = StepEnd::STOPPED, .walked = walked.stopped, .blocked = walked.blocked}; } - if (step.action == RouteAction::FACE){ + if (step.action == RouteAction::FACE || step.action == RouteAction::OPEN_GATE || step.action == RouteAction::PRESS_SWITCH){ return StepOutcome{}; } const Milliseconds watch = step.wild ? AFTER_WILD_LEG_WATCH : AFTER_LEG_WATCH; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp index 4f809df56d..f53a33d5c5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.cpp @@ -9,9 +9,13 @@ #include #include #include +#include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/Navigation/Pokemon_GatedPlanner.h" +#include "Pokemon/Navigation/Pokemon_GateTiles.h" #include "Pokemon/Navigation/Pokemon_LegPlanner.h" +#include "PokemonFRLG_OverworldGatedRoute.h" #include "PokemonFRLG_OverworldMaps.h" #include "PokemonFRLG_OverworldObjects.h" #include "PokemonFRLG_OverworldRoute.h" @@ -347,6 +351,63 @@ class StepModel{ const RouteCosts& m_costs; }; +// The maps through each gate state a search reaches, resolved once. +class GateMaps{ +public: + explicit GateMaps(const std::vector& maps) + : m_maps(maps) + , m_gated(has_gates(maps)) + {} + + const std::vector& at(const Pokemon::GateState& gates) const{ + if (!m_gated){ + return m_maps; + } + auto iter = m_resolved.find(gates); + if (iter == m_resolved.end()){ + iter = m_resolved.emplace(gates, resolve_maps(m_maps, gates)).first; + } + return iter->second; + } + +private: + const std::vector& m_maps; + bool m_gated; + // Nodes keep their addresses, so a reference stays good while the + // search adds states. + mutable std::unordered_map> m_resolved; +}; + +// StepModel for the gated planner (Pokemon_GatedPlanner.h): the same step +// rules over the maps as the gates make them. +class GatedStepModel{ +public: + using State = Located; + using StateHash = LocatedHash; + + GatedStepModel(const GateMaps& maps, const RouteCosts& costs) + : m_maps(maps) + , m_costs(costs) + {} + + std::optional> press(const State& state, Direction direction, const Pokemon::GateState& gates) const{ + return StepModel(m_maps.at(gates), m_costs).press(state, direction); + } + bool held_at(const State& state, Direction direction, const Pokemon::GateState& gates) const{ + return StepModel(m_maps.at(gates), m_costs).held_at(state, direction); + } + int open_stop_risk(const State& state, Direction direction, const Pokemon::GateState& gates) const{ + return StepModel(m_maps.at(gates), m_costs).open_stop_risk(state, direction); + } + Pokemon::MapPlace place_of(const State& state) const{ + return Pokemon::MapPlace{(size_t)state.map, state.state.position}; + } + +private: + const GateMaps& m_maps; + const RouteCosts& m_costs; +}; + Pokemon::LegCosts to_leg_costs(const RouteCosts& costs){ Pokemon::LegCosts leg_costs; leg_costs.per_tile = route_cost(costs, RouteCost::TILE); @@ -415,14 +476,24 @@ RouteStep to_route_step(const std::vector& maps, const Pokemon::Leg& maps, const Pokemon::Leg> plan_overworld_route( } +bool has_gates(const std::vector& maps){ + return std::ranges::any_of(maps, [](const MapData& map){ + return !map.gates.empty(); + }); +} + +std::vector resolve_maps(const std::vector& maps, const Pokemon::GateState& gates){ + std::vector resolved = maps; + for (MapData& map : resolved){ + if (!map.gates.empty()){ + map.tiles = Pokemon::resolve_tiles(map, gates); + } + } + return resolved; +} + +namespace{ + +// `legs` as route steps, each read on the maps its gates make. +std::vector gated_route_steps(const GateMaps& gate_maps, const std::vector>>& legs){ + std::vector route; + for (const Pokemon::Leg>& gated : legs){ + Pokemon::Leg leg{ + .kind = gated.kind, .action = gated.action, .direction = gated.direction, .tiles = gated.tiles, + .warps = gated.warps, .to_wall = gated.to_wall, .wild = gated.wild, .facing_after = gated.facing_after, + .start = gated.start.inner, .end = gated.end.inner, + }; + RouteStep step = to_route_step(gate_maps.at(gated.start.gates), leg); + step.gate_change = Pokemon::gate_change_of(gated); + route.push_back(std::move(step)); + } + return route; +} + +} // namespace + +std::optional> plan_overworld_route_gated( + const std::vector& maps, + const MapPosition& start, + const RouteGoal& goal, + const Pokemon::GateState& gates, + const Pokemon::GateRules& rules, + const RouteCosts& costs, + std::optional start_facing +){ + if (!has_gates(maps)){ + return plan_overworld_route(maps, start, goal, costs, start_facing); + } + const int start_map = find_map(maps, start.map); + const int goal_map = find_map(maps, goal.position.map); + if (start_map < 0 || goal_map < 0){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Route between maps that aren't loaded."); + } + const GateMaps gate_maps(maps); + const std::vector& first_maps = gate_maps.at(gates); + Pokemon::GatedStart first; + first.state.map = start_map; + first.state.state.position = start.point; + first.state.state.elevation = elevation_at(first_maps[start_map], start.point); + first.state.state.surfing = is_water(first_maps[start_map], start.point); + first.gates = gates; + first.facing = start_facing; + + const Pokemon::ConnectedMaps world(maps); + const GatedStepModel model(gate_maps, costs); + const auto legs = Pokemon::plan_gated_legs( + model, world, rules, first, + Pokemon::GatedGoal{ + .at_goal = [&](const Located& player){ + return player.map == goal_map && player.state.position == goal.position.point; + }, + .facing = goal.facing, + }, + to_leg_costs(costs) + ); + if (!legs){ + return std::nullopt; + } + + std::vector route = gated_route_steps(gate_maps, *legs); + tap_from_known_tile(route); + return route; +} + +Pokemon::GateState gates_after_route(const Pokemon::GateState& before, const std::vector& route){ + Pokemon::GateState gates = before; + for (const RouteStep& step : route){ + Pokemon::apply_gate_change(gates, step.gate_change); + } + return gates; +} + + namespace{ // Further than any straight line on a map. @@ -592,11 +756,44 @@ std::vector leg_tiles( return tiles; } +namespace{ + +// `step`'s tiles from `player`, on `maps` as the gates now make them. +void follow_step(const std::vector& maps, Located& player, const RouteStep& step){ + for (int c = 0; c < step.tiles; c++){ + const std::optional transition = press(maps, player, step.direction); + if (!transition || transition->action != step.action){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Step refused at " + to_string(MapPosition{maps[player.map].name, player.state.position}) + ": " + to_string(step) + ); + } + player = transition->next; + } + const MapPosition position{maps[player.map].name, player.state.position}; + if (!(position == step.end)){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Ended at " + to_string(position) + " instead of " + to_string(step.end) + ); + } +} + +} // namespace + MapPosition follow_overworld_route( const std::vector& maps, const MapPosition& start, - const std::vector& route + const std::vector& route, + const Pokemon::GateState& start_gates ){ + Pokemon::GateState gates = start_gates; + // Only maps with gates are copied to read through them. + const bool gated = has_gates(maps); + std::vector resolved; + if (gated){ + resolved = resolve_maps(maps, gates); + } Located player; player.map = find_map(maps, start.map); if (player.map < 0){ @@ -610,23 +807,14 @@ MapPosition follow_overworld_route( if (step.action == RouteAction::FACE){ continue; } - for (int c = 0; c < step.tiles; c++){ - const std::optional transition = press(maps, player, step.direction); - if (!transition || transition->action != step.action){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Step refused at " + to_string(MapPosition{maps[player.map].name, player.state.position}) + ": " + to_string(step) - ); + if (step.action == RouteAction::OPEN_GATE || step.action == RouteAction::PRESS_SWITCH){ + Pokemon::apply_gate_change(gates, step.gate_change); + if (gated){ + resolved = resolve_maps(maps, gates); } - player = transition->next; - } - const MapPosition position{maps[player.map].name, player.state.position}; - if (!(position == step.end)){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Ended at " + to_string(position) + " instead of " + to_string(step.end) - ); + continue; } + follow_step(gated ? resolved : maps, player, step); } return MapPosition{maps[player.map].name, player.state.position}; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h index fd06a21aec..605e61f49d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h @@ -66,10 +66,13 @@ std::vector leg_tiles( // Replays `route` from `start` with the game's step rules and returns where // it ends. Throws InternalProgramError if a step can't be taken as planned. +// A route with gates (plan_overworld_route_gated()) starts with `gates`; its +// OPEN_GATE and PRESS_SWITCH steps change them. MapPosition follow_overworld_route( const std::vector& maps, const MapPosition& start, - const std::vector& route + const std::vector& route, + const Pokemon::GateState& gates = {} ); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h index 3f4d90bea7..60fc968525 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteSteps.h @@ -15,6 +15,7 @@ #include #include #include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "Pokemon/Navigation/Pokemon_GateState.h" #include "PokemonFRLG_OverworldMap.h" namespace PokemonAutomation{ @@ -38,6 +39,12 @@ enum class RouteAction{ WALK, // hold `direction` for `tiles` tiles SURF, // face `direction`, use Surf, and land on the water there FACE, // turn to `direction` without moving + // Face the closed card-key gate in `direction` and open it with A: the + // Silph Co. door's message follows. The player stays on the tile. + OPEN_GATE, + // Face the statue in `direction` and press it with A, YES to the + // switch's question (Pokemon Mansion). The player stays on the tile. + PRESS_SWITCH, }; // A single step along an overworld path. @@ -93,6 +100,9 @@ struct RouteStep{ Direction facing_after = Direction::NORTH; // Where the player is after the step. MapPosition end; + // OPEN_GATE, PRESS_SWITCH: what the step does to the gates, for the + // story to keep (gates_after_route()). + Pokemon::GateChange gate_change = {}; }; // Formats a RouteStep as a string. std::string to_string(const RouteStep& step); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteStrings.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteStrings.cpp index 8b7175b066..b26cd60248 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteStrings.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRouteStrings.cpp @@ -31,6 +31,12 @@ std::string to_string(const RouteStep& step){ case RouteAction::FACE: text = "face " + std::string(direction_name(step.direction)); break; + case RouteAction::OPEN_GATE: + text = "open gate " + std::string(direction_name(step.direction)); + break; + case RouteAction::PRESS_SWITCH: + text = "press switch " + std::string(direction_name(step.direction)); + break; } return text + " -> " + to_string(step.end); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp index 96d07b3d6f..e9bada9229 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.cpp @@ -147,6 +147,9 @@ OverworldSim::OverworldSim(std::vector maps, MapPosition start, Directi throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Sim: start on a map that isn't loaded: " + start.map); } add_coded_field(); + m_state.gates = m_script.gates; + m_state.card_key_held = m_script.card_key_held; + read_gates(); m_player = PlayerState{start.point, elevation_at(map(), start.point), false}; m_state.facing = facing; m_state.on_bike = m_script.on_bike; @@ -837,21 +840,15 @@ std::optional OverworldSimWalker::walk_step(const RouteStep& step, if (step.action == RouteAction::SURF){ return surf(step); } + if (step.action == RouteAction::OPEN_GATE || step.action == RouteAction::PRESS_SWITCH){ + return use_gate(step); + } if (turns_first(step, m_speed, facing)){ sim_turn_to(m_sim, step.direction, m_rules.confirm_turn); } const int warps_before = m_sim.state().warps; const std::vector& ints = interrupts(step); - Pokemon::LegSpec leg; - leg.direction = step.direction; - leg.tiles = step.tiles + step.warp_slack; - leg.to_wall = step.to_wall; - leg.tile_time = tile_time(step, m_speed); - leg.stop_on_interrupt = !step.to_wall; - leg.stop_if_blocked = step.to_wall && m_rules.stop_if_blocked; - if (m_rules.hold_over_connections){ - leg.stalled_steps = step.connection_steps; - } + const Pokemon::LegSpec leg = leg_spec(step); Pokemon::LegCalls calls; calls.hold_watching = [&](Milliseconds hold) -> std::optional{ const std::optional seen = hold_watching(step, hold, ints); @@ -901,7 +898,7 @@ StepOutcome OverworldSimWalker::walk_ridden(const RouteStep& step, std::optional }else if (const std::optional walked = walk_step(step, facing)){ return StepOutcome{.end = StepEnd::STOPPED, .walked = walked}; } - if (step.action == RouteAction::FACE){ + if (step.action == RouteAction::FACE || step.action == RouteAction::OPEN_GATE || step.action == RouteAction::PRESS_SWITCH){ return StepOutcome{}; } size_t late = clear_late(interrupts(step), step.wild ? m_rules.after_wild_leg_watch : AFTER_LEG_WATCH, MAX_INTERRUPTIONS_PER_LEG); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h index 2a4c86864d..20c3b3efd1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h @@ -170,6 +170,12 @@ class OverworldSim{ bool choose_lift_floor(size_t floor); bool push_poster_switch(); bool start_surf(); + // A on the gate or the statue the player faces; false, as a violation, + // if there is none or the Card Key is missing. + bool open_gate(); + bool press_switch(); + // Reads each map's gate tiles through the gates of m_state. + void read_gates(); bool fly_to_town(size_t town); // The trees cut come back, as after a warp. void regrow_cut_trees(); @@ -432,6 +438,11 @@ class OverworldSimWalker{ // Nothing: a Surf is never stopped part-way. // (PokemonFRLG_OverworldSimField.cpp) std::optional surf(const RouteStep& step); + // OPEN_GATE, PRESS_SWITCH: turned to the gate or statue, A (and YES), + // as use_field(). (PokemonFRLG_OverworldSimField.cpp) + std::optional use_gate(const RouteStep& step); + // The hold of a WALK step. (PokemonFRLG_OverworldSimField.cpp) + Pokemon::LegSpec leg_spec(const RouteStep& step) const; bool after_warp(const RouteStep& step, int warps_before, Milliseconds watched_from); bool fade_over_since(Milliseconds from) const; // after_warp() on a fade seen with no warp: fails, or with @@ -475,6 +486,8 @@ void add_tests_OverworldSim(UnitTestDatabase& database); void add_tests_OverworldWarpFade(UnitTestDatabase& database); // Register the tests of the way a warp leaves the player facing. void add_tests_OverworldStairs(UnitTestDatabase& database); +// Register the tests of gated routes, and of the sim opening gates. +void add_tests_OverworldGates(UnitTestDatabase& database); } // namespace PokemonFRLG diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp index 84384e54da..f368a4e3c1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.cpp @@ -10,10 +10,13 @@ #include #include +#include "Pokemon/Navigation/Pokemon_GateTiles.h" #include "PokemonFRLG_CodedRooms.h" #include "PokemonFRLG_FlyMap.h" +#include "PokemonFRLG_OverworldGatedRoute.h" #include "PokemonFRLG_OverworldSim.h" #include "PokemonFRLG_OverworldSimField.h" +#include "PokemonFRLG_OverworldWalk.h" #include "PokemonFRLG_BikeSpinMechanics.h" #include "PokemonFRLG_OverworldSpin.h" @@ -44,6 +47,10 @@ bool OverworldSim::use_field(SimField field, size_t floor){ return start_surf(); case SimField::FLY: return fly_to_town(floor); + case SimField::OPEN_GATE: + return open_gate(); + case SimField::PRESS_SWITCH: + return press_switch(); } return false; } @@ -137,6 +144,62 @@ bool OverworldSim::start_surf(){ return true; } +void OverworldSim::read_gates(){ + // Only the tiles: the objects the sim has changed stay as they are. + // Maps without a gate were not copied. + if (m_state.gate_maps.empty() && has_gates(m_maps)){ + m_state.gate_maps = m_maps; + } + for (size_t c = 0; c < m_state.gate_maps.size(); c++){ + if (!m_state.gate_maps[c].gates.empty()){ + m_maps[c].tiles = Pokemon::resolve_tiles(m_state.gate_maps[c], m_state.gates); + } + } +} + +bool OverworldSim::open_gate(){ + if (m_state.gate_maps.empty()){ + violation("no gates on the maps."); + return false; + } + const MapData& source = m_state.gate_maps[m_map]; + const Pokemon::MapGate* gate = Pokemon::closed_card_key_gate_faced(source, m_player.position, m_state.facing, m_state.gates); + if (gate == nullptr || !m_script.card_key_held || m_state.screen != SimScreen::OVERWORLD || m_frozen){ + violation(std::format( + "no card-key gate to open {} of {}{}.", + direction_name(m_state.facing), to_string(m_state.position), m_script.card_key_held ? "" : " (no Card Key)" + )); + return false; + } + // "Opened the door with the CARD KEY!", then the door. + advance_to(m_now + m_script.timing.message); + m_state.gates.opened.insert(Pokemon::gate_key(source.name, gate->id)); + read_gates(); + note("opened " + Pokemon::gate_key(source.name, gate->id) + "."); + return true; +} + +bool OverworldSim::press_switch(){ + const Pokemon::MapSwitch* pressed = m_state.gate_maps.empty() + ? nullptr + : Pokemon::switch_pressed(m_state.gate_maps[m_map], m_player.position, m_state.facing); + if (pressed == nullptr || m_state.screen != SimScreen::OVERWORLD || m_frozen){ + violation(std::format("no statue to press {} of {}.", direction_name(m_state.facing), to_string(m_state.position))); + return false; + } + // The prompt, YES, and the text after it. + advance_to(m_now + m_script.timing.message); + const bool now_on = pressed->toggle ? !m_state.gates.switch_on(pressed->id) : true; + if (now_on){ + m_state.gates.switches_on.insert(pressed->id); + }else{ + m_state.gates.switches_on.erase(pressed->id); + } + read_gates(); + note(std::format("switch {} is {}.", pressed->id, now_on ? "on" : "off")); + return true; +} + bool OverworldSim::fly_to_town(size_t town){ const std::vector& towns = kanto_fly_towns(); const MapPosition* landing = town < towns.size() ? &towns[town].landing : nullptr; @@ -162,6 +225,31 @@ bool OverworldSim::fly_to_town(size_t town){ return true; } +Pokemon::LegSpec OverworldSimWalker::leg_spec(const RouteStep& step) const{ + Pokemon::LegSpec leg; + leg.direction = step.direction; + leg.tiles = step.tiles + step.warp_slack; + leg.to_wall = step.to_wall; + leg.tile_time = OverworldWalkSteps::tile_time(step, m_speed); + leg.stop_on_interrupt = !step.to_wall; + leg.stop_if_blocked = step.to_wall && m_rules.stop_if_blocked; + if (m_rules.hold_over_connections){ + leg.stalled_steps = step.connection_steps; + } + return leg; +} + +std::optional OverworldSimWalker::use_gate(const RouteStep& step){ + if (m_sim.state().facing != step.direction){ + sim_turn_to(m_sim, step.direction, m_rules.confirm_turn); + } + const bool opens = step.action == RouteAction::OPEN_GATE; + if (!m_sim.use_field(opens ? SimField::OPEN_GATE : SimField::PRESS_SWITCH)){ + fail("walk_overworld_route(): " + to_string(step) + " did not open anything."); + } + return std::nullopt; +} + std::optional OverworldSimWalker::surf(const RouteStep& step){ if (m_sim.state().facing != step.direction){ sim_turn_to(m_sim, step.direction, m_rules.confirm_turn); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.h index b4993fa1e8..f2d8a29fe6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimField.h @@ -45,6 +45,12 @@ enum class SimField{ // kanto_fly_towns(), outdoors: the fade, then the player on its landing // tile facing south, still for SimTiming::fly. FLY, + // The card-key gate the player faces (a `G` tile of a map's `gates`), + // with SimScript::card_key_held: its message, and the gate is open. + OPEN_GATE, + // The statue the player faces (a map's `switches`): the prompt, YES, and + // the switch flips, with every gate that follows it on every map. + PRESS_SWITCH, }; // Register the tests of the Bicycle's taps and SELECT on a made-up map. diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h index e985f46736..7c1e063d98 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSimState.h @@ -29,6 +29,12 @@ namespace PokemonFRLG{ // What a test sets up beyond the maps. struct SimScript{ std::vector encounters; + // The player holds the Card Key: A on a card-key gate opens it + // (SimField::OPEN_GATE). Without it the door does not open, as in the game. + bool card_key_held = false; + // The gates open at the start. The sim reads each map's gate tiles + // through them (Pokemon_GateTiles.h). + Pokemon::GateState gates; // The START menu is open at the start: the D-pad moves its cursor. bool start_menu_open = false; // The hold numbered by the key (from 1) stops this many tiles short, @@ -130,6 +136,14 @@ struct SimScript{ // The player and the screen, and what went wrong that the game would show. struct SimState{ MapPosition position; + // The gates open and the switches on (SimScript::gates, then what the + // player opened and pressed). + Pokemon::GateState gates; + // The maps as loaded, with each gate closed or open as the map says, to + // plan through the gates (resolve_maps()); empty if no map has a gate. + std::vector gate_maps; + // Whether the player holds the Card Key (SimScript::card_key_held). + bool card_key_held = false; Direction facing = Direction::SOUTH; SimScreen screen = SimScreen::OVERWORLD; // Whether black shows below the map: the player stands near the bottom diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp index b47e21f6d1..3dcbaaa052 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim_Tests.cpp @@ -1038,12 +1038,12 @@ void add_tests_OverworldSim(UnitTestDatabase& database){ add_tests_OverworldLateBattle(database); add_tests_OverworldWarpFade(database); add_tests_OverworldStairs(database); + add_tests_OverworldGates(database); add_tests_OverworldSpin(database); add_tests_OverworldBike(database); } - } // namespace PokemonFRLG } // namespace NintendoSwitch } // namespace PokemonAutomation \ No newline at end of file diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp index 1c37503a94..ebf46afd7d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.cpp @@ -25,6 +25,7 @@ #include "VideoGames/PokemonFRLG/PokemonFRLG_Settings.h" #include "PokemonFRLG_PlayerFacingReader.h" #include "PokemonFRLG_OverworldWalk.h" +#include "PokemonFRLG_OverworldWalkGates.h" #include "PokemonFRLG_OverworldBike.h" #include "PokemonFRLG_BikeSpinMechanics.h" #include "PokemonFRLG_BikeSpinPresses.h" @@ -44,6 +45,14 @@ namespace{ constexpr Milliseconds WARP_TIMEOUT = 8000ms; constexpr Milliseconds SURF_PROMPT_TIMEOUT = 5000ms; constexpr Milliseconds SURF_ANIMATION = 3000ms; +// A card-key door's message, and the door opening after it. +constexpr Milliseconds GATE_MESSAGE_WAIT = 1500ms; +constexpr Milliseconds GATE_SETTLE = 1500ms; +// The Yes/No prompt of a statue, and how long B's through the text before +// and after the switch last. +constexpr Milliseconds SWITCH_PROMPT_TIMEOUT = 5000ms; +constexpr Milliseconds SWITCH_SETTLE = 2000ms; +constexpr int MAX_TEXT_BOXES = 5; // After a message closes: a trainer who saw the player speaks first, then // the battle starts, with " would like to battle!" seconds later. constexpr Milliseconds TRAINER_BATTLE_WATCH = 6000ms; @@ -761,6 +770,56 @@ void start_surf(ConsoleHandle& console, ProControllerContext& context, Direction pbf_wait(context, SURF_ANIMATION); } +namespace{ + +// B through the text boxes that are open, at most MAX_TEXT_BOXES of them. +void clear_text(ConsoleHandle& console, ProControllerContext& context){ + for (int c = 0; c < MAX_TEXT_BOXES; c++){ + context.wait_for_all_requests(); + VideoSnapshot screen = console.video().snapshot(); + if (!screen || !WhiteDialogDetector(COLOR_RED).detect(screen)){ + return; + } + pbf_press_button(context, BUTTON_B, 160ms, 1000ms); + } +} + +void face_for_a(ProControllerContext& context, Direction direction, bool facing){ + // An A pressed while the player is still turning is lost. + if (!facing){ + pbf_press_dpad(context, dpad(direction), FACE_HOLD, FACE_SETTLE); + } +} + +} // namespace + +void open_gate(ConsoleHandle& console, ProControllerContext& context, Direction direction, bool facing_gate){ + face_for_a(context, direction, facing_gate); + pbf_press_button(context, BUTTON_A, 160ms, GATE_MESSAGE_WAIT); + clear_text(console, context); + pbf_wait(context, GATE_SETTLE); + context.wait_for_all_requests(); +} + +void press_switch(ConsoleHandle& console, ProControllerContext& context, Direction direction, bool facing_statue){ + face_for_a(context, direction, facing_statue); + pbf_press_button(context, BUTTON_A, 160ms, 0ms); + SelectionDialogWatcher prompt(COLOR_RED); + context.wait_for_all_requests(); + if (wait_until(console, context, SWITCH_PROMPT_TIMEOUT, {prompt}) < 0){ + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + "walk_overworld_route(): no prompt facing the statue.", + console + ); + } + // Yes is selected. + pbf_press_button(context, BUTTON_A, 160ms, 1000ms); + clear_text(console, context); + pbf_wait(context, SWITCH_SETTLE); + context.wait_for_all_requests(); +} + } // namespace OverworldWalkSteps @@ -858,6 +917,25 @@ void walk_step_leg( check_warp_was_no_battle(console, context, step); } +// A WALK step: turned first, then its leg. +void walk_hold( + ConsoleHandle& console, ProControllerContext& context, + const RouteStep& step, std::optional facing, + const OverworldInterruptSet& interrupts, MoveSpeed speed, PlayerGender player +){ + // Turning first, with a tap, makes the hold start from a standstill + // facing the right way: holding through a turn lost a tile on the + // console, while holds from a standstill were exact over 15 tiles. + // Not on the Bicycle, where the tap is a step. + if (turns_first(step, speed, facing)){ + turn_to(console, context, step.direction, player); + } + if (const std::string note = speed_note(step, speed); !note.empty()){ + console.log(note); + } + walk_step_leg(console, context, step, interrupts, speed); +} + } // namespace @@ -878,17 +956,7 @@ void walk_overworld_route( check_overworld(console, context, step); switch (step.action){ case RouteAction::WALK: - // Turning first, with a tap, makes the hold start from a standstill - // facing the right way: holding through a turn lost a tile on the - // console, while holds from a standstill were exact over 15 tiles. - // Not on the Bicycle, where the tap is a step. - if (turns_first(step, speed, facing)){ - turn_to(console, context, step.direction, player); - } - if (const std::string note = speed_note(step, speed); !note.empty()){ - console.log(note); - } - walk_step_leg(console, context, step, interrupts, speed); + walk_hold(console, context, step, facing, interrupts, speed, player); break; case RouteAction::SURF: start_surf(console, context, step.direction, facing == step.direction); @@ -899,8 +967,17 @@ void walk_overworld_route( // (console B, 2026-11-11, 09.02 moon_stone). turn_to(console, context, step.direction, player); break; + case RouteAction::OPEN_GATE: + case RouteAction::PRESS_SWITCH: + turn_to(console, context, step.direction, player); + if (step.action == RouteAction::OPEN_GATE){ + open_gate(console, context, step.direction, true); + }else{ + press_switch(console, context, step.direction, true); + } + break; } - if (step.action != RouteAction::FACE){ + if (step.action != RouteAction::FACE && step.action != RouteAction::OPEN_GATE && step.action != RouteAction::PRESS_SWITCH){ const OverworldInterrupts& watched = step.wild ? interrupts.wild : interrupts.other; if (Pokemon::clear_late_interrupts(console, context, watched, step.wild ? AFTER_WILD_LEG_WATCH : AFTER_LEG_WATCH, MAX_INTERRUPTIONS_PER_LEG) == 0){ clear_unseen_battle(console, context, interrupts.wild, step); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkGates.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkGates.h new file mode 100644 index 0000000000..cdbbfd6907 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkGates.h @@ -0,0 +1,38 @@ +/* Overworld Walk Gates + * + * From: https://github.com/PokemonAutomation/ + * + * The console steps of a route through gates (RouteAction::OPEN_GATE and + * PRESS_SWITCH), next to the other steps of OverworldWalkSteps. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_OverworldWalkGates_H +#define PokemonAutomation_PokemonFRLG_OverworldWalkGates_H + +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonFRLG_OverworldRoute.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ +namespace OverworldWalkSteps{ + + +// Facing a card-key gate `direction` (turning first unless `facing_gate`), +// presses A: with the Card Key the game says so and the door opens. B +// clears the message, then the walk waits for the door to settle. +void open_gate(ConsoleHandle& console, ProControllerContext& context, Direction direction, bool facing_gate); + +// Facing a statue `direction` (turning first unless `facing_statue`), +// presses A, takes Yes at the prompt, and clears the text with B. +void press_switch(ConsoleHandle& console, ProControllerContext& context, Direction direction, bool facing_statue); + + + +} // namespace OverworldWalkSteps +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp index a7ddecc44a..970080ca26 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.cpp @@ -573,7 +573,10 @@ void flee_battle(ConsoleHandle& console, ProControllerContext& context){ } } -bool exit_wild_battle(ConsoleHandle& console, ProControllerContext& context, bool stop_on_move_learn, bool prevent_evolution){ +WildBattleExitResult exit_wild_battle( + Logger& logger, WildBattleExitActions& actions, + bool stop_on_move_learn, bool prevent_evolution +){ // For move learning, there are two dialog selection boxes in a row // we need to decline the first one and accept the second one, so mashing B won't work // The first one will occur after an Advance Battle Dialog @@ -585,113 +588,70 @@ bool exit_wild_battle(ConsoleHandle& console, ProControllerContext& context, boo bool evolved = false; while (true){ if (errors > 5 || loops > 5){ - OperationFailedExceptionWithScreenshot::fire( - ErrorReportMode::SEND_ERROR_REPORT, - "exit_wild_battle(): Failed to exit battle.", - console - ); + return WildBattleExitResult::Failed; } - BlackScreenWatcher battle_exited(COLOR_RED); - AdvanceBattleDialogWatcher advance_dialog(COLOR_RED); - BattleLearnDialogWatcher move_learn_select(COLOR_RED); + WildBattleExitEvent event = first_attempt + ? actions.mash_b_until_battle_exited() + : actions.press_until_dialog(rejected_first_box ? BUTTON_A : BUTTON_B); - context.wait_for_all_requests(); - WallClock deadline = current_time() + 30s; - int ret; - if (first_attempt){ - ret = run_until( - console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 20000ms); - }, - { battle_exited } - ); - }else{ - ret = run_until( - console, context, - [deadline, rejected_first_box](ProControllerContext& context){ - pbf_wait(context, 1000ms); // give the watchers a chance to detect something - while (current_time() < deadline){ - pbf_press_button(context, rejected_first_box ? BUTTON_A : BUTTON_B, 200ms, 1800ms); - // Presses are queued, so without this the loop queues a minute of them - // before the deadline and keeps pressing long after it. - context.wait_for_all_requests(); - } - }, - { battle_exited, advance_dialog, move_learn_select } - ); - } - - BattleDialogWatcher evolution_started(COLOR_RED); - int ret2; - - switch (ret){ - case 0: + switch (event){ + case WildBattleExitEvent::BattleExited: // check for the evolution screen - context.wait_for_all_requests(); - ret2 = run_until( - console, context, - [](ProControllerContext& context){ - pbf_wait(context, 2000ms); - }, - { evolution_started } - ); - - if (ret2 == 0){ - console.log("Evolution detected."); + if (actions.evolution_started()){ + logger.log("Evolution detected."); evolved = true; if (!prevent_evolution){ // make sure B isn't pressed too soon, which would cancel the evolution - pbf_wait(context, 20000ms); + actions.wait_for_evolution(); } rejected_first_box = false; continue; // press B as in other cases, and handle any move learning loops that might come up } - console.log("Battle exited."); - return move_learned; - case 1: - console.log("Battle Advance arrow detected."); - pbf_press_button(context, BUTTON_B, 200ms, 800ms); + logger.log("Battle exited."); + return move_learned ? WildBattleExitResult::ExitedAfterMoveLearn : WildBattleExitResult::Exited; + case WildBattleExitEvent::AdvanceDialog: + logger.log("Battle Advance arrow detected."); + actions.advance_dialog(); rejected_first_box = false; continue; - case 2: + case WildBattleExitEvent::MoveLearnPrompt: if (stop_on_move_learn){ - console.log("Move learn detected."); - return true; + logger.log("Move learn detected."); + return WildBattleExitResult::StoppedOnMoveLearn; }else if (rejected_first_box){ loops++; - console.log("Declined to learn new move."); - pbf_press_button(context, BUTTON_A, 200ms, 0ms); + logger.log("Declined to learn new move."); + actions.answer_move_prompt(BUTTON_A); }else{ - pbf_press_button(context, BUTTON_B, 200ms, 0ms); + actions.answer_move_prompt(BUTTON_B); rejected_first_box = true; move_learned = true; } continue; - default: + case WildBattleExitEvent::None: // An evolution ends on the overworld without another black screen, so nothing above // can see that it is over. Check for the overworld now, instead of pressing B for // another 30 seconds first. if (evolved){ evolved = false; first_attempt = false; - if (in_overworld(console, context)){ - console.log("Battle exited."); - return move_learned; + if (actions.return_to_overworld()){ + logger.log("Battle exited."); + return move_learned ? WildBattleExitResult::ExitedAfterMoveLearn : WildBattleExitResult::Exited; } continue; } if (first_attempt){ - console.log("Loop detected."); + logger.log("Loop detected."); first_attempt = false; continue; } - console.log("Failed to detect expected battle dialogs."); + logger.log("Failed to detect expected battle dialogs."); errors++; - if (in_overworld(console, context)){ - console.log("Battle exited."); - return move_learned; + if (actions.return_to_overworld()){ + logger.log("Battle exited."); + return move_learned ? WildBattleExitResult::ExitedAfterMoveLearn : WildBattleExitResult::Exited; } rejected_first_box = false; continue; @@ -699,6 +659,124 @@ bool exit_wild_battle(ConsoleHandle& console, ProControllerContext& context, boo } } +namespace{ + +class ConsoleWildBattleExitActions : public WildBattleExitActions{ +public: + ConsoleWildBattleExitActions(ConsoleHandle& console, ProControllerContext& context) + : m_console(console), m_context(context) + {} + + virtual WildBattleExitEvent mash_b_until_battle_exited() override{ + BlackScreenWatcher battle_exited(COLOR_RED); + m_context.wait_for_all_requests(); + int ret = run_until( + m_console, m_context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 20000ms); + }, + { battle_exited } + ); + return ret == 0 ? WildBattleExitEvent::BattleExited : WildBattleExitEvent::None; + } + virtual WildBattleExitEvent press_until_dialog(Button button) override{ + BlackScreenWatcher battle_exited(COLOR_RED); + AdvanceBattleDialogWatcher advance_dialog(COLOR_RED); + BattleLearnDialogWatcher move_learn_select(COLOR_RED); + m_context.wait_for_all_requests(); + WallClock deadline = current_time() + 30s; + int ret = run_until( + m_console, m_context, + [deadline, button](ProControllerContext& context){ + pbf_wait(context, 1000ms); // give the watchers a chance to detect something + while (current_time() < deadline){ + pbf_press_button(context, button, 200ms, 1800ms); + // Presses are queued, so without this the loop queues a minute of them + // before the deadline and keeps pressing long after it. + context.wait_for_all_requests(); + } + }, + { battle_exited, advance_dialog, move_learn_select } + ); + switch (ret){ + case 0: + return WildBattleExitEvent::BattleExited; + case 1: + return WildBattleExitEvent::AdvanceDialog; + case 2: + return WildBattleExitEvent::MoveLearnPrompt; + default: + return WildBattleExitEvent::None; + } + } + virtual bool evolution_started() override{ + BattleDialogWatcher evolution_started(COLOR_RED); + m_context.wait_for_all_requests(); + int ret = run_until( + m_console, m_context, + [](ProControllerContext& context){ + pbf_wait(context, 2000ms); + }, + { evolution_started } + ); + return ret == 0; + } + virtual void wait_for_evolution() override{ + pbf_wait(m_context, 20000ms); + } + virtual void advance_dialog() override{ + pbf_press_button(m_context, BUTTON_B, 200ms, 800ms); + } + virtual void answer_move_prompt(Button button) override{ + pbf_press_button(m_context, button, 200ms, 0ms); + } + virtual bool return_to_overworld() override{ + StartMenuWatcher start_menu_open(COLOR_RED); + // attempt to exit any screen that might be open (party, bag, etc) + pbf_mash_button(m_context, BUTTON_B, 500ms); + // overworld detection: look for the start menu + m_context.wait_for_all_requests(); + int ret = run_until( + m_console, m_context, + [](ProControllerContext& context){ + pbf_press_button(context, BUTTON_PLUS, 200ms, 800ms); + pbf_press_button(context, BUTTON_PLUS, 200ms, 800ms); + pbf_press_button(context, BUTTON_PLUS, 200ms, 800ms); + }, + { start_menu_open } + ); + if (ret == 0){ + pbf_mash_button(m_context, BUTTON_B, 500ms); + } + m_context.wait_for_all_requests(); + return ret == 0; + } + +private: + ConsoleHandle& m_console; + ProControllerContext& m_context; +}; + +} + +bool exit_wild_battle(ConsoleHandle& console, ProControllerContext& context, bool stop_on_move_learn, bool prevent_evolution){ + ConsoleWildBattleExitActions actions(console, context); + switch (exit_wild_battle(console.logger(), actions, stop_on_move_learn, prevent_evolution)){ + case WildBattleExitResult::Exited: + return false; + case WildBattleExitResult::ExitedAfterMoveLearn: + case WildBattleExitResult::StoppedOnMoveLearn: + return true; + case WildBattleExitResult::Failed: + break; + } + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + "exit_wild_battle(): Failed to exit battle.", + console + ); +} + void open_party_menu_from_overworld(ConsoleHandle& console, ProControllerContext& context, StartMenuContext menu_context){ uint16_t errors = 0; bool start_menu_is_open = false; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h index b896431aa1..e802a4be6d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h @@ -9,6 +9,7 @@ #ifndef PokemonAutomation_PokemonFRLG_Navigation_H #define PokemonAutomation_PokemonFRLG_Navigation_H +#include "Common/Cpp/Logging/AbstractLogger.h" #include "CommonFramework/Language.h" #include "CommonFramework/Tools/VideoStream.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" @@ -74,6 +75,57 @@ void flee_battle(ConsoleHandle& console, ProControllerContext& context); // Returns true if a move was learned (even if it was rejected) and false otherwise. bool exit_wild_battle(ConsoleHandle& console, ProControllerContext& context, bool stop_on_move_learn, bool prevent_evolution); +// What a step of exit_wild_battle() saw. +enum class WildBattleExitEvent{ + BattleExited, // The screen went black as the battle ended. + AdvanceDialog, // A battle dialog is waiting for a button. + MoveLearnPrompt, // A Pokemon is trying to learn a move. + None, // Nothing was seen before the step timed out. +}; + +// The game steps that exit_wild_battle() takes. They are injected so that its decisions (what to +// press after each dialog, when to give up) run in tests without a Switch. +class WildBattleExitActions{ +public: + virtual ~WildBattleExitActions() = default; + + // Mash B for up to 20 seconds, until the battle ends. + virtual WildBattleExitEvent mash_b_until_battle_exited() = 0; + + // Press `button` every 2 seconds for up to 30 seconds, until the battle ends, a battle dialog + // waits for a button, or a move-learn prompt opens. + virtual WildBattleExitEvent press_until_dialog(Button button) = 0; + + // Right after the battle ends, check for a dialog, which means a Pokemon is evolving. + virtual bool evolution_started() = 0; + + // Wait for an evolution to finish without pressing B, which would cancel it. + virtual void wait_for_evolution() = 0; + + // Close a battle dialog that is waiting for a button. + virtual void advance_dialog() = 0; + + // Answer a move-learn prompt with `button`. + virtual void answer_move_prompt(Button button) = 0; + + // Close any open screen, then check for the overworld by opening the start menu. Returns true + // if it opened; it is closed again. + virtual bool return_to_overworld() = 0; +}; + +enum class WildBattleExitResult{ + Exited, + ExitedAfterMoveLearn, // A move-learn prompt came up and the move was declined. + StoppedOnMoveLearn, // Stopped at a move-learn prompt, as stop_on_move_learn asks. + Failed, +}; + +// The decisions of exit_wild_battle(), taking its game steps from `actions`. +WildBattleExitResult exit_wild_battle( + Logger& logger, WildBattleExitActions& actions, + bool stop_on_move_learn, bool prevent_evolution +); + // Starting from the start menu, a sub-screen of the start menu, or the overworld, navigate to the party screen enum class StartMenuContext { STANDARD, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 66947d9483..9516b4c908 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -57,6 +57,8 @@ #include "Programs/AutoStory/PokemonFRLG_AutoStoryRows12_Tests.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRows14_Tests.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRows15_Tests.h" +#include "Overworld/PokemonFRLG_OverworldGateMaps_Tests.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryGates_Tests.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRows13_Tests.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRows16_Tests.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryTable.h" @@ -343,6 +345,8 @@ static void add_tests_AutoStoryRows(UnitTestDatabase& database){ add_tests_AutoStoryCinnabarGym(database); add_tests_AutoStorySilph(database); add_tests_AutoStoryMansion(database); + add_tests_AutoStoryGates(database); + add_tests_OverworldGateMaps(database); } void add_tests(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp index e9d59ecdd5..18bc4398cf 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp @@ -14,6 +14,7 @@ #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "Pokemon/Navigation/Pokemon_RouteLog.h" #include "VideoGames/PokemonFRLG/Inference/Dialogs/PokemonFRLG_DialogDetector.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGatedRoute.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldReanchor.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecoveryWalk.h" @@ -158,7 +159,7 @@ Outcome walk_route(StoryEnv& env, RunState& state, const StoryStep& step, const return Pokemon::outcome_failed("bad_target", Pokemon::to_string(target_pose)); } const RouteGoal goal{{target->map, target->tile}, target->facing}; - const std::optional> route = plan_story_route(maps, state.pose, facing, goal); + const std::optional> route = plan_story_route(maps, state.pose, facing, goal, state.gates, Pokemon::gate_rules_of(state)); if (!route){ return Pokemon::outcome_failed("no_route", Pokemon::to_string(state.pose) + " to " + to_string(goal.position)); } @@ -167,10 +168,10 @@ Outcome walk_route(StoryEnv& env, RunState& state, const StoryStep& step, const } const OverworldInterruptSet interrupts = walk_interrupts(env, step); // Planning lets the walker recover a stopped open leg: it plans back to - // the leg's end, then walks the rest as given. From a set of tiles - // the start isn't known: the walker reads the facing. - const RoutePlanning planning{.maps = &maps, .costs = story_route_costs(), .start = start, .label = step.name, .wall_check = wall_check(env)}; + // the leg's end, then walks the rest. From a set of tiles: reads the facing. + const RoutePlanning planning{.maps = &maps, .gates = state.gates, .costs = story_route_costs(), .start = start, .label = step.name, .wall_check = wall_check(env)}; walk_overworld_route_with_recovery(env.console, env.context, *route, planning, env.player_gender, facing, interrupts, move_speed(step)); + state.gates = gates_after_route(state.gates, *route); log_arrival(env, step.name, target->map, target->tile); const std::optional end_facing = route->empty() ? facing : std::optional(route->back().facing_after); return Pokemon::outcome_ok(to_pose(StoryPose{target->map, target->tile, end_facing})); @@ -435,7 +436,8 @@ Pokemon::Pose paced_pose(const Pokemon::Pose& patch, const StoryStep& step){ std::optional> plan_story_route( const std::vector& maps, const Pokemon::Pose& pose, - std::optional facing, const RouteGoal& goal + std::optional facing, const RouteGoal& goal, + const Pokemon::GateState& gates, const Pokemon::GateRules& rules ){ std::vector tiles; for (const TilePos& tile : Pokemon::tiles_of(pose)){ @@ -449,7 +451,7 @@ std::optional> plan_story_route( if (!holds->empty()){ facing = holds->back().facing_after; } - std::optional> route = plan_overworld_route(maps, from, goal, story_route_costs(), facing); + std::optional> route = plan_overworld_route_gated(maps, from, goal, gates, rules, story_route_costs(), facing); if (route){ route->insert(route->begin(), holds->begin(), holds->end()); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGates_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGates_Tests.cpp new file mode 100644 index 0000000000..faf10ba2a6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGates_Tests.cpp @@ -0,0 +1,439 @@ +/* AutoStory Gates Tests + * + * From: https://github.com/PokemonAutomation/ + * + * A ROUTE step on the row sims with gates: StoryMapsSim (the whole story + * on maps) and OverworldStepSim (a row's steps on the OverworldSim) stop at + * a closed Silph Co. card-key door, open it for a player with the Card Key + * and keep the gate state, and press a Pokemon Mansion statue for the + * barrier its switch opens. + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "Pokemon/AutoStory/Pokemon_StoryPose.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGatedRoute.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" +#include "PokemonFRLG_AutoStoryGates_Tests.h" +#include "PokemonFRLG_AutoStoryPoses.h" +#include "PokemonFRLG_AutoStoryRowSim.h" +#include "PokemonFRLG_StoryReplay.h" +#include "PokemonFRLG_StoryReplay_IO.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + +namespace{ + +struct GatesInput{ + std::string name; + std::function body; +}; +struct GatesExpectation{ +}; +struct GatesCase{ + GatesInput input; + GatesExpectation expectation; +}; + +class Test_AutoStoryGates : public UnitTest{ +public: + explicit Test_AutoStoryGates(GatesCase test_case) + : UnitTest("PokemonFRLG::AutoStoryGates - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_case.input.body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + GatesCase m_case; +}; + +// A walk across a gate on the real maps: Silph Co. 5F's card-key door, and +// the Pokemon Mansion 1F's barrier behind its statue's switch. +struct Scene{ + std::string_view map; + TilePos start; + TilePos goal; +}; +constexpr Scene DOOR{"SilphCo_5F", {10, 9}, {5, 9}}; +constexpr Scene STATUE{"PokemonMansion_1F", {5, 8}, {19, 13}}; + +const std::vector& scene_maps(){ + static const std::vector MAPS = overworld_maps(); + return MAPS; +} + +StoryStep route_step(const std::string& map, TilePos goal){ + StoryStep step; + step.kind = StoryStepKind::ROUTE; + step.name = "cross"; + step.args["target"] = Pokemon::GridPose{map, {goal}, std::nullopt}; + return step; +} + +Pokemon::RunState run_state(const Scene& scene, bool card_key){ + Pokemon::RunState state; + state.pose = to_pose(StoryPose{std::string(scene.map), scene.start, Direction::EAST}); + if (card_key){ + state.flags.insert("card_key_held"); + } + return state; +} + +// The step on StoryMapsSim over `maps`, from the start of the corridor. +Pokemon::Outcome on_maps(const Scene& scene, bool card_key, Pokemon::RunState& state){ + StorySimKnobs knobs; + knobs.maps = &scene_maps(); + StoryMapsSim sim(knobs); + state = run_state(scene, card_key); + return sim.run(route_step(std::string(scene.map), scene.goal), state); +} + + +// A closed door stops a player without the Card Key: the story's sim does +// not walk through gates the run has not opened. +UnitTestResult test_maps_sim_door_blocks(){ + Pokemon::RunState state; + const Pokemon::Outcome outcome = on_maps(DOOR, false, state); + if (outcome.succeeded()){ + return "The row sim walked through a closed card-key door without the Card Key."; + } + return true; +} + +UnitTestResult test_maps_sim_door_opens(){ + Pokemon::RunState state; + const Pokemon::Outcome outcome = on_maps(DOOR, true, state); + if (!outcome.succeeded()){ + return "The row sim did not open the door for a player with the Card Key: " + Pokemon::to_string(outcome); + } + if (!state.gates.opened.contains("SilphCo_5F/door_1")){ + return "The run's gates do not have the door open after the step."; + } + return true; +} + +UnitTestResult test_maps_sim_statue_switch(){ + Pokemon::RunState state; + const Pokemon::Outcome outcome = on_maps(STATUE, false, state); + if (!outcome.succeeded()){ + return "The row sim did not press the statue for the barrier: " + Pokemon::to_string(outcome); + } + if (!state.gates.switch_on("mansion")){ + return "The run's gates do not have the switch on after the step."; + } + return true; +} + +struct GateStateOut{ + Pokemon::GateState gates; + MapPosition position; +}; + +// The step on OverworldStepSim and its OverworldSim, with the Card Key as `card_key`. +std::string on_overworld_sim(const Scene& scene, bool card_key, GateStateOut& out){ + SimScript script; + script.card_key_held = card_key; + OverworldSim sim(scene_maps(), MapPosition{std::string(scene.map), scene.start}, Direction::EAST, script); + StoryPose at{std::string(scene.map), scene.start, Direction::EAST}; + const std::string failure = row_step_on_sim(sim, at, route_step(std::string(scene.map), scene.goal), "test"); + out.gates = sim.state().gates; + out.position = sim.state().position; + return failure; +} + +UnitTestResult test_step_sim_door_blocks(){ + GateStateOut out; + if (on_overworld_sim(DOOR, false, out).empty()){ + return "The step walked through a closed card-key door without the Card Key."; + } + return true; +} + +UnitTestResult test_step_sim_door_opens(){ + GateStateOut out; + const std::string failure = on_overworld_sim(DOOR, true, out); + if (!failure.empty()){ + return "The step did not open the door for a player with the Card Key: " + failure; + } + if (!out.gates.opened.contains("SilphCo_5F/door_1") || !(out.position == MapPosition{std::string(DOOR.map), DOOR.goal})){ + return "Expected the door open and the player at the goal, ended at " + to_string(out.position); + } + return true; +} + +UnitTestResult test_step_sim_statue_switch(){ + GateStateOut out; + const std::string failure = on_overworld_sim(STATUE, false, out); + if (!failure.empty()){ + return "The step did not press the statue: " + failure; + } + if (!out.gates.switch_on("mansion") || !(out.position == MapPosition{std::string(STATUE.map), STATUE.goal})){ + return "Expected the switch on and the player at the goal, ended at " + to_string(out.position); + } + return true; +} + +// A recorded route replayed on the real maps: the native planner's route +// through the gate as the replay's supplied commands (what a recording of +// the walk holds), replayed by the story engine on the pinned maps with the +// run's flags (the Card Key) and the gates the route's commands change. +constexpr std::string_view REVISION = "0123456789abcdef0123456789abcdef01234567"; +constexpr std::string_view CHECKPOINT_ID = "99.01"; + +const MapData& scene_map(const Scene& scene){ + for (const MapData& map : scene_maps()){ + if (map.name == scene.map){ + return map; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown scene map."); +} + +JsonObject tile_json(const Scene& scene, TilePos tile, std::string_view facing){ + JsonArray pair; + pair.push_back(tile.x); + pair.push_back(tile.y); + JsonArray tiles; + tiles.push_back(std::move(pair)); + JsonObject where; + where["kind"] = "tiles"; + where["tiles"] = std::move(tiles); + where["facing"] = std::string(facing); + JsonObject pose; + pose["certainty"] = "tile"; + pose["map"] = std::string(scene.map); + pose["where"] = std::move(where); + return pose; +} + +// The planned route as supplied commands: walks, turns, and the gate's A press. +JsonArray recorded_commands(const Scene& scene, const std::vector& route){ + JsonArray commands; + for (const RouteStep& step : route){ + JsonObject command; + command["event"] = "cross"; + command["map"] = std::string(scene.map); + command["direction"] = std::string(direction_name(step.direction)); + switch (step.action){ + case RouteAction::WALK: + command["kind"] = "walk"; + command["tiles"] = step.tiles; + break; + case RouteAction::FACE: + command["kind"] = "turn"; + break; + case RouteAction::OPEN_GATE: + command["kind"] = "open_gate"; + break; + case RouteAction::PRESS_SWITCH: + command["kind"] = "press_switch"; + break; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "The scene's route has a step the replay does not take."); + } + commands.push_back(std::move(command)); + } + return commands; +} + +// The capture of the scene's checkpoint: one route across it, to `facing_after`. +std::string capture_text(const Scene& scene, Direction facing_after){ + JsonObject target = tile_json(scene, scene.goal, direction_name(facing_after)); + JsonObject event; + event["id"] = "cross"; + event["kind"] = "route"; + event["target"] = std::move(target); + event["why"] = "across the gate"; + JsonArray events; + events.push_back(std::move(event)); + JsonObject checkpoint; + checkpoint["id"] = std::string(CHECKPOINT_ID); + checkpoint["title"] = "Gate replay"; + checkpoint["start"] = tile_json(scene, scene.start, "east"); + checkpoint["events"] = std::move(events); + JsonObject capture; + capture["format"] = "pokesim-native-checkpoint-export/1"; + capture["game"] = "frlg"; + capture["checkpoint"] = std::move(checkpoint); + capture["source_revision"] = std::string(REVISION); + capture["unbound"] = JsonArray(); + return capture.dump(-1); +} + +// The binding of that capture to the scene's map, as the replay pins it. +std::string binding_text(const Scene& scene, const std::string& capture){ + std::string map_hash; + for (const auto& [name, text] : overworld_map_json()){ + if (name == scene.map){ + map_hash = StoryReplayInternal::digest(text); + } + } + JsonObject capture_pin; + capture_pin["file"] = "gate-replay.json"; + capture_pin["sha256"] = StoryReplayInternal::digest(capture); + capture_pin["source_revision"] = std::string(REVISION); + JsonObject maps; + maps[std::string(scene.map)] = map_hash; + JsonObject capability; + capability["capability"] = "frlg-runtime-route/1"; + capability["parameters"] = JsonObject(); + JsonObject capabilities; + capabilities["cross"] = std::move(capability); + JsonObject costs; + costs["tile"] = 1; + costs["turn"] = 2; + costs["grass"] = 5; + costs["warp"] = 1; + JsonObject policy; + policy["basis"] = "synthetic-offline-policy"; + policy["entry"] = "scripted-observation"; + policy["attempts"] = 1; + policy["failure"] = "stop"; + policy["save"] = "never"; + JsonObject binding; + binding["format"] = "pokesim-story-replay-binding/1"; + binding["capture"] = std::move(capture_pin); + binding["map_revision"] = std::string(REVISION); + binding["maps"] = std::move(maps); + binding["capabilities"] = std::move(capabilities); + binding["costs"] = std::move(costs); + binding["max_route_moves"] = 256; + binding["policy"] = std::move(policy); + return binding.dump(-1); +} + +// The scenario: the player on the scene's start, with the Card Key if `card_key`. +JsonValue scenario_json(const Scene& scene, bool card_key){ + JsonObject entry_pose; + entry_pose["map"] = std::string(scene.map); + JsonArray tile; + tile.push_back(scene.start.x); + tile.push_back(scene.start.y); + entry_pose["tile"] = std::move(tile); + entry_pose["facing"] = "east"; + entry_pose["elevation"] = elevation_at(scene_map(scene), scene.start); + JsonObject entry; + entry["basis"] = "scripted"; + entry["screen"] = "overworld"; + entry["pose"] = std::move(entry_pose); + JsonObject scenario; + scenario["entry"] = std::move(entry); + scenario["signals"] = JsonObject(); + JsonArray flags; + if (card_key){ + flags.push_back("card_key_held"); + } + scenario["start_flags"] = std::move(flags); + return scenario; +} + +// The scene's checkpoint replayed with the route recorded for a player who has the +// Card Key, for a run that has it if `card_key`. Throws what the replay rejects. +JsonValue replay_scene(const Scene& scene, bool card_key){ + const std::optional> route = plan_overworld_route_gated( + scene_maps(), MapPosition{std::string(scene.map), scene.start}, RouteGoal{MapPosition{std::string(scene.map), scene.goal}, std::nullopt}, + Pokemon::GateState(), Pokemon::GateRules{.card_key_held = true}, default_route_costs(), Direction::EAST + ); + if (!route){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No route across the scene to record."); + } + const std::string capture = capture_text(scene, route->back().direction); + const std::string binding = binding_text(scene, capture); + JsonObject routes; + routes["cross"] = recorded_commands(scene, *route); + JsonObject candidate; + candidate["format"] = "pokesim-route-candidate/1"; + candidate["binding_sha256"] = StoryReplayInternal::digest(binding); + candidate["checkpoint"] = std::string(CHECKPOINT_ID); + candidate["routes"] = std::move(routes); + return replay_story_checkpoint(capture, binding, candidate.dump(-1), scenario_json(scene, card_key)); +} + +// The replay completed the checkpoint and its actions have `kind` (the gate's command). +std::string completed_with(const JsonValue& report, std::string_view kind){ + const JsonObject& root = report.to_object_throw(); + if (root.get_string_throw("status") != "model_complete"){ + return std::format("The replay stopped: {}", report.dump(-1)); + } + for (const JsonValue& action : root.get_array_throw("actions")){ + if (action.to_object_throw().get_string_throw("kind") == kind){ + return ""; + } + } + return std::format("The replay's actions have no {}.", kind); +} + +UnitTestResult test_replay_door_with_card_key(){ + const std::string failure = completed_with(replay_scene(DOOR, true), "open_gate"); + if (!failure.empty()){ + return failure; + } + return true; +} + +// The recording was made with the Card Key; the run's scenario has none. +UnitTestResult test_replay_door_without_card_key(){ + try{ + const std::string failure = completed_with(replay_scene(DOOR, false), "open_gate"); + if (failure.empty()){ + return "The replay opened a card-key door for a run without the Card Key."; + } + }catch (const ParseException& e){ + if (e.message().find("card-key") == std::string::npos){ + return std::format("Unexpected rejection: {}", e.message()); + } + } + return true; +} + +UnitTestResult test_replay_statue_switch(){ + const std::string failure = completed_with(replay_scene(STATUE, false), "press_switch"); + if (!failure.empty()){ + return failure; + } + return true; +} + +const std::vector GATES_CASES{ + {.input = {.name = "story maps: a closed door blocks without the Card Key", .body = test_maps_sim_door_blocks}, .expectation = {}}, + {.input = {.name = "story maps: the door opens with the Card Key and stays open", .body = test_maps_sim_door_opens}, .expectation = {}}, + {.input = {.name = "story maps: the statue's switch opens its barrier", .body = test_maps_sim_statue_switch}, .expectation = {}}, + {.input = {.name = "overworld sim: a closed door blocks without the Card Key", .body = test_step_sim_door_blocks}, .expectation = {}}, + {.input = {.name = "overworld sim: the door opens with the Card Key", .body = test_step_sim_door_opens}, .expectation = {}}, + {.input = {.name = "overworld sim: the statue's switch opens its barrier", .body = test_step_sim_statue_switch}, .expectation = {}}, + {.input = {.name = "replay: a recorded route opens Silph Co.'s card-key door", .body = test_replay_door_with_card_key}, .expectation = {}}, + {.input = {.name = "replay: the recorded door stays shut without the Card Key", .body = test_replay_door_without_card_key}, .expectation = {}}, + {.input = {.name = "replay: a recorded route presses the Mansion's statue", .body = test_replay_statue_switch}, .expectation = {}}, +}; + +} // namespace + + +void add_tests_AutoStoryGates(UnitTestDatabase& database){ + for (const GatesCase& item : GATES_CASES){ + database.add(item); + } +} + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGates_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGates_Tests.h new file mode 100644 index 0000000000..e329fe4ede --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGates_Tests.h @@ -0,0 +1,27 @@ +/* AutoStory Gates Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Registration of the tests of the story's sims with gates: a Silph Co. + * card-key door and a Pokemon Mansion statue switch on the row sim. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryGates_Tests_H +#define PokemonAutomation_PokemonFRLG_AutoStoryGates_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// StoryMapsSim and OverworldStepSim honoring gates (PokemonFRLG_AutoStoryGates_Tests.cpp). +void add_tests_AutoStoryGates(UnitTestDatabase& database); + + +} // namespace PokemonFRLG +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMansion_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMansion_Tests.cpp index 01aeb65a89..8679139cba 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMansion_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMansion_Tests.cpp @@ -4,8 +4,9 @@ * * Rows 13.01 to 13.04 (StoryData/frlg-13.0N.plan.json) on the overworld * sim: Cinnabar's Center to the Pokemon Mansion's statue switches, the - * SECRET KEY and the Escape Rope out. The sim has the map's switch state - * (flag clear), so a step through a barrier the switches open is declared. + * SECRET KEY and the Escape Rope out. The sim reads the real maps through + * the switch's state, from the checkpoint's start_gates, and the routes + * press the statues themselves. * */ @@ -90,72 +91,27 @@ struct MansionRow{ std::vector floors; }; -// A step over a tile the switches open: the pack's maps are the clear -// state, where it is a wall, so the sim cannot walk it and the step's -// declared pose stands. `wall` is whether the tile it lands on is such a -// barrier on the map; the step after it, onto floor, is declared too. -struct SwitchStep{ - std::string_view row; - std::string_view step; - bool wall; -}; - -const SwitchStep SWITCH_STEPS[] = { - {"13.02", "into_opening_1", true}, - {"13.02", "into_opening_2", true}, - {"13.02", "through_opening", false}, - {"13.03", "into_room_2", true}, - {"13.03", "into_room_3", true}, - {"13.04", "into_opening", true}, - {"13.04", "through_opening", false}, -}; - -const SwitchStep* switch_step(std::string_view row, std::string_view step){ - for (const SwitchStep& item : SWITCH_STEPS){ - if (item.row == row && item.step == step){ - return &item; - } - } - return nullptr; -} - -bool map_wall(const MapPosition& at){ - for (const MapData& map : story_maps()){ - if (map.name == at.map){ - return map.tiles.at(at.point) == TileKind::WALL; - } - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, std::format("No map {}.", at.map)); -} - -// A row on the sim from its start: every step lands (a switch step on its -// declared pose, on a barrier that is a wall on the map), the row ends on -// its postcondition's tile after the floors it should cross, and nobody but Lewis is met and no rule is broken on the way (checked -// after each step). +// A row on the sim from its start, through the gates it has on a save +// (start_gates): every step lands (a route presses the statues it needs), +// the row ends on its postcondition's tile after the floors it should +// cross, the switch is as its last step says, and nobody but Lewis is met +// and no rule is broken on the way (checked after each step). UnitTestResult test_row(const MansionRow& expected){ const StoryCheckpoint& row = checkpoint(expected.id); StoryPose at = *story_pose(Pokemon::pose_of(*row.start)); + SimScript script; + script.gates = row.start_gates.value_or(Pokemon::GateState()); std::optional sim; - sim.emplace(story_maps(), MapPosition{at.map, at.tile}, *at.facing); + sim.emplace(story_maps(), MapPosition{at.map, at.tile}, *at.facing, script); std::vector floors; for (const StoryStep& step : row.steps){ - if (const SwitchStep* barrier = switch_step(row.id, step.name)){ - at = *story_pose(Pokemon::pose_of(*step.pose_after)); - if (map_wall(MapPosition{at.map, at.tile}) != barrier->wall){ - return std::format("{}/{}: expected {} on {}.", row.id, step.name, barrier->wall ? "a barrier" : "floor", to_string(MapPosition{at.map, at.tile})); - } - sim.emplace(story_maps(), MapPosition{at.map, at.tile}, *at.facing); - }else if (step.name == "escape_rope"){ + if (step.name == "escape_rope"){ // The rope's script has no map: the player stands where it says. at = *story_pose(Pokemon::pose_of(*step.pose_after)); - sim.emplace(story_maps(), MapPosition{at.map, at.tile}, *at.facing); + sim.emplace(story_maps(), MapPosition{at.map, at.tile}, *at.facing, script); }else if (const std::string failure = row_step_on_sim(*sim, at, step, row.id); !failure.empty()){ return std::format("{}: ended on {}; {}", row.id, to_string(sim->state().position), failure); } - if (step.name == "down_the_hole"){ - // The hole's fade: a declared step does not wait it out, a walk does. - sim->watch({}, OverworldWalkSteps::AFTER_WARP); - } if (!sim->state().violations.empty()){ return std::format("{}/{}: broke a rule on the way, on {}: {}.", row.id, step.name, to_string(sim->state().position), sim->state().violations.front()); } @@ -167,6 +123,9 @@ UnitTestResult test_row(const MansionRow& expected){ if (floors.empty() || floors.back() != at.map){ floors.push_back(at.map); } + if (step.name != "escape_rope"){ + script.gates = sim->state().gates; + } } if (!(MapPosition{at.map, at.tile} == expected.end)){ return std::format("{}: ended on {}, not {}.", row.id, to_string(MapPosition{at.map, at.tile}), to_string(expected.end)); @@ -181,31 +140,31 @@ UnitTestResult test_row(const MansionRow& expected){ return true; } -const MansionRow ROW_13_01{"13.01", {"PokemonMansion_3F", {12, 6}}, +const MansionRow ROW_13_01{"13.01", {"PokemonMansion_3F", {19, 13}}, {"PokemonMansion_3F"}}; const MansionRow ROW_13_02{"13.02", {"PokemonMansion_B1F", {34, 29}}, - {"PokemonMansion_3F", "PokemonMansion_1F", "PokemonMansion_B1F"}}; -const MansionRow ROW_13_03{"13.03", {"PokemonMansion_B1F", {27, 6}}, + {"PokemonMansion_1F", "PokemonMansion_B1F"}}; +const MansionRow ROW_13_03{"13.03", {"PokemonMansion_B1F", {23, 5}}, {"PokemonMansion_B1F"}}; const MansionRow ROW_13_04{"13.04", {"CinnabarIsland", {8, 4}}, {"PokemonMansion_B1F", "CinnabarIsland"}}; const AutoStoryMansionCase AUTO_STORY_MANSION_CASES[] = { { - .input = {.name = "13.01 Cinnabar to the Mansion's 3F statue", .body = []{ return test_row(ROW_13_01); }}, - .expectation = {.description = "through 1F and 2F to 3F's (12, 6), nobody met"}, + .input = {.name = "13.01 Cinnabar to the Mansion's 3F room of holes", .body = []{ return test_row(ROW_13_01); }}, + .expectation = {.description = "through 1F and 2F to 3F's (19, 13) by a statue press, nobody met"}, }, { - .input = {.name = "13.02 3F's opening, the hole, 1F's stairs", .body = []{ return test_row(ROW_13_02); }}, - .expectation = {.description = "through the declared opening and the hole to B1F's (34, 29)"}, + .input = {.name = "13.02 3F's hole, 1F's stairs", .body = []{ return test_row(ROW_13_02); }}, + .expectation = {.description = "through the hole and the stairs to B1F's (34, 29)"}, }, { - .input = {.name = "13.03 B1F's two statues, the Elixir and TM14", .body = []{ return test_row(ROW_13_03); }}, - .expectation = {.description = "through the declared opening to (27, 6), nobody but Lewis met"}, + .input = {.name = "13.03 B1F's Elixir and TM14", .body = []{ return test_row(ROW_13_03); }}, + .expectation = {.description = "by a statue press to the Elixir and TM14, nobody but Lewis met"}, }, { .input = {.name = "13.04 the SECRET KEY and the Escape Rope", .body = []{ return test_row(ROW_13_04); }}, - .expectation = {.description = "through the declared opening to the key, out by the rope to (8, 4)"}, + .expectation = {.description = "by a statue press to the key, out by the rope to (8, 4)"}, }, }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h index 46590fe54b..6fac86baf3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPacedRoute.h @@ -12,6 +12,7 @@ #include #include +#include "Pokemon/Navigation/Pokemon_GatedTypes.h" #include "Pokemon/Navigation/Pokemon_Grid.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMap.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" @@ -45,7 +46,8 @@ const RouteCosts& story_route_costs(); // Nothing if either can't be planned. std::optional> plan_story_route( const std::vector& maps, const Pokemon::Pose& pose, - std::optional facing, const RouteGoal& goal + std::optional facing, const RouteGoal& goal, + const Pokemon::GateState& gates = Pokemon::GateState(), const Pokemon::GateRules& rules = Pokemon::GateRules() ); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden13.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden13.h index 8f249b0c04..57e3a4717b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden13.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryPlanGolden13.h @@ -18,7 +18,7 @@ namespace PokemonFRLG{ // The stored plan lines of segment 13, after FRLG_PLAN_GOLDEN_16's. inline constexpr std::string_view FRLG_PLAN_GOLDEN_13[] = { - "13.01 mansion_3f from CinnabarIsland_PokemonCenter_1F (7, 4) facing north to PokemonMansion_3F (8, 3) facing east", + "13.01 mansion_holes from CinnabarIsland_PokemonCenter_1F (7, 4) facing north to PokemonMansion_3F (19, 13) facing south", "13.01 walk south 5 (warp) -> CinnabarIsland (14, 12) [walk only]", "13.01 walk east 7 -> CinnabarIsland (21, 12)", "13.01 walk north 7 (to wall) -> CinnabarIsland (21, 5)", @@ -32,8 +32,65 @@ inline constexpr std::string_view FRLG_PLAN_GOLDEN_13[] = { "13.01 walk west 8 -> PokemonMansion_2F (9, 6) [wild]", "13.01 walk north 3 (to wall) -> PokemonMansion_2F (9, 3) [wild]", "13.01 walk east 1 (warp) -> PokemonMansion_3F (8, 3)", - "13.02 down_to_b1f from PokemonMansion_1F (26, 27) facing north to PokemonMansion_B1F (34, 29) facing west", - "13.02 walk west 2 (warp) -> PokemonMansion_B1F (34, 29)", + "13.01 walk south 3 -> PokemonMansion_3F (8, 6) [wild]", + "13.01 walk east 4 -> PokemonMansion_3F (12, 6) [wild]", + "13.01 press switch north -> PokemonMansion_3F (12, 6)", + "13.01 walk east 8 (to wall) -> PokemonMansion_3F (20, 6) [wild]", + "13.01 walk north 3 (to wall) -> PokemonMansion_3F (20, 3) [wild]", + "13.01 walk west 1 (to wall) -> PokemonMansion_3F (19, 3) [wild]", + "13.01 walk south 10 -> PokemonMansion_3F (19, 13) [wild]", + "13.02 to_ted_room from PokemonMansion_3F (19, 13) facing south to PokemonMansion_1F (17, 23) facing south", + "13.02 walk south 5 (warp) -> PokemonMansion_1F (20, 22) [wild]", + "13.02 walk west 3 (to wall) -> PokemonMansion_1F (17, 22) [wild]", + "13.02 walk south 1 -> PokemonMansion_1F (17, 23) [wild]", + "13.02 past_ted from PokemonMansion_1F (17, 23) facing south to PokemonMansion_1F (17, 25) facing south", + "13.02 walk south 2 -> PokemonMansion_1F (17, 25) [wild]", + "13.02 down_to_b1f from PokemonMansion_1F (17, 25) facing south to PokemonMansion_B1F (34, 29) facing west", + "13.02 walk south 8 (to wall) -> PokemonMansion_1F (17, 33) [wild]", + "13.02 walk east 13 (to wall) -> PokemonMansion_1F (30, 33) [wild]", + "13.02 walk north 6 (to wall) -> PokemonMansion_1F (30, 27) [wild]", + "13.02 walk west 6 (warp) -> PokemonMansion_B1F (34, 29) [wild]", + "13.03 to_elixir from PokemonMansion_B1F (34, 29) facing west to PokemonMansion_B1F (34, 5) facing east", + "13.03 walk west 7 (to wall) -> PokemonMansion_B1F (27, 29) [wild]", + "13.03 walk north 12 (to wall) -> PokemonMansion_B1F (27, 17) [wild]", + "13.03 walk west 5 -> PokemonMansion_B1F (22, 17) [wild]", + "13.03 walk south 9 (to wall) -> PokemonMansion_B1F (22, 26) [wild]", + "13.03 walk east 3 (to wall) -> PokemonMansion_B1F (25, 26) [wild]", + "13.03 walk south 5 (to wall) -> PokemonMansion_B1F (25, 31) [wild]", + "13.03 walk west 1 -> PokemonMansion_B1F (24, 31) [wild]", + "13.03 walk north 1 (to wall) -> PokemonMansion_B1F (24, 30) [wild]", + "13.03 press switch north -> PokemonMansion_B1F (24, 30)", + "13.03 walk west 9 -> PokemonMansion_B1F (15, 30) [wild]", + "13.03 walk north 13 (to wall) -> PokemonMansion_B1F (15, 17) [wild]", + "13.03 walk east 14 (to wall) -> PokemonMansion_B1F (29, 17) [wild]", + "13.03 walk south 5 -> PokemonMansion_B1F (29, 22) [wild]", + "13.03 walk east 4 -> PokemonMansion_B1F (33, 22) [wild]", + "13.03 walk north 17 -> PokemonMansion_B1F (33, 5) [wild]", + "13.03 walk east 1 -> PokemonMansion_B1F (34, 5) [wild]", + "13.03 to_tm14 from PokemonMansion_B1F (34, 5) facing east to PokemonMansion_B1F (23, 5) facing north", + "13.03 walk west 4 -> PokemonMansion_B1F (30, 5) [wild]", + "13.03 walk south 8 (to wall) -> PokemonMansion_B1F (30, 13) [wild]", + "13.03 walk west 11 -> PokemonMansion_B1F (19, 13) [wild]", + "13.03 walk north 10 (to wall) -> PokemonMansion_B1F (19, 3) [wild]", + "13.03 walk east 5 (to wall) -> PokemonMansion_B1F (24, 3) [wild]", + "13.03 walk south 2 (to wall) -> PokemonMansion_B1F (24, 5) [wild]", + "13.03 walk west 1 -> PokemonMansion_B1F (23, 5) [wild]", + "13.03 face north -> PokemonMansion_B1F (23, 5)", + "13.04 to_key from PokemonMansion_B1F (23, 5) facing north to PokemonMansion_B1F (5, 6) facing south", + "13.04 walk west 4 -> PokemonMansion_B1F (19, 5) [wild]", + "13.04 walk south 8 (to wall) -> PokemonMansion_B1F (19, 13) [wild]", + "13.04 walk east 11 -> PokemonMansion_B1F (30, 13) [wild]", + "13.04 walk north 10 (to wall) -> PokemonMansion_B1F (30, 3) [wild]", + "13.04 walk west 4 (to wall) -> PokemonMansion_B1F (26, 3) [wild]", + "13.04 walk south 3 (to wall) -> PokemonMansion_B1F (26, 6) [wild]", + "13.04 walk east 1 -> PokemonMansion_B1F (27, 6) [wild]", + "13.04 press switch north -> PokemonMansion_B1F (27, 6)", + "13.04 walk east 3 -> PokemonMansion_B1F (30, 6) [wild]", + "13.04 walk south 4 -> PokemonMansion_B1F (30, 10) [wild]", + "13.04 walk west 29 (to wall) -> PokemonMansion_B1F (1, 10) [wild]", + "13.04 walk north 4 -> PokemonMansion_B1F (1, 6) [wild]", + "13.04 walk east 4 -> PokemonMansion_B1F (5, 6) [wild]", + "13.04 face south -> PokemonMansion_B1F (5, 6)", }; } // namespace PokemonFRLG diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp index 102739fb16..f5a138d6a9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.cpp @@ -12,11 +12,13 @@ #include #include #include "Common/Cpp/Exceptions.h" +#include "Pokemon/AutoStory/Pokemon_StoryPose.h" #include "Pokemon/AutoStory/Pokemon_TilePose.h" #include "PokemonFRLG_AutoStoryLegs.h" #include "PokemonFRLG_AutoStoryPacedRoute.h" #include "PokemonFRLG_AutoStoryActions.h" #include "PokemonFRLG_AutoStoryBattleDecisions.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGatedRoute.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk.h" #include "PokemonFRLG_AutoStoryFieldMoves.h" @@ -71,8 +73,8 @@ std::string stub_report(const std::vector& rows){ namespace{ -const MapData* map_named(const std::string& name){ - for (const MapData& map : story_maps()){ +const MapData* map_named(const std::string& name, const std::vector& maps = story_maps()){ + for (const MapData& map : maps){ if (map.name == name){ return ↦ } @@ -83,8 +85,8 @@ const MapData* map_named(const std::string& name){ // Whether the player, at the end of a WALK `step`, stops there holding on: // the map's edge, a wall, or water to Surf onto, but no warp of any kind, // even one to a map that isn't loaded. -bool stops_past_end(const RouteStep& step){ - const MapData& map = *map_named(step.end.map); +bool stops_past_end(const RouteStep& step, const std::vector& maps){ + const MapData& map = *map_named(step.end.map, maps); const TilePos here = step.end.point; const TilePos ahead = here.next(step.direction); if (!in_bounds(map, ahead)){ @@ -102,9 +104,9 @@ bool stops_past_end(const RouteStep& step){ // The first leg of `route` to a wall that holding on would carry past its // end, or nothing (console B, 2026-11-02: one rode Route 4's Pokemon // Center escalator). -std::optional overrun_wall_leg(const std::vector& route){ +std::optional overrun_wall_leg(const std::vector& route, const std::vector& maps){ for (const RouteStep& step : route){ - if (step.to_wall && !stops_past_end(step)){ + if (step.to_wall && !stops_past_end(step, maps)){ return to_string(step); } } @@ -117,14 +119,14 @@ struct Standing{ Direction facing = Direction::NORTH; std::string error; }; -Standing standing(const Pokemon::Pose& pose){ +Standing standing(const Pokemon::Pose& pose, const std::vector& maps){ const std::optional at = story_pose(pose); if (!at){ return {{}, Direction::NORTH, "no one-tile pose: " + Pokemon::to_string(pose)}; } std::optional facing = at->facing; if (!facing){ - const MapData* map = map_named(at->map); + const MapData* map = map_named(at->map, maps); facing = map ? wall_beside(*map, at->tile) : std::nullopt; } if (!facing){ @@ -209,7 +211,7 @@ StepInterruptActions StoryMapsSim::sim_interrupt_actions(){ Pokemon::StoryAction StoryMapsSim::action(StoryActionId id){ switch (id){ case StoryActionId::ROUTE: - return played([this](const StoryStep& step, RunState& state){ return walk_to(state.pose, step); }); + return played([this](const StoryStep& step, RunState& state){ return walk_to(state, step); }); case StoryActionId::LEGS: return played([this](const StoryStep& step, RunState& state){ return legs(state.pose, step); }); case StoryActionId::STEP: @@ -217,7 +219,9 @@ Pokemon::StoryAction StoryMapsSim::action(StoryActionId id){ // The nurse's way must plan too, but the run goes on from where it stands. case StoryActionId::READY: return played([this](const StoryStep& step, RunState& state){ - const Outcome to_nurse = walk_to(state.pose, step); + // The way to the nurse is walked in a copy: the run goes on from here. + RunState visit = state; + const Outcome to_nurse = walk_to(visit, step); return to_nurse.succeeded() ? Pokemon::outcome_ok() : to_nurse; }); case StoryActionId::SHOP: @@ -244,11 +248,11 @@ Pokemon::StoryAction StoryMapsSim::action(StoryActionId id){ } Outcome StoryMapsSim::legs(const Pokemon::Pose& pose, const StoryStep& step) const{ - const Standing at = standing(pose); + const Standing at = standing(pose, maps()); if (!at.error.empty()){ return Pokemon::outcome_failed("no_pose", at.error); } - const std::optional> route = fixed_route(story_maps(), at.position, Pokemon::story_arg>(step.args, "legs")); + const std::optional> route = fixed_route(maps(), at.position, Pokemon::story_arg>(step.args, "legs")); if (!route || route->empty()){ return Pokemon::outcome_failed("bad_legs", to_string(at.position)); } @@ -309,37 +313,45 @@ Outcome StoryMapsSim::shop(const StoryStep& step){ return Pokemon::outcome_ok(); } -Outcome StoryMapsSim::walk_to(const Pokemon::Pose& pose, const StoryStep& step) const{ +const std::vector& StoryMapsSim::maps() const{ + return m_knobs.maps != nullptr ? *m_knobs.maps : story_maps(); +} + +Outcome StoryMapsSim::walk_to(Pokemon::RunState& state, const StoryStep& step) const{ + const Pokemon::Pose& pose = state.pose; + const Pokemon::GateRules rules = Pokemon::gate_rules_of(state); if (Pokemon::tiles_of(pose).size() > 1){ // From the tiles a pacing step leaves: the route must plan, and // test_routes_after_pacing() walks it on the sim from each. const std::optional target = story_pose(Pokemon::pose_of(Pokemon::story_arg(step.args, "target"))); const RouteGoal goal{{target->map, target->tile}, target->facing}; - const std::optional> route = plan_story_route(story_maps(), pose, std::nullopt, goal); + const std::optional> route = plan_story_route(maps(), pose, std::nullopt, goal, state.gates, rules); if (!route || route->empty()){ return Pokemon::outcome_failed("no_route", Pokemon::to_string(pose) + " to " + to_string(goal.position)); } + state.gates = gates_after_route(state.gates, *route); return Pokemon::outcome_ok(to_pose(StoryPose{target->map, target->tile, route->back().facing_after})); } - const Standing at = standing(pose); + const Standing at = standing(pose, maps()); if (!at.error.empty()){ return Pokemon::outcome_failed("no_pose", at.error); } const std::optional target = story_pose(Pokemon::pose_of(Pokemon::story_arg(step.args, "target"))); const RouteGoal goal{{target->map, target->tile}, target->facing}; - const std::optional> route = plan_overworld_route( - story_maps(), at.position, goal, story_route_costs(), at.facing + const std::optional> route = plan_overworld_route_gated( + maps(), at.position, goal, state.gates, rules, story_route_costs(), at.facing ); if (!route){ return Pokemon::outcome_failed("no_route", to_string(at.position) + " to " + to_string(goal.position)); } - const MapPosition end = follow_overworld_route(story_maps(), at.position, *route); + const MapPosition end = follow_overworld_route(maps(), at.position, *route, state.gates); if (!(end == goal.position)){ return Pokemon::outcome_failed("wrong_end", to_string(end)); } - if (const std::optional leg = overrun_wall_leg(*route)){ + if (const std::optional leg = overrun_wall_leg(*route, maps())){ return Pokemon::outcome_failed("wall_overrun", *leg); } + state.gates = gates_after_route(state.gates, *route); const Direction facing = route->empty() ? at.facing : route->back().facing_after; return Pokemon::outcome_ok(to_pose(StoryPose{target->map, target->tile, facing})); } @@ -347,14 +359,17 @@ Outcome StoryMapsSim::walk_to(const Pokemon::Pose& pose, const StoryStep& step) // The route the program walks for `step`, a ROUTE or LEGS, from `at`: // planned, or the legs laid out. -std::optional> walked_route(const StoryPose& at, const StoryStep& step){ +std::optional> walked_route( + const StoryPose& at, const StoryStep& step, + const std::vector& maps, const Pokemon::GateState& gates, const Pokemon::GateRules& rules +){ const MapPosition start{at.map, at.tile}; if (step.kind == StoryStepKind::LEGS){ - return fixed_route(story_maps(), start, Pokemon::story_arg>(step.args, "legs")); + return fixed_route(maps, start, Pokemon::story_arg>(step.args, "legs")); } const std::optional target = story_pose(Pokemon::pose_of(Pokemon::story_arg(step.args, "target"))); const RouteGoal goal{{target->map, target->tile}, target->facing}; - return plan_overworld_route(story_maps(), start, goal, story_route_costs(), at.facing); + return plan_overworld_route_gated(maps, start, goal, gates, rules, story_route_costs(), at.facing); } @@ -471,12 +486,17 @@ void sim_wait_out_battle_exit(OverworldSim& sim){ // A ROUTE or LEGS by the sim's walker, fighting a trainer who sees the // player on the way. std::string OverworldStepSim::walk(const StoryStep& step){ - const std::optional> route = walked_route(m_at, step); + // The story's maps, as the planner and the program have them (the grunt the sim has + // hidden stands on them, and the stairs a switch opens are open); the gates are the sim's, + // which the walker's steps open. + const std::vector& maps = story_maps(); + const Pokemon::GateState& gates = m_sim.state().gates; + const std::optional> route = walked_route(m_at, step, maps, gates, Pokemon::GateRules{.card_key_held = m_sim.state().card_key_held}); if (route && route->empty()){ // Already there. return ""; } - const RoutePlanning planning{.maps = &story_maps(), .costs = story_route_costs(), .start = MapPosition{m_at.map, m_at.tile}, .label = step.name}; + const RoutePlanning planning{.maps = &maps, .gates = gates, .costs = story_route_costs(), .start = MapPosition{m_at.map, m_at.tile}, .label = step.name}; SimWalkerRules rules; rules.trainer_battle_end = battle_end_on_sim; // A BIKE_VARIANT rides, as on the console, when the sim has the diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.h index b4f7327504..593d763f06 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRowSim.h @@ -19,6 +19,8 @@ #include #include #include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "Pokemon/Navigation/Pokemon_GatedTypes.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" #include "PokemonFRLG_AutoStoryEvents.h" @@ -40,6 +42,9 @@ struct StorySimKnobs{ // Whether the executor clears what came up between steps // (step_interrupts()), as the console does; off, as before it did. bool clear_interrupts = true; + // The maps the story is planned and walked on, with the gates of the + // run state; the story's (story_maps()) if null. + const std::vector* maps = nullptr; }; // The whole story on the story maps, without a walker: each ROUTE planned @@ -84,7 +89,9 @@ class StoryMapsSim : public Pokemon::TableExecutor{ private: Pokemon::StoryAction action(StoryActionId id); - Pokemon::Outcome walk_to(const Pokemon::Pose& pose, const StoryStep& step) const; + const std::vector& maps() const; + // Plans the route and moves the run's pose and gates to its end. + Pokemon::Outcome walk_to(Pokemon::RunState& state, const StoryStep& step) const; Pokemon::Outcome legs(const Pokemon::Pose& pose, const StoryStep& step) const; Pokemon::Outcome step_ahead(const Pokemon::Pose& pose, const StoryStep& step) const; Pokemon::Outcome shop(const StoryStep& step); @@ -108,8 +115,14 @@ class StoryMapsSim : public Pokemon::TableExecutor{ // The route the program walks for `step`, a ROUTE or LEGS, from `at`: -// planned, or the legs laid out. -std::optional> walked_route(const StoryPose& at, const StoryStep& step); +// planned, or the legs laid out. A route is planned over `maps` through +// `gates`, and may open a card-key gate if `rules` say the player holds +// the Card Key. +std::optional> walked_route( + const StoryPose& at, const StoryStep& step, + const std::vector& maps = story_maps(), + const Pokemon::GateState& gates = Pokemon::GateState(), const Pokemon::GateRules& rules = Pokemon::GateRules() +); // A row's steps on the OverworldSim as the program does them: routes and // legs by the sim's walker from where the table says the player stands, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp index 369cd2c030..ecd536bdb6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp @@ -22,6 +22,7 @@ #include "Common/Cpp/TestRunners/UnitTest.h" #include "CommonFramework/ImageTypes/ImageRGB32.h" #include "VideoGames/PokemonFRLG/Inference/Menus/PokemonFRLG_OptionMenuReader.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGatedRoute.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldMaps.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRoute.h" @@ -95,6 +96,61 @@ const MapData* find_map_named(const std::string& name){ return nullptr; } +// The gates the walk the test is following has opened and the switches it +// has pressed, and whether it holds the Card Key: what the story's steps +// carry through a checkpoint (start_gates, gates_after, flags_after). Each +// test runs on one thread, from begin_walk() on. +struct WalkGates{ + Pokemon::GateState gates; + bool card_key_held = false; +}; +WalkGates& walk_state(){ + thread_local WalkGates walk; + return walk; +} + +// Starts a walk at `checkpoint`'s start: its start_gates and start_flags. +void begin_walk(const StoryCheckpoint& checkpoint){ + walk_state() = WalkGates{}; + if (checkpoint.start_gates){ + walk_state().gates = *checkpoint.start_gates; + } + walk_state().card_key_held = std::ranges::find(checkpoint.start_flags, "card_key_held") != checkpoint.start_flags.end(); +} + +// A walk through the checkpoint that follows the one before: only what its +// start says replaces the gates carried. +void continue_walk(const StoryCheckpoint& checkpoint){ + if (checkpoint.start_gates){ + walk_state().gates = *checkpoint.start_gates; + } + if (std::ranges::find(checkpoint.start_flags, "card_key_held") != checkpoint.start_flags.end()){ + walk_state().card_key_held = true; + } +} + +// What `step` does to the walk's gates once done, besides a route's own. +void apply_step_effects(const StoryStep& step){ + if (step.gates_after){ + apply_gate_change(walk_state().gates, *step.gates_after); + } + if (std::ranges::find(step.flags_after, "card_key_held") != step.flags_after.end()){ + walk_state().card_key_held = true; + } +} + +// The story's maps as the walk's gates make them. +const std::vector& walk_maps(){ + thread_local std::optional>> resolved; + if (!has_gates(story_maps())){ + return story_maps(); + } + if (!resolved || !(resolved->first == walk_state().gates)){ + resolved.emplace(walk_state().gates, resolve_maps(story_maps(), walk_state().gates)); + } + return resolved->second; +} + std::string describe(const std::vector& route){ std::string text; for (const RouteStep& step : route){ @@ -164,7 +220,7 @@ UnitTestResult check_held_legs(const std::string& name, const std::vector> route = fixed_route(story_maps(), MapPosition{pose.map, pose.tile}, Pokemon::story_arg>(step.args, "legs")); + const std::optional> route = fixed_route(walk_maps(), MapPosition{pose.map, pose.tile}, Pokemon::story_arg>(step.args, "legs")); if (!route || route->empty()){ return step.name + ": the legs can't be walked from " + describe(pose) + "."; } @@ -214,7 +270,8 @@ UnitTestResult check_route(StoryPose& pose, const StoryStep& step, std::vector(step.args, "target")); const RouteGoal goal{{target.map, target.tile}, target.facing}; - const std::optional> route = plan_overworld_route(story_maps(), start, goal, default_route_costs(), facing); + const Pokemon::GateRules rules{.card_key_held = walk_state().card_key_held}; + const std::optional> route = plan_overworld_route_gated(story_maps(), start, goal, walk_state().gates, rules, default_route_costs(), facing); if (!route){ return step.name + ": no route from " + to_string(start) + " to " + to_string(goal.position) + "."; } @@ -223,7 +280,7 @@ UnitTestResult check_route(StoryPose& pose, const StoryStep& step, std::vectorempty() ? facing : route->back().facing_after}; return true; } @@ -271,6 +329,7 @@ UnitTestResult check_checkpoint_steps(const StoryCheckpoint& checkpoint, StoryPo if (step.pose_after){ pose = one_tile(Pokemon::grid_pose_of(*step.pose_after)); } + apply_step_effects(step); } return true; } @@ -295,8 +354,10 @@ UnitTestResult chain_story_routes(std::vector& golden){ return "Expected 66 checkpoints, the first from a new game."; } StoryPose pose; + walk_state() = WalkGates{}; for (size_t c = 0; c < checkpoints.size(); c++){ const StoryCheckpoint& checkpoint = checkpoints[c]; + continue_walk(checkpoint); if (c > 0 && starts_after_unauthored_rows(checkpoint.id)){ pose = one_tile(Pokemon::grid_pose_of(*checkpoint.start)); }else if (c > 0){ @@ -542,12 +603,12 @@ std::vector legs_walked(const StoryPose& pose, const StoryStep& step) const MapPosition start{pose.map, pose.tile}; std::optional> route; if (step.kind == StoryStepKind::LEGS){ - route = fixed_route(story_maps(), start, Pokemon::story_arg>(step.args, "legs")); + route = fixed_route(walk_maps(), start, Pokemon::story_arg>(step.args, "legs")); }else if (step.args.contains("target")){ const MapData* map = find_map_named(pose.map); const std::optional facing = pose.facing ? pose.facing : map ? wall_beside(*map, pose.tile) : std::nullopt; const StoryPose target = one_tile(Pokemon::story_arg(step.args, "target")); - route = plan_overworld_route(story_maps(), start, RouteGoal{{target.map, target.tile}, target.facing}, story_route_costs(), facing); + route = plan_overworld_route_gated(story_maps(), start, RouteGoal{{target.map, target.tile}, target.facing}, walk_state().gates, Pokemon::GateRules{.card_key_held = walk_state().card_key_held}, story_route_costs(), facing); } return route ? *route : std::vector{}; } @@ -576,7 +637,7 @@ std::vector> wanderer_stops(const StoryPose& pose, co std::vector> stops; MapPosition from{pose.map, pose.tile}; for (const RouteStep& leg : legs_walked(pose, step)){ - const std::optional c = trainer_crossing(story_maps(), from, leg); + const std::optional c = trainer_crossing(walk_maps(), from, leg); if (c && std::any_of(c->seen.begin(), c->seen.end(), wanderer_sees)){ stops.push_back(c->seen.size() == 1 && !leg.wild && !leg.warps ? std::optional(c->seen[0]) : std::nullopt); } @@ -596,7 +657,7 @@ std::string held_past_lookers(const StoryPose& pose, const StoryStep& step, cons for (const RouteStep& leg : legs_walked(pose, step)){ const MapData* map = find_map_named(from.map); bool crosses = false; - for (const MapPosition& tile : leg.action == RouteAction::WALK && map ? leg_tiles(story_maps(), from, leg) : std::vector{}){ + for (const MapPosition& tile : leg.action == RouteAction::WALK && map ? leg_tiles(walk_maps(), from, leg) : std::vector{}){ for (const MapObject& object : map->objects){ crosses |= looks_around(object) && !beaten.contains(&object) && trainer_may_see(*map, object, tile.point); } @@ -615,7 +676,7 @@ std::vector tiles_walked(const StoryPose& pose, const StoryStep& st MapPosition from{pose.map, pose.tile}; for (const RouteStep& leg : legs_walked(pose, step)){ if (leg.action == RouteAction::WALK){ - const std::vector passed = leg_tiles(story_maps(), from, leg); + const std::vector passed = leg_tiles(walk_maps(), from, leg); tiles.insert(tiles.end(), passed.begin() + 1, passed.end()); } from = leg.end; @@ -666,6 +727,7 @@ UnitTestResult advance(StoryPose& pose, const StoryStep& step){ if (step.pose_after){ pose = one_tile(Pokemon::grid_pose_of(*step.pose_after)); } + apply_step_effects(step); return true; } @@ -674,6 +736,7 @@ UnitTestResult advance(StoryPose& pose, const StoryStep& step){ // `repelled`: a Repel the table used is on (it lasts past the // checkpoint's save): grass is walked as any floor. UnitTestResult check_lines(const StoryCheckpoint& checkpoint, std::set& beaten, bool& repelled){ + begin_walk(checkpoint); StoryPose pose = one_tile(Pokemon::grid_pose_of(*checkpoint.start)); for (size_t c = 0; c < checkpoint.steps.size(); c++){ const StoryStep& step = checkpoint.steps[c]; @@ -693,9 +756,9 @@ UnitTestResult check_lines(const StoryCheckpoint& checkpoint, std::set> stops = walks ? wanderer_stops(pose, step) : std::vector>{}; - // 13.03's walk into Lewis's room, B1F of the Pokemon Mansion: its one way in, + // 13.03's walk into (and, planned, past) Lewis's room, B1F of the Pokemon Mansion: its one way in, // (22, 24), is beside his wander range (19..21, 24..26), on a cave's wild floor. - const bool lewis = checkpoint.id == "13.03" && step.name == "to_statue"; + const bool lewis = checkpoint.id == "13.03" && (step.name == "to_statue" || step.name == "to_elixir"); if (!lewis && std::count(stops.begin(), stops.end(), std::nullopt) > 0){ return where + "crosses a wandering trainer's sight where the walk can't tell where they'd stop the player."; } @@ -765,6 +828,7 @@ UnitTestResult test_legs_onto_stairs_their_way(){ if (!walked){ continue; } + begin_walk(checkpoint); StoryPose pose = one_tile(Pokemon::grid_pose_of(*checkpoint.start)); for (const StoryStep& step : checkpoint.steps){ if (step.kind == StoryStepKind::ROUTE){ @@ -827,12 +891,13 @@ std::string approach_off_tile(const std::vector& legs){ // approach to the Rare Candy, "west 4" and "south 6" held open, ended a // tile west and met a gravestone (console B, 2026-11-12 04:39). // PASSED_ON_CONSOLE: approaches before 10.05 that passed their console -// runs as held legs (a follow-up to tap them). +// runs as held legs (a follow-up to tap them). 13.03 and 13.04 plan their statue +// approaches (PRESS_SWITCH) and have not run on a console. UnitTestResult test_approaches_end_on_their_tile(){ const std::set PASSED_ON_CONSOLE{ "02.02/below_oak", "03.02/before_brock", "05.07/below_bill_clefairy", "05.07/pc_front", "05.07/beside_bill", "06.01/behind_captain", "07.01/beside_chairman", "07.01/bike_clerk", - "09.01/below_poster_guard", "09.02/below_left_guard", "09.03/above_tea_woman", "10.01/below_fly_woman", + "09.01/below_poster_guard", "09.02/below_left_guard", "09.03/above_tea_woman", "10.01/below_fly_woman", "13.03/to_elixir", "13.04/to_key", // Not run on a console: 14.01 (#410) predates this rule. Its quiz machine approaches are held // open routes; tap them (follow-up) and drop these. "14.01/below_quiz_1", "14.01/below_quiz_2", "14.01/below_quiz_3", "14.01/below_quiz_4", @@ -845,6 +910,7 @@ UnitTestResult test_approaches_end_on_their_tile(){ if (!start){ continue; } + begin_walk(checkpoint); StoryPose pose = *start; // The legs of the ROUTE and LEGS steps since the last other step. std::vector approach; @@ -891,6 +957,7 @@ UnitTestResult test_facing_after_trainer_battles(){ if (!start){ continue; } + begin_walk(checkpoint); StoryPose pose = *start; for (size_t c = 0; c < checkpoint.steps.size(); c++){ const StoryStep& step = checkpoint.steps[c]; @@ -983,6 +1050,7 @@ UnitTestResult check_trigger(const TriggerCase& c){ return "No checkpoint " + c.checkpoint + "."; } const MapPosition onto{c.map, {c.onto_x, c.y}}; + begin_walk(*checkpoint); StoryPose pose = one_tile(Pokemon::grid_pose_of(*checkpoint->start)); for (const StoryStep& step : checkpoint->steps){ const std::string where = c.checkpoint + "/" + step.name + ": "; @@ -1032,6 +1100,7 @@ UnitTestResult test_nugget_bridge_order(){ } const std::vector& steps = checkpoint->steps; std::string met; + begin_walk(*checkpoint); StoryPose pose = one_tile(Pokemon::grid_pose_of(*checkpoint->start)); for (size_t c = 0; c < steps.size(); c++){ const MapData* map = find_map_named(pose.map); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay.cpp index 159a6c2488..c23b2eb102 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay.cpp @@ -26,6 +26,12 @@ JsonValue replay_story_checkpoint(std::string_view capture, std::string_view bin const auto entry = StoryReplayInternal::read_pose(scenario.to_object_throw().get_object_throw("entry").get_value_throw("pose"), data.maps); Pokemon::RunState state; state.pose = Pokemon::tile_pose(entry.position.map, {entry.position.point}, entry.facing); + // The run flags the checkpoint starts with (card_key_held opens card-key doors). + if (const JsonArray* flags = scenario.to_object_throw().get_array("start_flags")){ + for (const JsonValue& flag : *flags){ + state.flags.insert(flag.to_string_throw()); + } + } JsonArray logs; Pokemon::EventLogger logger = [&](const std::string& line){ logs.push_back(line); }; const Pokemon::CheckpointReport result = Pokemon::run_checkpoint(state, checkpoint, logger); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay_Executor.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay_Executor.cpp index f46ebfbe11..80faff34b3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay_Executor.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay_Executor.cpp @@ -6,6 +6,8 @@ #include "Common/Cpp/Exceptions.h" #include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" #include "Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h" +#include "Pokemon/Navigation/Pokemon_GateTiles.h" +#include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGatedRoute.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldSim.h" #include "PokemonFRLG_StoryReplay_Executor.h" namespace PokemonAutomation{ @@ -77,9 +79,9 @@ bool ReplayStepGuard::stops_on_failure(const StoryStep&) const{ Pokemon::StoryAction ReplayExecutor::replay_action(StoryActionId id){ switch (id){ case StoryActionId::ROUTE: - return {.act = [this](const StoryStep& step, Pokemon::RunState&){ return replay_route(step); }}; + return {.act = [this](const StoryStep& step, Pokemon::RunState& state){ return replay_route(step, state); }}; case StoryActionId::STEP: - return {.act = [this](const StoryStep& step, Pokemon::RunState&){ return replay_step(step); }}; + return {.act = [this](const StoryStep& step, Pokemon::RunState& state){ return replay_step(step, state); }}; case StoryActionId::MASH: return {.act = [this](const StoryStep& step, Pokemon::RunState&){ return replay_scene(step); }}; default: @@ -153,9 +155,62 @@ void ReplayExecutor::observe_interruption(const OverworldPose& predicted){ m_interrupted = true; lose_pose("unknown-after-interruption"); } -ReplayLeg ReplayExecutor::prepare_leg(const JsonValue& value, OverworldPose& current) const{ +const std::vector& ReplayExecutor::maps_through(const Pokemon::GateState& gates) const{ + if (!has_gates(m_data->maps)){ + return m_data->maps; + } + if (!m_resolved || !(m_resolved->first == gates)){ + m_resolved.emplace(gates, resolve_maps(m_data->maps, gates)); + } + return m_resolved->second; +} +// An open_gate or a press_switch: A at the gate or statue the player +// faces, which the model has to find there (and, for a gate, the player to +// hold the Card Key). +ReplayLeg ReplayExecutor::prepare_gate_leg(const JsonValue& value, const OverworldPose& current, Pokemon::GateState& gates) const{ + const JsonObject& command = value.to_object_throw(); + fields(value, {"event", "kind", "map", "direction"}); + const bool opens = command.get_string_throw("kind") == "open_gate"; + const Direction facing = direction(command.get_string_throw("direction")); + if (command.get_string_throw("event") != m_active || command.get_string_throw("map") != current.position.map){ + throw ParseException("story replay: supplied route has wrong event/map"); + } + if (current.facing != facing){ + throw ParseException("story replay: supplied gate command is not facing its gate"); + } + const MapData& map = map_named(m_data->maps, current.position.map); + Pokemon::GateState after = gates; + if (opens){ + const Pokemon::MapGate* gate = m_rules.card_key_held + ? Pokemon::closed_card_key_gate_faced(map, current.position.point, facing, gates) : nullptr; + if (gate == nullptr){ + throw ParseException("story replay: no card-key gate to open (or no Card Key)"); + } + after.opened.insert(Pokemon::gate_key(map.name, gate->id)); + }else{ + const Pokemon::MapSwitch* pressed = Pokemon::switch_pressed(map, current.position.point, facing); + if (pressed == nullptr){ + throw ParseException("story replay: no statue to press"); + } + if (pressed->toggle && gates.switch_on(pressed->id)){ + after.switches_on.erase(pressed->id); + }else{ + after.switches_on.insert(pressed->id); + } + } + RouteStep step{.action = opens ? RouteAction::OPEN_GATE : RouteAction::PRESS_SWITCH, .direction = facing, .tiles = 0}; + step.end = current.position; + step.facing_after = facing; + step.gate_change = Pokemon::gate_change_between(gates, after); + gates = std::move(after); + return ReplayLeg{.step = step, .action = value.clone()}; +} +ReplayLeg ReplayExecutor::prepare_leg(const JsonValue& value, OverworldPose& current, Pokemon::GateState& gates) const{ const JsonObject& command = value.to_object_throw(); const std::string kind = command.get_string_throw("kind"); + if (kind == "open_gate" || kind == "press_switch"){ + return prepare_gate_leg(value, current, gates); + } if (kind == "walk"){ fields(value, {"event", "kind", "map", "direction", "tiles"}); }else if (kind == "transition"){ @@ -175,7 +230,7 @@ ReplayLeg ReplayExecutor::prepare_leg(const JsonValue& value, OverworldPose& cur } RouteStep step{.action = kind == "turn" ? RouteAction::FACE : RouteAction::WALK, .direction = facing, .tiles = (int)tiles}; for (int64_t n = 0; n < tiles; n++){ - const auto next = predict_overworld_press(m_data->maps, current, facing); + const auto next = predict_overworld_press(maps_through(gates), current, facing); if (!next){ throw ParseException("story replay: native model rejects supplied route"); } @@ -201,10 +256,11 @@ std::vector ReplayExecutor::prepare_route(const StoryStep& step){ throw ParseException("story replay: supplied route exceeds action bound"); } OverworldPose current = m_pose; + Pokemon::GateState gates = m_gates; std::vector route; m_legs.clear(); for (const JsonValue& command : commands){ - m_legs.emplace_back(prepare_leg(command, current)); + m_legs.emplace_back(prepare_leg(command, current, gates)); route.push_back(m_legs.back().step); } const OverworldPose goal = authored_pose(Pokemon::pose_of(Pokemon::story_arg(step.args, "target")), m_data->maps); @@ -215,13 +271,15 @@ std::vector ReplayExecutor::prepare_route(const StoryStep& step){ } void ReplayExecutor::default_plan(const StoryStep& step){ const OverworldPose goal = authored_pose(Pokemon::pose_of(Pokemon::story_arg(step.args, "target")), m_data->maps); - const auto planned = plan_overworld_route(m_data->maps, m_pose.position, {goal.position, goal.facing}, story_route_costs(), m_pose.facing); + const auto planned = plan_overworld_route_gated( + m_data->maps, m_pose.position, {goal.position, goal.facing}, m_gates, m_rules, story_route_costs(), m_pose.facing + ); JsonObject plan; plan["policy"] = "native-story-route-costs"; plan["exact_python_leg_comparison"] = "not-comparable-different-planner-policies"; JsonArray legs; if (planned){ - const MapPosition actual = follow_overworld_route(m_data->maps, m_pose.position, *planned); + const MapPosition actual = follow_overworld_route(m_data->maps, m_pose.position, *planned, m_gates); if (!(actual == goal.position)){ throw ParseException("story replay: native default plan did not reach target"); } @@ -239,8 +297,11 @@ void ReplayExecutor::timed_plan(const StoryStep& step, const std::vectormaps, m_pose.position, m_pose.facing); - const RoutePlanning planning{.maps = &m_data->maps, .start = m_pose.position, + SimScript script; + script.gates = m_gates; + script.card_key_held = m_rules.card_key_held; + OverworldSim sim(m_data->maps, m_pose.position, m_pose.facing, script); + const RoutePlanning planning{.maps = &m_data->maps, .gates = m_gates, .start = m_pose.position, .label = step.name, .wall_check = WallCheck::SKIP}; const std::string failure = OverworldSimWalker(sim).run(route, planning); const auto goal = authored_pose(Pokemon::pose_of(Pokemon::story_arg(step.args, "target")), m_data->maps); @@ -259,11 +320,20 @@ void ReplayExecutor::timed_plan(const StoryStep& step, const std::vectormaps, m_pose, step.direction); + const auto next = predict_overworld_press(maps_through(m_gates), m_pose, step.direction); if (!next){ throw ParseException("story replay: supplied walk became blocked"); } @@ -277,14 +347,16 @@ StepOutcome ReplayExecutor::walk_leg(const RouteStep& step){ m_moves++; } m_pose.facing = step.facing_after; - const MapPosition followed = follow_overworld_route(m_data->maps, start.position, {step}); + const MapPosition followed = follow_overworld_route(m_data->maps, start.position, {step}, m_gates); if (!(followed == m_pose.position)){ throw ParseException("story replay: walker and independent native route replay disagree"); } m_basis = "model-prediction"; return StepOutcome{}; } -Pokemon::Outcome ReplayExecutor::replay_route(const StoryStep& step){ +Pokemon::Outcome ReplayExecutor::replay_route(const StoryStep& step, Pokemon::RunState& state){ + m_gates = state.gates; + m_rules = Pokemon::gate_rules_of(state); default_plan(step); const std::vector route = prepare_route(step); size_t moves = 0; @@ -309,10 +381,11 @@ Pokemon::Outcome ReplayExecutor::replay_route(const StoryStep& step){ if (signal() && !m_interrupted){ throw ParseException("story replay: physical encounter injection was not reached"); } + state.gates = m_gates; return Pokemon::outcome_ok(native_pose(m_pose)); } -Pokemon::Outcome ReplayExecutor::replay_step(const StoryStep& step){ - const auto next = predict_overworld_press(m_data->maps, m_pose, Pokemon::story_arg(step.args, "direction")); +Pokemon::Outcome ReplayExecutor::replay_step(const StoryStep& step, const Pokemon::RunState& state){ + const auto next = predict_overworld_press(maps_through(state.gates), m_pose, Pokemon::story_arg(step.args, "direction")); if (!next){ lose_pose("unknown-after-transition"); return Pokemon::outcome_failed("step_unresolved"); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay_Executor.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay_Executor.h index 0801680e0d..011fb4d9dc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay_Executor.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay_Executor.h @@ -3,10 +3,13 @@ */ #ifndef PokemonAutomation_PokemonFRLG_StoryReplay_Executor_H #define PokemonAutomation_PokemonFRLG_StoryReplay_Executor_H +#include #include #include +#include #include "Common/Cpp/Json/JsonArray.h" #include "Pokemon/AutoStory/Pokemon_StoryActions.h" +#include "Pokemon/Navigation/Pokemon_GatedTypes.h" #include "VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldRecovery.h" #include "PokemonFRLG_AutoStoryStepInterrupts.h" #include "PokemonFRLG_AutoStoryStepTable.h" @@ -46,14 +49,21 @@ class ReplayExecutor : public Pokemon::StoryStepExecutor{ // The replay's action for `id`: a ROUTE, STEP or MASH; every other // action is unsupported. Pokemon::StoryAction replay_action(StoryActionId id); - Pokemon::Outcome replay_route(const StoryStep& step); - Pokemon::Outcome replay_step(const StoryStep& step); + // A ROUTE or STEP reads the maps through the run's gates, and a + // route's open_gate and press_switch commands change them. + Pokemon::Outcome replay_route(const StoryStep& step, Pokemon::RunState& state); + Pokemon::Outcome replay_step(const StoryStep& step, const Pokemon::RunState& state); Pokemon::Outcome replay_scene(const StoryStep& step); const JsonObject* signal() const; const JsonObject& parameters(const StoryStep& step) const; - ReplayLeg prepare_leg(const JsonValue& command, OverworldPose& current) const; + // `gates`: the gates before the command, and after it. + ReplayLeg prepare_leg(const JsonValue& command, OverworldPose& current, Pokemon::GateState& gates) const; + ReplayLeg prepare_gate_leg(const JsonValue& command, const OverworldPose& current, Pokemon::GateState& gates) const; + // The maps as `gates` make them: a closed gate is a wall. + const std::vector& maps_through(const Pokemon::GateState& gates) const; std::vector prepare_route(const StoryStep& step); StepOutcome walk_leg(const RouteStep& step); + StepOutcome gate_leg(const RouteStep& step); void default_plan(const StoryStep& step); void timed_plan(const StoryStep& step, const std::vector& route); void lose_pose(std::string basis); @@ -66,6 +76,11 @@ class ReplayExecutor : public Pokemon::StoryStepExecutor{ const ReplayData* m_data; const JsonObject* m_scenario; OverworldPose m_pose; + // The gates open and switches on, and what the player may open, as + // the run state says at the start of each step. + Pokemon::GateState m_gates; + Pokemon::GateRules m_rules; + mutable std::optional>> m_resolved; bool m_known = true; std::string m_basis = "scripted-observation"; std::string m_active; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay_IO.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay_IO.cpp index 9105490f3c..e1c484e17d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay_IO.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_StoryReplay_IO.cpp @@ -350,15 +350,26 @@ ReplayScreen between_steps_screen(std::string_view kind){ } return screen; } +namespace{ +// The run flags a scenario starts with: strings. +void check_start_flags(const JsonValue& flags){ + for (const JsonValue& flag : flags.to_array_throw()){ + flag.to_string_throw(); + } +} +} // namespace void validate_scenario(const ReplayData& data, const JsonValue& scenario){ const JsonObject& root = scenario.to_object_throw(); for (const auto& [name, value] : root){ - if (name != "entry" && name != "signals" && name != "between_steps" && name != "check_actions"){ + if (name != "entry" && name != "signals" && name != "between_steps" && name != "check_actions" && name != "start_flags"){ throw ParseException("story replay: unknown scenario field"); } if (name == "check_actions"){ value.to_boolean_throw(); } + if (name == "start_flags"){ + check_start_flags(value); + } } const JsonObject& entry = fields(root.get_value_throw("entry"), {"basis", "screen", "pose"}); expect(entry, "basis", "scripted"); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-13.01.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-13.01.plan.json index da40ebbfcb..45918aefdc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-13.01.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-13.01.plan.json @@ -3,7 +3,7 @@ "game": "frlg", "checkpoint": { "id": "13.01", - "title": "Cinnabar to the Pokemon Mansion: 1F and 2F up to 3F's statue, press it", + "title": "Cinnabar to the Pokemon Mansion: 1F and 2F up to 3F's room of holes, the statue switch pressed on the way", "start": { "map": "CinnabarIsland_PokemonCenter_1F", "tiles": [ @@ -16,7 +16,7 @@ }, "events": [ { - "id": "mansion_3f", + "id": "mansion_holes", "kind": "route", "action": "run", "args": { @@ -24,60 +24,19 @@ "map": "PokemonMansion_3F", "tiles": [ [ - 8, - 3 + 19, + 13 ] ], - "facing": "east" + "facing": "south" } }, - "why": "out of Cinnabar's Center, up to the Mansion door (8, 3), 1F (8, 33) up its stairs (10, 13) to 2F (6, 14), through 2F's rooms to the stairs (9, 3), onto 3F's (8, 3); all in the switch's clear state, which is the map's" - }, - { - "id": "to_statue", - "kind": "legs", - "action": "taps", - "args": { - "legs": [ - { - "direction": "south", - "tiles": 3 - }, - { - "direction": "east", - "tiles": 4 - } - ] - }, - "why": "a tap a tile on 3F in the clear state: down to (8, 6) and east along row 6 to (12, 6), below the statue (12, 5)" - }, - { - "id": "face_statue", - "kind": "step", - "args": { - "direction": "north" - }, - "declared_after": { - "map": "PokemonMansion_3F", - "tiles": [ - [ - 12, - 6 - ] - ], - "facing": "north" - }, - "why": "turn north to the statue (12, 5)" - }, - { - "id": "press_3f_statue", - "kind": "talk", - "why": "face the statue (12, 5) and press A: \"Press the secret switch?\"" - }, - { - "id": "press_3f", - "kind": "answer", - "why": "YES: \"Who wouldn't?\"; the switch flag is set, 3F's (17-19,11-12) open, its (21,4-8) close" + "why": "out of Cinnabar's Center, up to the Mansion door (8, 3), 1F up its stairs, 2F's northern rooms to the stairs (9, 3), and on 3F through the barrier (17-19, 11-12) that a statue press opens: the route presses the statue the cheapest way and walks on to (19, 13), the room of holes", + "gates_after": { + "switches": { + "mansion": true + } + } } ] }, @@ -85,10 +44,8 @@ "menu": "full", "notes": { "checkpoint": [ - "Starts at Cinnabar's nurse, facing her, where 12.03 ends (Fly to Pallet Town and Surf down Route 21, as PokeGuy goes after Koga). Ends on 3F (12, 6) facing the statue it just pressed.", - "The Mansion's statue switches: one flag for all four floors. Switch model (pokefirered data/scripts/pokemon_mansion.inc, PokemonMansion_*F scripts.inc; one global flag, set on a press and applied on each floor's load; the pack's maps are the flag-clear state only). Assumed per floor (read from pokefirered; the overlay data on PokemonSimulation's maps/frlg-mansion-switches branch, seen 2026-11-12, has the same tiles open or closed per state): 1F set: (22-24,10-11), (27-29,25-26), (32-34,25-26) open, (31-33,18-19) closed. 2F set: (24-26,14-15), (10,30-32) open, (12,4-8) closed, (10,28-29) wall. 3F set: (17-19,11-12) open, (21,4-8) closed. B1F set: (12,10-12), (20-22,22-23) open, (33-35,20-21) and (16,28-30) closed. Clear = the map as it is.", - "13.01 walks only in the clear state; the press at its end sets the flag, and every row after walks the set state until a statue is pressed again (13.03 presses B1F's two).", - "Mansion trainers met on this walk: 1F Johnson wanders row 8, 2F Arnie (5, 23) and 3F Simon (6-8, 12-14) are off the route (the route takes 2F's northern rooms and 3F's (8, 3) arrival)." + "Starts at Cinnabar's nurse, facing her, where 12.03 ends (Fly to Pallet Town and Surf down Route 21, as PokeGuy goes after Koga). Ends on 3F (19, 13) facing south, in the room of holes, with the switch on.", + "The Mansion's statue switches: one flag for all four floors (pokefirered data/scripts/pokemon_mansion.inc, PokemonMansion_*F scripts.inc), a toggle each press flips and each floor applies on load. The pinned maps (PokemonSimulation 4b886bb) carry it as gates: barriers that open when the switch is on or off, and the statues that press it. A route plans the presses itself (PRESS_SWITCH: face the statue, A, Yes, B through the text) wherever a barrier is in the way, and the step's gates_after says the switch it leaves; a checkpoint that starts from a save says the switch in start_gates." ] } }, @@ -99,11 +56,11 @@ "map": "PokemonMansion_3F", "tiles": [ [ - 12, - 6 + 19, + 13 ] ], - "facing": "north" + "facing": "south" } } } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-13.02.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-13.02.plan.json index db95982209..4a211eb32f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-13.02.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-13.02.plan.json @@ -3,167 +3,53 @@ "game": "frlg", "checkpoint": { "id": "13.02", - "title": "Pokemon Mansion 3F through the switch's opening, the hole to 1F, 1F's stairs to B1F", + "title": "Pokemon Mansion 3F's hole to 1F, 1F's stairs to B1F", "start": { "map": "PokemonMansion_3F", "tiles": [ [ - 12, - 6 + 19, + 13 ] ], - "facing": "north" + "facing": "south" }, "events": [ { - "id": "to_barrier", - "kind": "legs", - "action": "taps", - "args": { - "legs": [ - { - "direction": "east", - "tiles": 7 - }, - { - "direction": "south", - "tiles": 4 - } - ] - }, - "why": "a tap a tile: east along row 6 to (19, 6), south to (19, 10), above 3F's opening (17-19, 11-12), set open by the press (the map has it closed)" - }, - { - "id": "into_opening_1", - "kind": "step", - "args": { - "direction": "south" - }, - "declared_after": { - "map": "PokemonMansion_3F", - "tiles": [ - [ - 19, - 11 - ] - ], - "facing": "south" - }, - "why": "a step onto (19, 11): the opening is open only in the set state, closed on the map" - }, - { - "id": "into_opening_2", - "kind": "step", - "args": { - "direction": "south" - }, - "declared_after": { - "map": "PokemonMansion_3F", - "tiles": [ - [ - 19, - 12 - ] - ], - "facing": "south" - }, - "why": "a step onto (19, 12), the opening's second row" - }, - { - "id": "through_opening", - "kind": "step", - "args": { - "direction": "south" - }, - "declared_after": { - "map": "PokemonMansion_3F", - "tiles": [ - [ - 19, - 13 - ] - ], - "facing": "south" - }, - "why": "a step through onto (19, 13), the room of holes" - }, - { - "id": "to_hole_edge", - "kind": "legs", - "action": "taps", - "args": { - "legs": [ - { - "direction": "south", - "tiles": 4 - } - ] - }, - "why": "a tap a tile down column 19 to (19, 17), above the hole row (18..20, 18); Braydon (22, 13) looks south along column 22, so x 19 is clear" - }, - { - "id": "down_the_hole", - "kind": "step", + "id": "to_ted_room", + "kind": "route", + "action": "run", "args": { - "direction": "south" - }, - "declared_after": { - "map": "PokemonMansion_1F", - "tiles": [ - [ - 20, - 22 - ] - ], - "facing": "south" + "target": { + "map": "PokemonMansion_1F", + "tiles": [ + [ + 17, + 23 + ] + ], + "facing": "south" + } }, - "why": "a step onto the hole (19, 18), which drops to 1F (20, 22) (3F map.json warp to 1F warp 8)" + "why": "south to the hole row (18..20, 18), which drops to 1F's room (19..20, 22), west along row 23 to the room's west wall, out of the sight line of Ted at (22, 24) facing west (4 tiles: 18..21 on row 24)" }, { - "id": "to_stairs", - "kind": "legs", - "action": "taps", + "id": "past_ted", + "kind": "route", + "action": "run", "args": { - "legs": [ - { - "direction": "south", - "tiles": 1 - }, - { - "direction": "west", - "tiles": 3 - }, - { - "direction": "south", - "tiles": 2 - }, - { - "direction": "east", - "tiles": 1 - }, - { - "direction": "south", - "tiles": 2 - }, - { - "direction": "east", - "tiles": 4 - }, - { - "direction": "south", - "tiles": 2 - }, - { - "direction": "east", - "tiles": 4 - }, - { - "direction": "north", - "tiles": 2 - } - ] + "target": { + "map": "PokemonMansion_1F", + "tiles": [ + [ + 17, + 25 + ] + ], + "facing": "south" + } }, - "why": "a tap a tile along 1F's southern rooms to (26, 27): west to column 17 (Ted (22, 24) looks west along row 24 and sees x 18-21 only), down to row 27, east on to (22, 27), (22, 29), (26, 29) and up to (26, 27), east of the stairs (25, 27), an arrow warp to B1F (34, 29)" + "why": "south down the west wall: (17, 24) is the one tile of row 24 past Ted's 4-tile line" }, { "id": "down_to_b1f", @@ -181,18 +67,26 @@ "facing": "west" } }, - "why": "west from (26, 27) onto the stairs (25, 27), an arrow warp, to B1F's (34, 29)" + "why": "south to the hole row (18..20, 18), which drops to 1F's east rooms (a one-way warp), through them to the stairs (25, 27), an arrow warp, to B1F's (34, 29); the switch stays on", + "gates_after": { + "switches": { + "mansion": true + } + } } - ] + ], + "start_gates": { + "switches": { + "mansion": true + } + } }, "execution": { "menu": "full", "notes": { "checkpoint": [ - "Starts where 13.01 ends, 3F (12, 6) facing the pressed statue. Ends on B1F (34, 29), the foot of 1F's stairs, in the set state.", - "Barriers: Switch model (pokefirered data/scripts/pokemon_mansion.inc, PokemonMansion_*F scripts.inc; one global flag, set on a press and applied on each floor's load; the pack's maps are the flag-clear state only). Assumed per floor (read from pokefirered; the overlay data on PokemonSimulation's maps/frlg-mansion-switches branch, seen 2026-11-12, has the same tiles open or closed per state): 1F set: (22-24,10-11), (27-29,25-26), (32-34,25-26) open, (31-33,18-19) closed. 2F set: (24-26,14-15), (10,30-32) open, (12,4-8) closed, (10,28-29) wall. 3F set: (17-19,11-12) open, (21,4-8) closed. B1F set: (12,10-12), (20-22,22-23) open, (33-35,20-21) and (16,28-30) closed. Clear = the map as it is.", - "This row walks 3F and 1F in the set state: 3F (19, 11-12) are open, so the three single steps are declared (the map has the barrier there); the holes (18..20, 18) drop to 1F (19, 22) and (20, 22), and 1F's east rooms (x 17-37, y 20-33) are reachable only by them (a wall at x 16 splits them from the west).", - "The hole is the way pokeguy goes (floor drop, then the staircase to the basement, before 1:19:56)." + "Starts where 13.01 ends, 3F (19, 13) facing south, the switch on (start_gates). Ends on B1F (34, 29), the foot of 1F's stairs. The hole is the way pokeguy goes (floor drop, then the staircase to the basement, before 1:19:56).", + "The Mansion's statue switches: one flag for all four floors (pokefirered data/scripts/pokemon_mansion.inc, PokemonMansion_*F scripts.inc), a toggle each press flips and each floor applies on load. The pinned maps (PokemonSimulation 4b886bb) carry it as gates: barriers that open when the switch is on or off, and the statues that press it. A route plans the presses itself (PRESS_SWITCH: face the statue, A, Yes, B through the text) wherever a barrier is in the way, and the step's gates_after says the switch it leaves; a checkpoint that starts from a save says the switch in start_gates." ] } }, @@ -211,4 +105,4 @@ } } } -} +} \ No newline at end of file diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-13.03.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-13.03.plan.json index bf9b0b8466..e73298c632 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-13.03.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-13.03.plan.json @@ -3,7 +3,7 @@ "game": "frlg", "checkpoint": { "id": "13.03", - "title": "Pokemon Mansion B1F: the statue by Lewis's room, the Elixir, TM14, the statue by the Elixir room", + "title": "Pokemon Mansion B1F: the Elixir and TM14", "start": { "map": "PokemonMansion_B1F", "tiles": [ @@ -16,176 +16,27 @@ }, "events": [ { - "id": "to_lewis_room", - "kind": "legs", - "action": "taps", + "id": "to_elixir", + "kind": "route", + "action": "run", "args": { - "legs": [ - { - "direction": "west", - "tiles": 7 - }, - { - "direction": "north", - "tiles": 9 - }, - { - "direction": "west", - "tiles": 5 - } - ] - }, - "why": "B1F arrives in the set state (the flag is set), which closes its north: a tap a tile west to (27, 29), up column 27 to (27, 20) and west along row 20 to (22, 20), above the opening (20-22, 22-23), set open" - }, - { - "id": "into_room_1", - "kind": "step", - "args": { - "direction": "south" - }, - "declared_after": { - "map": "PokemonMansion_B1F", - "tiles": [ - [ - 22, - 21 - ] - ], - "facing": "south" - }, - "why": "a step to (22, 21)" - }, - { - "id": "into_room_2", - "kind": "step", - "args": { - "direction": "south" - }, - "declared_after": { - "map": "PokemonMansion_B1F", - "tiles": [ - [ - 22, - 22 - ] - ], - "facing": "south" - }, - "why": "a step onto (22, 22): the opening (20-22, 22-23) is open only in the set state, closed on the map" - }, - { - "id": "into_room_3", - "kind": "step", - "args": { - "direction": "south" - }, - "declared_after": { - "map": "PokemonMansion_B1F", - "tiles": [ - [ - 22, - 23 - ] - ], - "facing": "south" - }, - "why": "a step onto (22, 23), the opening's second row" - }, - { - "id": "to_statue", - "kind": "legs", - "action": "taps", - "args": { - "legs": [ - { - "direction": "south", - "tiles": 1 - }, - { - "direction": "east", - "tiles": 1 - }, - { - "direction": "south", - "tiles": 6 - }, - { - "direction": "east", - "tiles": 1 - } - ] - }, - "why": "a tap a tile down to (22, 24), east to (23, 24) and down column 23 to (23, 30), then east to (24, 30), below the statue (24, 29); Burglar Lewis wanders (19-21, 24-26) with sight 1, and a battle is taken as it comes (pokeguy passed without one)" - }, - { - "id": "face_statue", - "kind": "step", - "args": { - "direction": "north" - }, - "declared_after": { - "map": "PokemonMansion_B1F", - "tiles": [ - [ - 24, - 30 - ] - ], - "facing": "north" - }, - "why": "turn north to the statue (24, 29)" - }, - { - "id": "press_b1f_south", - "kind": "talk", - "why": "press A: \"Press the secret switch?\"" - }, - { - "id": "press_south", - "kind": "answer", - "why": "YES: the flag clears, B1F's north opens again ((12, 10-12) and (20-22, 22-23) close, (33-35, 20-21) and (16, 28-30) open: the map)" - }, - { - "id": "south_to_north", - "kind": "legs", - "action": "taps", - "args": { - "legs": [ - { - "direction": "west", - "tiles": 9 - }, - { - "direction": "north", - "tiles": 10 - }, - { - "direction": "east", - "tiles": 14 - }, - { - "direction": "south", - "tiles": 2 - }, - { - "direction": "east", - "tiles": 4 - }, - { - "direction": "north", - "tiles": 16 - }, - { - "direction": "north", - "tiles": 1 - }, - { - "direction": "east", - "tiles": 1 - } - ] - }, - "why": "a tap a tile in the clear state, which is the map's: west to (15, 30), up column 15 to (15, 20), east along row 20 to (29, 20), down to (29, 22), east to (33, 22), up column 33 to (33, 5) (Ivan (34, 13) looks south along column 34 with sight 6, so not x 34), and east to (34, 5), facing (35, 5)" + "target": { + "map": "PokemonMansion_B1F", + "tiles": [ + [ + 34, + 5 + ] + ], + "facing": "east" + } + }, + "why": "B1F arrives with the switch on, which closes its north ((33-35, 20-21), (16, 28-30)): the route presses the statue it needs and walks up to (34, 5), beside the hidden ELIXIR on (35, 5)", + "gates_after": { + "switches": { + "mansion": false + } + } }, { "id": "hidden_elixir", @@ -194,55 +45,21 @@ }, { "id": "to_tm14", - "kind": "legs", - "action": "taps", + "kind": "route", + "action": "run", "args": { - "legs": [ - { - "direction": "south", - "tiles": 1 - }, - { - "direction": "west", - "tiles": 4 - }, - { - "direction": "south", - "tiles": 4 - }, - { - "direction": "west", - "tiles": 11 - }, - { - "direction": "north", - "tiles": 5 - }, - { - "direction": "east", - "tiles": 4 - } - ] + "target": { + "map": "PokemonMansion_B1F", + "tiles": [ + [ + 23, + 5 + ] + ], + "facing": "north" + } }, - "why": "a tap a tile back down: (34, 6), west to (30, 6), down to (30, 10), west along row 10 to (19, 10), up column 19 to (19, 5) and east to (23, 5), below TM14 (23, 4)" - }, - { - "id": "face_tm14", - "kind": "step", - "args": { - "direction": "north" - }, - "declared_after": { - "map": "PokemonMansion_B1F", - "tiles": [ - [ - 23, - 5 - ] - ], - "facing": "north" - }, - "why": "turn north to the ball" + "why": "back along the north rooms to (23, 5), below the ball (23, 4)" }, { "id": "tm14", @@ -260,76 +77,20 @@ "keep": ["tackle", "withdraw", "tail-whip", "water-gun", "bubble", "bite", "mega-kick", "water-pulse", "surf"] }, "why": "TM14 Blizzard over Dig (pokeguy, PokemonSimulation docs/progression/pokeguy-moves.md: Strength, Surf, Bite, Blizzard; the user approved the TM spend 2026-11-12), taught as soon as it is picked up; keep list: every move the lead can know but Dig, so the one other move (Dig) goes; fails if none or several are outside the list" - }, - { - "id": "to_north_statue", - "kind": "legs", - "action": "taps", - "args": { - "legs": [ - { - "direction": "west", - "tiles": 4 - }, - { - "direction": "south", - "tiles": 5 - }, - { - "direction": "east", - "tiles": 11 - }, - { - "direction": "north", - "tiles": 4 - }, - { - "direction": "west", - "tiles": 3 - } - ] - }, - "why": "a tap a tile back: west to (19, 5), down column 19 to (19, 10), east along row 10 to (30, 10), up to (30, 6) and west to (27, 6), below the statue (27, 5)" - }, - { - "id": "face_north_statue", - "kind": "step", - "args": { - "direction": "north" - }, - "declared_after": { - "map": "PokemonMansion_B1F", - "tiles": [ - [ - 27, - 6 - ] - ], - "facing": "north" - }, - "why": "turn north to the statue (27, 5)" - }, - { - "id": "press_b1f_north", - "kind": "talk", - "why": "press A: \"Press the secret switch?\" (pokeguy 1:20:09 presses the statue before the TM, the Elixir between)" - }, - { - "id": "press_north", - "kind": "answer", - "why": "YES: the flag is set; (12, 10-12) open, (33-35, 20-21) and (16, 28-30) close" } - ] + ], + "start_gates": { + "switches": { + "mansion": true + } + } }, "execution": { "menu": "full", "notes": { "checkpoint": [ - "Starts on B1F (34, 29) where 13.02 ends. Ends below the second statue (27, 5), at (27, 6), with the flag set: (12, 10-12) is the opening the walk to the SECRET KEY takes.", - "Barriers: Switch model (pokefirered data/scripts/pokemon_mansion.inc, PokemonMansion_*F scripts.inc; one global flag, set on a press and applied on each floor's load; the pack's maps are the flag-clear state only). Assumed per floor (read from pokefirered; the overlay data on PokemonSimulation's maps/frlg-mansion-switches branch, seen 2026-11-12, has the same tiles open or closed per state): 1F set: (22-24,10-11), (27-29,25-26), (32-34,25-26) open, (31-33,18-19) closed. 2F set: (24-26,14-15), (10,30-32) open, (12,4-8) closed, (10,28-29) wall. 3F set: (17-19,11-12) open, (21,4-8) closed. B1F set: (12,10-12), (20-22,22-23) open, (33-35,20-21) and (16,28-30) closed. Clear = the map as it is.", - "The two B1F statues are (24, 29) (press from (24, 30)) and (27, 5) (from (27, 6)). B1F is entered in the set state whichever way it was left, so the first press is a reset to clear: that opens the north, which the set state closes ((33-35, 20-21), (16, 28-30) are open in the clear state). The path to the Elixir and TM14 is the clear state, as the map is.", - "Open: Burglar Lewis (wandering (19-21, 24-26), sight 1: Growlithe, Ponyta Lv34) cannot be avoided in the room (its one way in, (22, 24), is beside his range; the sim meets him there and the AutoStory test lists to_statue as the one wanderer crossing it allows); the row relies on the normal battle code if he fights. Ivan (34, 13, looking south, sight 6) is passed on x 33. The Elixir is a hidden item: the walk faces it from (34, 5).", - "PokeGuy (1:19:56 to 1:20:21): basement statue, the Elixir 1:20:06, another statue 1:20:09, TM14 1:20:15." + "Starts on B1F (34, 29) where 13.02 ends, the switch on (start_gates). Ends below TM14's ball at (23, 5), with the switch as the route to the Elixir left it.", + "The Mansion's statue switches: one flag for all four floors (pokefirered data/scripts/pokemon_mansion.inc, PokemonMansion_*F scripts.inc), a toggle each press flips and each floor applies on load. The pinned maps (PokemonSimulation 4b886bb) carry it as gates: barriers that open when the switch is on or off, and the statues that press it. A route plans the presses itself (PRESS_SWITCH: face the statue, A, Yes, B through the text) wherever a barrier is in the way, and the step's gates_after says the switch it leaves; a checkpoint that starts from a save says the switch in start_gates." ] } }, @@ -340,8 +101,8 @@ "map": "PokemonMansion_B1F", "tiles": [ [ - 27, - 6 + 23, + 5 ] ], "facing": "north" diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-13.04.plan.json b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-13.04.plan.json index b33ae0ce44..cada9585b4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-13.04.plan.json +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/StoryData/frlg-13.04.plan.json @@ -8,110 +8,35 @@ "map": "PokemonMansion_B1F", "tiles": [ [ - 27, - 6 + 23, + 5 ] ], "facing": "north" }, "events": [ - { - "id": "to_opening", - "kind": "legs", - "action": "taps", - "args": { - "legs": [ - { - "direction": "east", - "tiles": 3 - }, - { - "direction": "south", - "tiles": 4 - }, - { - "direction": "west", - "tiles": 17 - } - ] - }, - "why": "a tap a tile in the set state: east to (30, 6), down to (30, 10) and west along row 10 to (13, 10), east of the opening (12, 10-12), set open (closed on the map)" - }, - { - "id": "into_opening", - "kind": "step", - "args": { - "direction": "west" - }, - "declared_after": { - "map": "PokemonMansion_B1F", - "tiles": [ - [ - 12, - 10 - ] - ], - "facing": "west" - }, - "why": "a step onto (12, 10): open only in the set state" - }, - { - "id": "through_opening", - "kind": "step", - "args": { - "direction": "west" - }, - "declared_after": { - "map": "PokemonMansion_B1F", - "tiles": [ - [ - 11, - 10 - ] - ], - "facing": "west" - }, - "why": "a step through onto (11, 10)" - }, { "id": "to_key", - "kind": "legs", - "action": "taps", + "kind": "route", + "action": "run", "args": { - "legs": [ - { - "direction": "west", - "tiles": 3 - }, - { - "direction": "north", - "tiles": 4 - }, - { - "direction": "west", - "tiles": 3 - } - ] + "target": { + "map": "PokemonMansion_B1F", + "tiles": [ + [ + 5, + 6 + ] + ], + "facing": "south" + } }, - "why": "a tap a tile: west to (8, 10), up column 8 to (8, 6) and west to (5, 6), above the SECRET KEY (5, 7)" - }, - { - "id": "face_key", - "kind": "step", - "args": { - "direction": "south" - }, - "declared_after": { - "map": "PokemonMansion_B1F", - "tiles": [ - [ - 5, - 6 - ] - ], - "facing": "south" - }, - "why": "turn south to the ball" + "why": "to (5, 6), above the SECRET KEY (5, 7): the opening (12, 10-12) is open only with the switch on, so the route presses the statue it passes", + "gates_after": { + "switches": { + "mansion": true + } + } }, { "id": "secret_key", @@ -137,15 +62,19 @@ }, "why": "out to the Mansion's door (pokeguy 1:20:24-36, his ESCAPE ROPE count 3 to 2); the player stands on (8, 4), where 14.01 starts" } - ] + ], + "start_gates": { + "switches": { + "mansion": false + } + } }, "execution": { "menu": "full", "notes": { "checkpoint": [ - "Starts below B1F's second statue, at (27, 6), where 13.03 ends, the flag set. Ends outside the Mansion door on Cinnabar (8, 4) facing south, where 14.01 starts.", - "Barriers: Switch model (pokefirered data/scripts/pokemon_mansion.inc, PokemonMansion_*F scripts.inc; one global flag, set on a press and applied on each floor's load; the pack's maps are the flag-clear state only). Assumed per floor (read from pokefirered; the overlay data on PokemonSimulation's maps/frlg-mansion-switches branch, seen 2026-11-12, has the same tiles open or closed per state): 1F set: (22-24,10-11), (27-29,25-26), (32-34,25-26) open, (31-33,18-19) closed. 2F set: (24-26,14-15), (10,30-32) open, (12,4-8) closed, (10,28-29) wall. 3F set: (17-19,11-12) open, (21,4-8) closed. B1F set: (12,10-12), (20-22,22-23) open, (33-35,20-21) and (16,28-30) closed. Clear = the map as it is.", - "The walk west along row 10 crosses (12, 10-12), which is closed on the pack's map and open in the set state: its two steps are declared because the pack's map has the barrier there.", + "Starts below TM14's ball, at (23, 5), where 13.03 ends. Ends outside the Mansion door on Cinnabar (8, 4) facing south, where 14.01 starts.", + "The Mansion's statue switches: one flag for all four floors (pokefirered data/scripts/pokemon_mansion.inc, PokemonMansion_*F scripts.inc), a toggle each press flips and each floor applies on load. The pinned maps (PokemonSimulation 4b886bb) carry it as gates: barriers that open when the switch is on or off, and the statues that press it. A route plans the presses itself (PRESS_SWITCH: face the statue, A, Yes, B through the text) wherever a barrier is in the way, and the step's gates_after says the switch it leaves; a checkpoint that starts from a save says the switch in start_gates.", "Not taken: the FULL RESTORE (2F (2, 29)) and TM22 (1F (6, 21)); pokeguy leaves by Escape Rope after the key (1:20:24-36)." ] } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp index 3144110055..1ab49e8344 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_EggRng.cpp @@ -188,7 +188,7 @@ EggRng::EggRng() , HELD_ADVANCES( "Held Advances:
The total number of RNG advances for your held target.", LockMode::LOCK_WHILE_RUNNING, - 10000, 500, 1000000000 // default, min + 10000, 700, 1000000000 // default, min ) , m_pickup_settings("Pickup Frame Settings") , PICKUP_SEED( diff --git a/SerialPrograms/Source/VideoGames/PokemonHome/Inference/PokemonHome_BoxNumberReader.cpp b/SerialPrograms/Source/VideoGames/PokemonHome/Inference/PokemonHome_BoxNumberReader.cpp new file mode 100644 index 0000000000..1456a253ed --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonHome/Inference/PokemonHome_BoxNumberReader.cpp @@ -0,0 +1,146 @@ +/* Pokemon Home Box Number Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Strings/StringTools.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/OCR/OCR_Routines.h" +#include "Tests/ImageUnitTest.h" +#include "PokemonHome_BoxNumberReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ +namespace{ + +const ImageFloatBox BOX_NUMBER(0.080, 0.718, 0.082, 0.039); + +} + +void BoxNumberReader::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, BOX_NUMBER); +} + +std::optional BoxNumberReader::read_box_number(const ImageViewRGB32& screen) const{ + const ImageViewRGB32 crop = extract_box_reference(screen, BOX_NUMBER); + if (!crop){ + return std::nullopt; + } + + constexpr size_t OCR_HEIGHT = 64; + const ImageRGB32 scaled = crop.scale_to(crop.width() * OCR_HEIGHT / crop.height(), OCR_HEIGHT); + const std::string text = StringTools::strip(OCR::ocr_read(Language::English, scaled)); + const char* end = text.data() + text.size(); + size_t box = 0; + const auto [slash, box_error] = std::from_chars(text.data(), end, box); + if (box_error != std::errc{} || slash == end || *slash != '/'){ + return std::nullopt; + } + + size_t capacity = 0; + const auto [capacity_end, capacity_error] = std::from_chars(slash + 1, end, capacity); + if (capacity_error != std::errc{} || capacity_end != end || box == 0 || box > capacity || capacity > 300){ + return std::nullopt; + } + return box; +} + +class Test_BoxNumberReader : public ImageUnitTest{ +public: + Test_BoxNumberReader(const std::string& image, std::optional expected) + : ImageUnitTest("PokemonHome::BoxNumberReader - " + image, {image}) + , m_expected(expected) + { + m_memory += PADDLE_OCR_SINGLE_LINE_MEMORY_ESTIMATE; + } + + virtual UnitTestResult run_on_images( + Logger& logger, CancellableScope& scope, + const std::vector& images + ) const override{ + const auto result = BoxNumberReader().read_box_number(images[0]); + if (result == m_expected){ + return true; + } + return "Expected box " + (m_expected ? std::to_string(*m_expected) : "none") + + ", read " + (result ? std::to_string(*result) : "none"); + } + +private: + std::optional m_expected; +}; + +void add_tests_BoxNumberReader(UnitTestDatabase& database){ + database.add("PokemonHome/BoxView/BoxView-1.png", 21); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_BoxSpaces_01.png", 2); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_BoxSpaces_02.png", 2); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_BoxSpaces_03.png", 2); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_BoxSpaces_04.png", 2); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_BoxSpaces_05.png", 2); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_BoxSpaces_06.png", 2); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_BoxSpaces_07.png", 3); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_BoxSpaces_08.png", 1); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_BoxSpaces_09.png", 4); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row0_Column0_01.png", 219); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row0_Column0_02.png", 219); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row2_Column0_01.png", 299); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row3_Column3_01.png", 219); + database.add("PokemonHome/BoxView/SelectionArrow_Multi_Grid_Row3_Column3_02.png", 219); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxName_01.png", 300); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxName_02.png", 300); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxSpaces_01.png", 4); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxSpaces_02.png", 4); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxSpaces_03.png", 4); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxSpaces_04.png", 3); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxSpaces_05.png", 3); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxSpaces_06.png", 8); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxSpaces_07.png", 8); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxSpaces_08.png", 8); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxSpaces_09.png", 10); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxSpaces_10.png", 10); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_BoxSpaces_11.png", 300); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_Grid_Row0_Column0_01.png", 21); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_Grid_Row0_Column0_02.png", 146); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_Grid_Row3_Column0_01.png", 300); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_Newest30_01.png", std::nullopt); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_Newest30_02.png", std::nullopt); + database.add("PokemonHome/BoxView/SelectionArrow_Normal_Newest30_03.png", std::nullopt); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxName_01.png", 103); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxName_02.png", 103); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxName_03.png", 103); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxName_04.png", 168); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxName_05.png", 168); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxSpaces_01.png", 15); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxSpaces_02.png", 15); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxSpaces_03.png", 15); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxSpaces_04.png", 24); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxSpaces_05.png", 24); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxSpaces_06.png", 28); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxSpaces_07.png", 28); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxSpaces_08.png", 87); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxSpaces_09.png", 87); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxSpaces_10.png", 87); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxSpaces_11.png", 100); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxSpaces_12.png", 101); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxSpaces_13.png", 101); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxSpaces_14.png", 101); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxSpaces_15.png", 103); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_BoxSpaces_16.png", 103); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_Grid_Row2_Column0_01.png", 168); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_Grid_Row2_Column0_02.png", 168); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_Grid_Row2_Column5_01.png", 182); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_Grid_Row2_Column5_02.png", 182); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_Newest30_01.png", std::nullopt); + database.add("PokemonHome/BoxView/SelectionArrow_Relocate_Newest30_02.png", std::nullopt); + database.add("PokemonHome/SummaryScreen/annihilape_Regular.png", std::nullopt); +} + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonHome/Inference/PokemonHome_BoxNumberReader.h b/SerialPrograms/Source/VideoGames/PokemonHome/Inference/PokemonHome_BoxNumberReader.h new file mode 100644 index 0000000000..95df2b6721 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonHome/Inference/PokemonHome_BoxNumberReader.h @@ -0,0 +1,39 @@ +/* Pokemon Home Box Number Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonHome_BoxNumberReader_H +#define PokemonAutomation_PokemonHome_BoxNumberReader_H + +#include +#include "Common/Cpp/Color.h" + +namespace PokemonAutomation{ + class ImageViewRGB32; + class UnitTestDatabase; + class VideoOverlaySet; +namespace NintendoSwitch{ +namespace PokemonHome{ + +class BoxNumberReader{ +public: + BoxNumberReader(Color color = COLOR_RED) : m_color(color) {} + + void make_overlays(VideoOverlaySet& items) const; + + // Read the one-based box number from the lower-left counter on the box screen. + // Returns no value if the counter is missing or unreadable. + std::optional read_box_number(const ImageViewRGB32& screen) const; + +private: + Color m_color; +}; + +void add_tests_BoxNumberReader(UnitTestDatabase& database); + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonHome/Inference/PokemonHome_StorageView.h b/SerialPrograms/Source/VideoGames/PokemonHome/Inference/PokemonHome_StorageView.h new file mode 100644 index 0000000000..b063530fba --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonHome/Inference/PokemonHome_StorageView.h @@ -0,0 +1,50 @@ +/* Pokemon Home Storage View + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonHome_StorageView_H +#define PokemonAutomation_PokemonHome_StorageView_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + +// These locations are the same for both Box View and Page View. +inline const ImageFloatBox STORAGE_HEADER_STRIP(0.17, 0.091, 0.16, 0.004); +inline const ImageFloatBox STORAGE_PLUS_BUTTON(0.100, 0.940, 0.107, 0.057); + +enum class StorageViewHeader{ + Unknown, + BoxView, + PageView, +}; + +inline StorageViewHeader classify_storage_header(const ImageViewRGB32& screen){ + const ImageViewRGB32 header = extract_box_reference(screen, STORAGE_HEADER_STRIP); + if (!header){ + return StorageViewHeader::Unknown; + } + const FloatPixel color = image_average(header); + // Both headers are teal. Page View has a stronger blue channel. + if (color.g <= color.r + 80){ + return StorageViewHeader::Unknown; + } + if (color.b > color.g + 15){ + return StorageViewHeader::PageView; + } + if (color.b < color.g + 10){ + return StorageViewHeader::BoxView; + } + return StorageViewHeader::Unknown; +} + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonHome/PokemonHome_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonHome/PokemonHome_Tests.cpp index aadbdbed4b..0f5ea22ebe 100644 --- a/SerialPrograms/Source/VideoGames/PokemonHome/PokemonHome_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonHome/PokemonHome_Tests.cpp @@ -8,6 +8,7 @@ #include "Inference/PokemonHome_AlphaDetector.h" #include "Inference/PokemonHome_BallReader.h" #include "Inference/PokemonHome_BoxGenderDetector.h" +#include "Inference/PokemonHome_BoxNumberReader.h" #include "Inference/PokemonHome_BoxViewDetector.h" #include "Inference/PokemonHome_ButtonDetector.h" #include "Inference/PokemonHome_GigantamaxDetector.h" @@ -29,6 +30,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AlphaDetector(database); add_tests_BallReader(database); add_tests_BoxGenderDetector(database); + add_tests_BoxNumberReader(database); add_tests_BoxViewDetector(database); add_tests_ButtonDetector(database); add_tests_GigantamaxDetector(database); diff --git a/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxNavigation.cpp b/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxNavigation.cpp index 6ef0b2bd05..83fd703709 100644 --- a/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxNavigation.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxNavigation.cpp @@ -15,12 +15,14 @@ #include "CommonFramework/Tools/ErrorDumper.h" #include "CommonFramework/VideoPipeline/VideoFeed.h" #include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Async/InferenceRoutines.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "Pokemon/Resources/Pokemon_PokemonSlugs.h" #include "Pokemon/Inference/Pokemon_TypeReader.h" -#include "VideoGames/PokemonHome/Inference/PokemonHome_BallReader.h" #include "VideoGames/PokemonHome/Inference/PokemonHome_AlphaDetector.h" +#include "VideoGames/PokemonHome/Inference/PokemonHome_BallReader.h" #include "VideoGames/PokemonHome/Inference/PokemonHome_BoxGenderDetector.h" +#include "VideoGames/PokemonHome/Inference/PokemonHome_BoxViewDetector.h" #include "VideoGames/PokemonHome/Inference/PokemonHome_GigantamaxDetector.h" #include "VideoGames/PokemonHome/Inference/PokemonHome_OriginMarkReader.h" #include "VideoGames/PokemonHome/Inference/PokemonHome_ShinyDetector.h" @@ -322,46 +324,59 @@ void print_boxes_data(const std::vector>& bo env.console.log(ss.str()); } -void exit_menus(SingleSwitchProgramEnvironment& env, ProControllerContext& context, std::chrono::milliseconds video_delay){ - VideoSnapshot screen = env.console.video().snapshot(); - VideoOverlaySet video_overlay_set(env.console); +void exit_menus(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + BoxViewWatcher box_watcher(&env.console.overlay()); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + for (size_t i = 0; i < 20; i++){ + pbf_press_button(context, BUTTON_B, 80ms, 250ms); + context.wait_for_all_requests(); + } + }, + { box_watcher } + ); - ImageFloatBox select_check(0.495, 0.0045, 0.01, 0.005); // square color to check which mode is active - FloatPixel image_value = image_stats(extract_box_reference(screen, select_check)).average; + if (ret != 0){ + dump_image(env.console, ProgramInfo(), "SelectSquare", env.console.video().snapshot()); + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, "HomeBoxNavigation_ExitMenus(): could not find box view after 20 attempts", env.console + ); + } - env.console.log("Color detected from the select square: " + image_value.to_string()); + // Page view can be detected as Box view. Extra B to ensure we are in box view and not page view. + pbf_press_button(context, BUTTON_B, 80ms, 250ms); + context.wait_for(250ms); + context.wait_for_all_requests(); +} - //if the correct color is not detected, getting out of every possible menu to make sure the program work no matter where you start it in your pokemon home - video_overlay_set.add(COLOR_BLUE, select_check); - if (image_value.r <= image_value.g + image_value.b){ - for (int var = 0; var < 5; ++var){ - pbf_press_button(context, BUTTON_B, 80ms, video_delay + 80ms); - } - context.wait_for_all_requests(); - context.wait_for(std::chrono::milliseconds(video_delay)); - screen = env.console.video().snapshot(); - image_value = image_stats(extract_box_reference(screen, select_check)).average; - env.console.log("Color detected from the select square: " + image_value.to_string()); - if (image_value.r <= image_value.g + image_value.b){ - for (int i = 0; i < 2; ++i){ - pbf_press_button(context, BUTTON_ZR, 80ms, video_delay + 240ms); //additional delay because this animation is slower than the rest - context.wait_for_all_requests(); - screen = env.console.video().snapshot(); - image_value = image_stats(extract_box_reference(screen, select_check)).average; - env.console.log("Color detected from the select square: " + image_value.to_string()); - if (image_value.r > image_value.g + image_value.b){ - break; - } - else if (i == 1){ - dump_image(env.console, ProgramInfo(), "SelectSquare", screen); - env.console.log("ERROR: Could not find correct color mode please check color logs and timings\n", COLOR_RED); - return; - } - } +void switch_selection_mode(SingleSwitchProgramEnvironment& env, ProControllerContext& context, BoxSelectionMode desired_mode){ + context.wait_for_all_requests(); + const SelectionArrowDetector detector; + auto selection = detector.detect(env.console.video().snapshot()); + if (!selection){ + exit_menus(env, context); + selection = detector.detect(env.console.video().snapshot()); + if (!selection){ + dump_image(env.console, ProgramInfo(), "SelectionArrow", env.console.video().snapshot()); + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + "HomeBoxNavigation_SwitchSelectionMode(): could not find selection arrow after exiting menus", + env.console + ); } } + if (selection->mode == desired_mode){ + return; + } - video_overlay_set.clear(); + // ZL cycles Normal -> Relocate -> Multi -> Normal; ZR goes in reverse. + const bool select_left = + (selection->mode == BoxSelectionMode::Normal && desired_mode == BoxSelectionMode::Relocate) + || (selection->mode == BoxSelectionMode::Relocate && desired_mode == BoxSelectionMode::Multi) + || (selection->mode == BoxSelectionMode::Multi && desired_mode == BoxSelectionMode::Normal); + pbf_press_button(context, select_left ? BUTTON_ZL : BUTTON_ZR, 80ms, 300ms); + context.wait_for_all_requests(); } } diff --git a/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxNavigation.h b/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxNavigation.h index 5793e41e45..faf71e6a5a 100644 --- a/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxNavigation.h +++ b/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxNavigation.h @@ -8,7 +8,6 @@ #define PokemonAutomation_PokemonHome_BoxNavigation_H #include -#include #include #include #include "Common/Cpp/Time.h" @@ -16,6 +15,7 @@ #include "Pokemon/Pokemon_BoxCursor.h" #include "Pokemon/Pokemon_CollectedPokemonInfo.h" #include "Pokemon/Options/Pokemon_BoxSortingTable.h" +#include "VideoGames/PokemonHome/Inference/PokemonHome_SelectionArrowDetector.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -61,7 +61,10 @@ void print_boxes_data( SingleSwitchProgramEnvironment& env ); -void exit_menus(SingleSwitchProgramEnvironment& env, ProControllerContext& context, std::chrono::milliseconds video_delay); +// Backout of any menus to the box view. +void exit_menus(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +void switch_selection_mode(SingleSwitchProgramEnvironment& env, ProControllerContext& context, BoxSelectionMode desired_mode); } } diff --git a/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorter.cpp b/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorter.cpp index 2deea9ade5..bc2b13bc1c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorter.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorter.cpp @@ -222,8 +222,9 @@ void BoxSorter::program(SingleSwitchProgramEnvironment& env, ProControllerContex BoxCursor dest_cursor; BoxCursor nav_cursor = {0, 0, 0}; - exit_menus(env, context, VIDEO_DELAY.get()); - + exit_menus(env, context); + switch_selection_mode(env, context, BoxSelectionMode::Normal); + BoxViewWatcher box_view_watcher(&env.console.overlay()); SummaryScreenWatcher summary_screen_watcher(&env.console.overlay()); diff --git a/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex.cpp b/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex.cpp index 42d6f2fc02..1e8b714633 100644 --- a/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonHome/Programs/PokemonHome_BoxSorterLivingDex.cpp @@ -552,7 +552,8 @@ void BoxSorterLivingDex::program(SingleSwitchProgramEnvironment& env, ProControl ); } - exit_menus(env, context, VIDEO_DELAY.get()); + exit_menus(env, context); + switch_selection_mode(env, context, BoxSelectionMode::Normal); nav_cursor = populate_box_data(env, context, sort_preferences, living_dex_boxes_data, living_dex_box_count, nav_cursor, OT_NAME_LANGUAGE); diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index c40ce8c9c9..7c832aa506 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1468,12 +1468,23 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Inference/Pokemon_TrainPokemonOCR.h Source/Pokemon/Inference/Pokemon_TypeReader.cpp Source/Pokemon/Inference/Pokemon_TypeReader.h + Source/Pokemon/Navigation/Pokemon_ConnectedMaps.cpp + Source/Pokemon/Navigation/Pokemon_ConnectedMaps.h + Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.cpp + Source/Pokemon/Navigation/Pokemon_ConnectedMaps_Tests.h + Source/Pokemon/Navigation/Pokemon_GatedPlanner.h + Source/Pokemon/Navigation/Pokemon_GatedTypes.h + Source/Pokemon/Navigation/Pokemon_GateState.cpp + Source/Pokemon/Navigation/Pokemon_GateState.h + Source/Pokemon/Navigation/Pokemon_GateTiles.cpp + Source/Pokemon/Navigation/Pokemon_GateTiles.h Source/Pokemon/Navigation/Pokemon_Direction.cpp Source/Pokemon/Navigation/Pokemon_Direction.h Source/Pokemon/Navigation/Pokemon_Grid.cpp Source/Pokemon/Navigation/Pokemon_Grid.h Source/Pokemon/Navigation/Pokemon_LegTypes.h Source/Pokemon/Navigation/Pokemon_MapFeatures.h + Source/Pokemon/Navigation/Pokemon_MapGates.h Source/Pokemon/Navigation/Pokemon_MapTiles.h Source/Pokemon/Navigation/Pokemon_RouteLogLegs.h Source/Pokemon/Navigation/Pokemon_RouteLogTypes.h @@ -1491,6 +1502,9 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_MapData.h Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp Source/Pokemon/Navigation/Pokemon_MapData_Tests.h + Source/Pokemon/Navigation/Pokemon_MoveMechanics.h + Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.cpp + Source/Pokemon/Navigation/Pokemon_MoveMechanics_Tests.h Source/Pokemon/Navigation/Pokemon_RuntimeMap.cpp Source/Pokemon/Navigation/Pokemon_RuntimeMap.h Source/Pokemon/Navigation/Pokemon_RuntimeMap_Tests.cpp @@ -1500,6 +1514,14 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/Navigation/Pokemon_RouteLog.h Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.cpp Source/Pokemon/Navigation/Pokemon_RouteLog_Tests.h + Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.cpp + Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults.h + Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.cpp + Source/Pokemon/Navigation/Simulation/Pokemon_SimFaults_Tests.h + Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.cpp + Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden.h + Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.cpp + Source/Pokemon/Navigation/Simulation/Pokemon_SimGolden_Tests.h Source/Pokemon/Options/Pokemon_BoxSortingTable.cpp Source/Pokemon/Options/Pokemon_BoxSortingTable.h Source/Pokemon/Options/Pokemon_EncounterBotOptions.h @@ -1529,6 +1551,8 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson.h Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.h + Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.cpp + Source/Pokemon/AutoStory/Engine/Pokemon_ScreenObservation.h Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.cpp Source/Pokemon/AutoStory/Engine/Pokemon_StoryActionRegistry.h Source/Pokemon/AutoStory/Engine/Pokemon_StoryBackend.cpp @@ -1622,6 +1646,7 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.h Source/Pokemon/AutoStory/Pokemon_TilePose.cpp Source/Pokemon/AutoStory/Pokemon_TilePose.h + Source/Pokemon/AutoStory/Pokemon_TestExpect.h Source/Pokemon/AutoStory/Pokemon_Transitions.cpp Source/Pokemon/AutoStory/Pokemon_Transitions.h Source/Pokemon/AutoStory/Pokemon_Transitions_Tests.cpp @@ -1638,6 +1663,7 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.cpp Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckLevel.h Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpoint.h + Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointGates.cpp Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.cpp Source/Pokemon/AutoStory/Types/Pokemon_StoryCheckpointMetadata.h Source/Pokemon/AutoStory/Types/Pokemon_StoryPostconditions.h @@ -1974,6 +2000,10 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldBikeTaps.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldBikeTaps.h Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldBike_Tests.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGatedRoute.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGateMaps_Tests.cpp + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGateMaps_Tests.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldGates_Tests.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldLateBattle.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldLateBattle.h Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldLateBattle_Tests.cpp @@ -2021,6 +2051,7 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalk_Tests.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWarpFade_Tests.cpp Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkedTiles.h + Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkGates.h Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkMoves.h Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkOptions.h Source/VideoGames/PokemonFRLG/Overworld/PokemonFRLG_OverworldWalkTimes.h @@ -2069,6 +2100,8 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryCinnabarGym_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySilph_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows16_Tests.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGates_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryGates_Tests.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryMansion_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRows13_Tests.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryUnauthoredStarts_Tests.h @@ -2402,6 +2435,8 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonHome/Inference/PokemonHome_BallReader.h Source/VideoGames/PokemonHome/Inference/PokemonHome_BoxGenderDetector.cpp Source/VideoGames/PokemonHome/Inference/PokemonHome_BoxGenderDetector.h + Source/VideoGames/PokemonHome/Inference/PokemonHome_BoxNumberReader.cpp + Source/VideoGames/PokemonHome/Inference/PokemonHome_BoxNumberReader.h Source/VideoGames/PokemonHome/Inference/PokemonHome_BoxViewDetector.cpp Source/VideoGames/PokemonHome/Inference/PokemonHome_BoxViewDetector.h Source/VideoGames/PokemonHome/Inference/PokemonHome_ButtonDetector.cpp @@ -2414,6 +2449,7 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonHome/Inference/PokemonHome_SelectionArrowDetector.h Source/VideoGames/PokemonHome/Inference/PokemonHome_ShinyDetector.cpp Source/VideoGames/PokemonHome/Inference/PokemonHome_ShinyDetector.h + Source/VideoGames/PokemonHome/Inference/PokemonHome_StorageView.h Source/VideoGames/PokemonHome/Inference/PokemonHome_SummaryReader.cpp Source/VideoGames/PokemonHome/Inference/PokemonHome_SummaryReader.h Source/VideoGames/PokemonHome/Inference/PokemonHome_SummaryScreenDetector.cpp diff --git a/devtools/maps/map-resources.lock.json b/devtools/maps/map-resources.lock.json index 24f10bf535..6f55191d46 100644 --- a/devtools/maps/map-resources.lock.json +++ b/devtools/maps/map-resources.lock.json @@ -3,9 +3,9 @@ "repository": "dayfine/PokemonSimulation", "games": { "frlg": { - "revision": "0c46df1e5e9abe79016f2c8610aeb784835768fe", + "revision": "1cacf81b2377ec1413317d905ad5415f6fe8dad5", "manifest_path": "data/maps/runtime-manifest.json", - "manifest_sha256": "70f1947e4b2474319e87959480abad04f130834d235ef7b8a2f24a0256314c14" + "manifest_sha256": "0fbd71b8f985746c673ef530fa69fea17b7c6b808156fc7d7dbdadade7e7dd9a" } } } diff --git a/devtools/runtime-map-tests/README.md b/devtools/runtime-map-tests/README.md index 18235bb554..e1ae46d4b9 100644 --- a/devtools/runtime-map-tests/README.md +++ b/devtools/runtime-map-tests/README.md @@ -30,18 +30,21 @@ cmake --build /path/to/build -j4 ctest --test-dir /path/to/build --output-on-failure ``` -The focused target also runs all eight existing registered MapData cases, -including their legacy diagnostics and embedded map assets. The 26 new cases are registered in the application's native test +The focused target also runs the existing registered MapData cases, +including their legacy diagnostics and embedded map assets. The runtime-map cases are registered in the application's native test database. They cover v1 compatibility, mixed/malformed versions and pairs, inclusive wander bounds, object groups, interaction-vs-item rejection, coordinate events and complete normalized JSON parity, including unknown metadata. -For real data, prepare a clean PokemonSimulation checkout at -`40717c7c809c415c751fd7a348dfc1895f7ec3d7` (merged #53), then run: +For real data, prepare a clean PokemonSimulation checkout at the revision +that `.github/workflows/runtime-map-reader.yml` pins (CI passes it as +`--publisher-revision`; the script refuses any other), then run: ```sh python3 devtools/runtime-map-tests/prepare_parity.py \ - --publisher /path/to/PokemonSimulation --out /tmp/runtime-map-pairs.json + --publisher /path/to/PokemonSimulation \ + --publisher-revision \ + --out /tmp/runtime-map-pairs.json /path/to/build/RuntimeMapTests /tmp/runtime-map-pairs.json ``` diff --git a/devtools/runtime-map-tests/prepare_parity.py b/devtools/runtime-map-tests/prepare_parity.py index fb1cdea9ef..80519e81ee 100644 --- a/devtools/runtime-map-tests/prepare_parity.py +++ b/devtools/runtime-map-tests/prepare_parity.py @@ -16,7 +16,7 @@ import sys -PUBLISHER_REVISION = '40717c7c809c415c751fd7a348dfc1895f7ec3d7' +PUBLISHER_REVISION = '906956e94fc912ae9adb0e44845da780f3bc7e4c' def main(): diff --git a/devtools/story-data-tests/CMakeLists.txt b/devtools/story-data-tests/CMakeLists.txt index c8fe360274..9a46137153 100644 --- a/devtools/story-data-tests/CMakeLists.txt +++ b/devtools/story-data-tests/CMakeLists.txt @@ -14,6 +14,8 @@ add_executable(StoryDataTests "${STORY}/Types/Pokemon_StoryActionArg.cpp" "${STORY}/Types/Pokemon_StoryActionSpec.cpp" "${STORY}/Types/Pokemon_StoryCheckpointMetadata.cpp" + "${STORY}/Types/Pokemon_StoryCheckpointGates.cpp" + "${ROOT}/SerialPrograms/Source/Pokemon/Navigation/Pokemon_GateState.cpp" "${ROOT}/SerialPrograms/Source/Pokemon/Navigation/Pokemon_Grid.cpp" "${ROOT}/Common/Cpp/Exceptions.cpp" "${ROOT}/Common/Cpp/Json/JsonValue.cpp"