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_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Data/Pokemon_StoryStepJson_Tests.cpp index 0433258cbb..69f213ad13 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){ @@ -201,7 +201,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_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/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..c6b1ec19a9 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_AutoStory_Tests.h @@ -28,6 +28,7 @@ #include "Pokemon_StoryEvents_Tests.h" #include "Pokemon_StoryInterrupts_Tests.h" #include "Pokemon_StoryLog_Tests.h" +#include "Pokemon_StoryRngHandoff_Tests.h" #include "Pokemon_StorySavePolicy_Tests.h" #include "Pokemon_StorySegments_Tests.h" #include "Pokemon_StoryStepExecutor_Tests.h" @@ -44,6 +45,7 @@ inline void add_tests_AutoStory(UnitTestDatabase& database){ add_tests_StoryRun(database); add_tests_AutoStoryStats(database); add_tests_StoryLog(database); + add_tests_StoryRngHandoff(database); add_tests_StoryRangeOptions(database); add_tests_StoryEvents(database); add_tests_StorySegments(database); 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_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_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_StoryRngHandoff.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp new file mode 100644 index 0000000000..1890518dd4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp @@ -0,0 +1,68 @@ +/* Story RNG Handoff + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryRngHandoff.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +RngHandoffMode rng_handoff_mode(const RngHandoffOptions& options){ + if (options.run){ + return RngHandoffMode::RUN; + } + return options.stop ? RngHandoffMode::STOP : RngHandoffMode::OFF; +} + +bool RngHandoffResult::succeeded() const{ + return failure.empty(); +} + +std::optional run_rng_handoff_or_user_turn( + Logger& logger, const std::string& program, const RngHandoffCall& call +){ + const RngHandoffResult result = call(); + if (!result.succeeded()){ + throw_and_log(logger, ErrorReportMode::SEND_ERROR_REPORT, result.failure); + } + if (!result.user_turn.empty()){ + logger.log(program + " stopped for the user: " + result.user_turn, COLOR_BLUE); + return result.user_turn; + } + logger.log(program + " succeeded: " + result.summary, COLOR_BLUE); + return std::nullopt; +} + +Outcome run_rng_handoff(Logger& logger, const std::string& program, const RngHandoffCall& call){ + const std::optional user_turn = run_rng_handoff_or_user_turn(logger, program, call); + if (user_turn){ + // A story action has no stop to give the user's turn to. + throw_and_log(logger, ErrorReportMode::SEND_ERROR_REPORT, *user_turn); + } + return outcome_ok(); +} + +std::string report_rng_handoff_stop( + Logger& logger, const std::string& message, const std::vector& lines, + const std::function& show +){ + std::string text = message; + logger.log(message, COLOR_BLUE); + show(message); + for (const std::string& line : lines){ + logger.log(line, COLOR_BLUE); + show(line); + text += "\n" + line; + } + return text; +} + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h new file mode 100644 index 0000000000..ddc21f3286 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h @@ -0,0 +1,96 @@ +/* Story RNG Handoff + * + * From: https://github.com/PokemonAutomation/ + * + * The part of an AutoStory run that hands the game to an RNG program (BDSP + * Starter RNG, FRLG Starter RNG and Gift RNG) and takes it back. A game + * supplies the program's call; the contract around it is shared: + * + * - A handoff row has a mode: OFF (the story plays it by hand), STOP (the run + * ends after the row's handoff save, for the user to run the RNG program) + * or RUN (the story calls the RNG program itself and continues). + * - The call ends in an RngHandoffResult: no failure means the game stands + * where the story goes on; a failure is the reason it does not. A game + * whose program can also end where the user takes over (FRLG: the target + * hit but not shiny, the attempts spent) gives that end a user_turn, which + * is a stop and not an error. What the story runs after a continuation + * (FRLG: the rows after a shiny) is the game's, built from the call. + * - A failed RUN stops the program. It never retries the row: the program's + * own reset loop is the retry, and a reload of the save would lose a + * shiny it caught. + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRngHandoff_H +#define PokemonAutomation_Pokemon_StoryRngHandoff_H + +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Pokemon_StoryOutcome.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// What a handoff row does with its RNG program. +enum class RngHandoffMode{ + OFF, + STOP, + RUN, +}; + +// A handoff's two options. +struct RngHandoffOptions{ + bool stop = false; + bool run = false; +}; + +// The mode for a handoff's two options: RUN takes precedence over STOP. +RngHandoffMode rng_handoff_mode(const RngHandoffOptions& options); + + +// How an RNG program's call ended, as the story needs it. +struct RngHandoffResult{ + // Empty: the game stands where the story goes on. Otherwise why it does not. + std::string failure; + // What a success did, for the log: the resets used, the target hit. + std::string summary; + // Not empty (and no failure): the program ended where the user takes + // over, with this for them. The run stops without an error report. + std::string user_turn; + + bool succeeded() const; +}; + +// The call a handoff row runs in place of its steps. +using RngHandoffCall = std::function; + +// Runs `call` for the RNG program `program` ("Starter RNG"). A success is +// logged with its summary and returned as an ok Outcome. A failure throws +// OperationFailedException with an error report, so that no row retry +// reruns the program's reset loop. +Outcome run_rng_handoff(Logger& logger, const std::string& program, const RngHandoffCall& call); + +// As run_rng_handoff(), for a program whose call may end in the user's turn: +// returns that message, which is logged, and the run stops there. Returns +// nothing when the game stands where the story goes on. +std::optional run_rng_handoff_or_user_turn( + Logger& logger, const std::string& program, const RngHandoffCall& call +); + +// A run that stops for the user to run an RNG program, as the game's program +// reports it: `message` (what to do) and then `lines` (the RNG plan's +// attempts), each logged and passed to `show` (the overlay's log). Returns +// the whole text, one line each, for the program's finish notification. +std::string report_rng_handoff_stop( + Logger& logger, const std::string& message, const std::vector& lines, + const std::function& show +); + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp new file mode 100644 index 0000000000..a5733d5bce --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp @@ -0,0 +1,189 @@ +/* Story RNG Handoff Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "Pokemon_StoryRngHandoff.h" +#include "Pokemon_StoryRngHandoff_Tests.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +struct RngHandoffInput{ + std::string_view name; + UnitTestResult (*body)(Logger& logger); +}; + +struct RngHandoffExpectation{ + std::string_view description; +}; + +struct RngHandoffTestCase{ + RngHandoffInput input; + RngHandoffExpectation expectation; +}; + +class Test_RngHandoff : public UnitTest{ +public: + explicit Test_RngHandoff(RngHandoffTestCase scenario) + : UnitTest("Pokemon::StoryRngHandoff - " + std::string(scenario.input.name)) + , m_scenario(scenario) + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + return m_scenario.input.body(logger); + } + +private: + RngHandoffTestCase m_scenario; +}; + +// rng_handoff_mode()'s two options. +UnitTestResult test_mode(Logger&){ + struct Case{ + RngHandoffOptions options; + RngHandoffMode expected; + }; + const Case cases[] = { + {.options = {.stop = false, .run = false}, .expected = RngHandoffMode::OFF}, + {.options = {.stop = true, .run = false}, .expected = RngHandoffMode::STOP}, + {.options = {.stop = false, .run = true}, .expected = RngHandoffMode::RUN}, + {.options = {.stop = true, .run = true}, .expected = RngHandoffMode::RUN}, + }; + for (const Case& item : cases){ + if (rng_handoff_mode(item.options) != item.expected){ + return std::format("stop={}, run={}: wrong mode", item.options.stop, item.options.run); + } + } + return true; +} + +// A success is an ok Outcome and calls the program once. +UnitTestResult test_success(Logger& logger){ + int calls = 0; + const Outcome outcome = run_rng_handoff(logger, "Test RNG", [&]{ + calls++; + return RngHandoffResult{.summary = "2 resets"}; + }); + if (!outcome.succeeded()){ + return "Expected an ok outcome"; + } + if (calls != 1){ + return std::format("Expected 1 call, got {}", calls); + } + return true; +} + +// A failure throws, once: nothing reruns the program. +UnitTestResult test_failure(Logger& logger){ + int calls = 0; + try{ + run_rng_handoff(logger, "Test RNG", [&]{ + calls++; + return RngHandoffResult{.failure = "out of resets"}; + }); + }catch (OperationFailedException&){ + if (calls != 1){ + return std::format("Expected 1 call, got {}", calls); + } + return true; + } + return "Expected OperationFailedException"; +} + +// The user's turn is returned, not thrown, once; a success has none; a +// failure throws even with one. +UnitTestResult test_user_turn(Logger& logger){ + int calls = 0; + const std::optional turn = run_rng_handoff_or_user_turn(logger, "Test RNG", [&]{ + calls++; + return RngHandoffResult{.user_turn = "save by hand"}; + }); + if (!turn || *turn != "save by hand"){ + return "Expected the user's turn"; + } + if (calls != 1){ + return std::format("Expected 1 call, got {}", calls); + } + const std::optional none = run_rng_handoff_or_user_turn(logger, "Test RNG", []{ + return RngHandoffResult{.summary = "shiny"}; + }); + if (none){ + return "A success has no user's turn"; + } + try{ + run_rng_handoff_or_user_turn(logger, "Test RNG", []{ + return RngHandoffResult{.failure = "out of resets", .user_turn = "ignored"}; + }); + }catch (OperationFailedException&){ + return true; + } + return "A failure must throw even with a user's turn"; +} + +// A stop reports its message, then each line, to the log and to `show`; +// the notification text is one line each. +UnitTestResult test_stop_report(Logger& logger){ + std::vector shown; + const auto show = [&](const std::string& line){ + shown.push_back(line); + }; + const std::string text = report_rng_handoff_stop(logger, "Stopped for RNG.", {"Attempt 1", "Attempt 2"}, show); + if (text != "Stopped for RNG.\nAttempt 1\nAttempt 2"){ + return std::format("Wrong notification text: {}", text); + } + if (shown != std::vector{"Stopped for RNG.", "Attempt 1", "Attempt 2"}){ + return "The overlay must get the message and then each line"; + } + shown.clear(); + if (report_rng_handoff_stop(logger, "Stopped.", {}, show) != "Stopped." || shown.size() != 1){ + return "A stop without lines is its message alone"; + } + return true; +} + +const RngHandoffTestCase RNG_HANDOFF_CASES[] = { + { + .input = {.name = "RUN takes precedence over STOP", .body = test_mode}, + .expectation = {.description = "RUN wins when both options are on"}, + }, + { + .input = {.name = "a stop reports its message and lines", .body = test_stop_report}, + .expectation = {.description = "log, overlay and notification text agree"}, + }, + { + .input = {.name = "a success is ok", .body = test_success}, + .expectation = {.description = "an ok outcome after one call"}, + }, + { + .input = {.name = "a failure throws without a retry", .body = test_failure}, + .expectation = {.description = "OperationFailedException after one call"}, + }, + { + .input = {.name = "a user's turn is returned, not an error", .body = test_user_turn}, + .expectation = {.description = "the message comes back; a failure still throws"}, + }, +}; + +} // namespace + + +void add_tests_StoryRngHandoff(UnitTestDatabase& database){ + for (const RngHandoffTestCase& scenario : RNG_HANDOFF_CASES){ + database.add(scenario); + } +} + + +} // namespace Pokemon +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h new file mode 100644 index 0000000000..aca6f82c1b --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h @@ -0,0 +1,23 @@ +/* Story RNG Handoff Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StoryRngHandoff_Tests_H +#define PokemonAutomation_Pokemon_StoryRngHandoff_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// Registers unit tests for the shared RNG handoff contract. +void add_tests_StoryRngHandoff(UnitTestDatabase& database); + + + +} // namespace Pokemon +} // namespace PokemonAutomation +#endif 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_Tests.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp index 1d9ef32865..e22aa36eea 100644 --- a/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryStepExecutor_Tests.cpp @@ -727,18 +727,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{ 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/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_Tests.cpp b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp index 25c3ecfcb8..fcf299992e 100644 --- a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp +++ b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapData_Tests.cpp @@ -401,18 +401,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..b39d50bbf7 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. * */ diff --git a/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h b/SerialPrograms/Source/Pokemon/Navigation/Pokemon_MapTiles.h index 6f3cf1373e..63ebf79735 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. * */ 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..cbdd909b62 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. * */ 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/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/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp new file mode 100644 index 0000000000..4db0232e56 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp @@ -0,0 +1,220 @@ +/* BDSP RNG Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Logging/Logger.h" +#include "PokemonBDSP_RngFilter.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +const uint8_t BDSP_HEIGHT_MIN = 0; +const uint8_t BDSP_HEIGHT_MAX = 255; + + +BdspRngFilterRow::BdspRngFilterRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , misc(static_cast(parent_table).feature_flags) + , height( + LockMode::UNLOCK_WHILE_RUNNING, + BDSP_HEIGHT_MIN, BDSP_HEIGHT_MAX, BDSP_HEIGHT_MIN, BDSP_HEIGHT_MIN, + BDSP_HEIGHT_MIN, BDSP_HEIGHT_MAX, BDSP_HEIGHT_MAX, BDSP_HEIGHT_MAX + ) + , iv_hp(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_atk(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_def(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_spatk(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_spdef(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_speed(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) +{ + if (misc.feature_flags.action){ + PA_ADD_OPTION(misc.action); + } + if (misc.feature_flags.shiny){ + PA_ADD_OPTION(misc.shiny); + } + if (misc.feature_flags.gender){ + PA_ADD_OPTION(misc.gender); + } + if (misc.feature_flags.nature){ + PA_ADD_OPTION(misc.nature); + } + PA_ADD_OPTION(height); + PA_ADD_OPTION(iv_hp); + PA_ADD_OPTION(iv_atk); + PA_ADD_OPTION(iv_def); + PA_ADD_OPTION(iv_spatk); + PA_ADD_OPTION(iv_spdef); + PA_ADD_OPTION(iv_speed); +} +std::unique_ptr BdspRngFilterRow::clone() const{ + std::unique_ptr ret(new BdspRngFilterRow(parent())); + ret->misc.set(misc); + ret->height.set(height); + ret->iv_hp.set(iv_hp); + ret->iv_atk.set(iv_atk); + ret->iv_def.set(iv_def); + ret->iv_spatk.set(iv_spatk); + ret->iv_spdef.set(iv_spdef); + ret->iv_speed.set(iv_speed); + return ret; +} +bool BdspRngFilterRow::match_iv( + const IntegerRangeCell& desired, const IvRange& actual +){ + uint8_t lo, hi; + desired.current_values(lo, hi); + if (lo == 0 && hi == 31){ + return true; + } + if (actual.high < (int8_t)lo){ + return false; + } + if ((int8_t)hi < actual.low){ + return false; + } + return true; +} +bool BdspRngFilterRow::matches( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + uint8_t height, + const IvRanges& ivs +) const{ + if (!misc.matches(shiny, gender, nature)){ + return false; + } + + uint8_t height_lo, height_hi; + this->height.current_values(height_lo, height_hi); + if (height < height_lo || height_hi < height){ + return false; + } + + if (!match_iv(iv_hp, ivs.hp)){ + return false; + } + if (!match_iv(iv_atk, ivs.attack)){ + return false; + } + if (!match_iv(iv_def, ivs.defense)){ + return false; + } + if (!match_iv(iv_spatk, ivs.spatk)){ + return false; + } + if (!match_iv(iv_spdef, ivs.spdef)){ + return false; + } + if (!match_iv(iv_speed, ivs.speed)){ + return false; + } + + return true; +} + + +BdspRngFilterTable::BdspRngFilterTable( + const std::string& label, + const StatsHuntMiscFeatureFlags& p_feature_flags +) + : EditableTableOption_t(label, LockMode::UNLOCK_WHILE_RUNNING) + , feature_flags(p_feature_flags) +{} +std::vector BdspRngFilterTable::make_header() const{ + std::vector ret; + if (feature_flags.action){ + ret.emplace_back("Action"); + } + if (feature_flags.shiny){ + ret.emplace_back("Shininess"); + } + if (feature_flags.gender){ + ret.emplace_back("Gender"); + } + if (feature_flags.nature){ + ret.emplace_back("Nature"); + } + + ret.emplace_back("Height"); + + ret.emplace_back("HP"); + ret.emplace_back("Atk"); + ret.emplace_back("Def"); + ret.emplace_back("SpAtk"); + ret.emplace_back("SpDef"); + ret.emplace_back("Spd"); + + return ret; +} +BdspRngFilterSnapshot BdspRngFilterTable::make_snapshot() const{ + return BdspRngFilterSnapshot(copy_snapshot()); +} +void set_default_shiny_row(BdspRngFilterTable& table){ + std::vector> defaults; + auto row = std::make_unique(table); + row->misc.shiny.set(StatsHuntShinyFilter::Shiny); + defaults.emplace_back(std::move(row)); + table.set_default(std::move(defaults)); + table.restore_defaults(); +} +StatsHuntAction BdspRngFilterTable::get_action( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + uint8_t height, + const IvRanges& ivs +) const{ + return make_snapshot().get_action(shiny, gender, nature, height, ivs); +} + + +BdspRngFilterSnapshot::BdspRngFilterSnapshot(std::vector> rows) + : m_rows(std::move(rows)) +{} +StatsHuntAction BdspRngFilterSnapshot::get_action( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + uint8_t height, + const IvRanges& ivs +) const{ + StatsHuntAction action = StatsHuntAction::Discard; + for (size_t c = 0; c < m_rows.size(); c++){ + const BdspRngFilterRow& filter = *m_rows[c]; + + if (!filter.matches(shiny, gender, nature, height, ivs)){ + continue; + } + + StatsHuntAction filter_action = filter.misc.action; + + // No action matched so far. Take the current action and continue. + if (action == StatsHuntAction::Discard){ + action = filter_action; + continue; + } + + // Conflicting actions. + if (action != filter_action){ + global_logger_tagged().log( + "Multiple filters matched with conflicting actions. Stopping program...", + COLOR_RED + ); + return StatsHuntAction::StopProgram; + } + } + return action; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h new file mode 100644 index 0000000000..652bc73753 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h @@ -0,0 +1,106 @@ +/* BDSP RNG Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngFilter_H +#define PokemonAutomation_PokemonBDSP_RngFilter_H + +#include +#include +#include +#include "Common/Cpp/Options/EditableTableOption.h" +#include "Common/Cpp/Options/IntegerRangeOption.h" +#include "Pokemon/Pokemon_NatureChecker.h" +#include "Pokemon/Pokemon_StatsCalculation.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class BdspRngFilterTable; +class BdspRngFilterRow : public EditableTableRow{ +public: + BdspRngFilterRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + + bool matches( + bool shiny, + Pokemon::StatsHuntGenderFilter gender, + Pokemon::NatureCheckerValue nature, + uint8_t height, + const Pokemon::IvRanges& ivs + ) const; + +private: + static bool match_iv(const IntegerRangeCell& desired, const Pokemon::IvRange& actual); + +public: + Pokemon::StatsHuntRowMisc misc; + + IntegerRangeCell height; + + IntegerRangeCell iv_hp; + IntegerRangeCell iv_atk; + IntegerRangeCell iv_def; + IntegerRangeCell iv_spatk; + IntegerRangeCell iv_spdef; + IntegerRangeCell iv_speed; +}; + + +// The table copied once. Calling get_action() on the table itself clones every row on +// every call, which is far too slow for a scan running over millions of advances. +class BdspRngFilterSnapshot{ +public: + explicit BdspRngFilterSnapshot(std::vector> rows); + + Pokemon::StatsHuntAction get_action( + bool shiny, + Pokemon::StatsHuntGenderFilter gender, + Pokemon::NatureCheckerValue nature, + uint8_t height, + const Pokemon::IvRanges& ivs + ) const; + +private: + std::vector> m_rows; +}; + + +class BdspRngFilterTable : public EditableTableOption_t{ +public: + BdspRngFilterTable( + const std::string& label, + const Pokemon::StatsHuntMiscFeatureFlags& p_feature_flags + ); + virtual std::vector make_header() const override; + + BdspRngFilterSnapshot make_snapshot() const; + + Pokemon::StatsHuntAction get_action( + bool shiny, + Pokemon::StatsHuntGenderFilter gender, + Pokemon::NatureCheckerValue nature, + uint8_t height, + const Pokemon::IvRanges& ivs + ) const; + +public: + const Pokemon::StatsHuntMiscFeatureFlags feature_flags; +}; + + +// Makes the table's default, and its current content, one row: a shiny of +// any nature, gender and IVs. An empty table matches nothing, so a program +// that stops on a match must seed its table with this. +void set_default_shiny_row(BdspRngFilterTable& table); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.cpp index 7f1b00688e..a9f0675086 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.cpp @@ -41,6 +41,7 @@ #include "Programs/RngManipulation/PokemonBDSP_BedroomSeedFinder.h" #include "Programs/RngManipulation/PokemonBDSP_IntroSeedFinder.h" +#include "Programs/RngManipulation/PokemonBDSP_StarterRng.h" #include "Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.h" #include "Programs/TestPrograms/PokemonBDSP_SoundListener.h" @@ -67,6 +68,7 @@ void add_beta_and_developer_panels(std::vector& ret){ ret.emplace_back("---- Untested/Beta/WIP ----"); ret.emplace_back(make_SingleSwitchProgram()); ret.emplace_back(make_SingleSwitchProgram()); + ret.emplace_back(make_SingleSwitchProgram()); } if (STATIC_GLOBALS.DEVELOPER_MODE){ ret.emplace_back("---- Developer Tools ----"); diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp index afac33d987..30d00f6b2d 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Tests.cpp @@ -18,6 +18,7 @@ #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_StoryData_Tests.h" #include "Programs/AutoStory/PokemonBDSP_AutoStory_Walk_Tests.h" +#include "Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h" #include "PokemonBDSP_Tests.h" namespace PokemonAutomation{ @@ -40,6 +41,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStory_StoryData(database); add_tests_AutoStory_Walk(database); add_tests_AutoStory_PlannedRoute(database); + add_tests_StarterRng(database); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Lake.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Lake.cpp index 0c7841c7fe..2b4924116f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Lake.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Events_Lake.cpp @@ -118,6 +118,16 @@ void azure_flute_if_there(VideoStream& stream, ProControllerContext& context){ +// 00.02 with Run Starter RNG in AutoStory: runs Starter RNG from the +// Verity Lakefront (17, 14) start save through the Starly battle and +// Rowan's scene, ending on the VerityLakefront overworld at (17, 14..15). +Pokemon::Outcome starter_rng(StoryExecutor& executor, Pokemon::RunState&, const Pokemon::StoryStep&){ + if (!executor.env().run_starter_rng){ + return Pokemon::outcome_failed("starter_rng_not_configured", "Starter RNG is not configured on StoryEnv."); + } + return executor.env().run_starter_rng(); +} + // 00.04: Dawn's catching tutorial on Route 202: her lines and her demo // battle, B for 70 s. void catch_tutorial(VideoStream& stream, ProControllerContext& context){ @@ -134,6 +144,7 @@ void add_lake_events(StoryEvents& events){ events.emplace("azure_flute_if_there", console_event(azure_flute_if_there)); events.emplace("starter_briefcase", console_event(starter_briefcase)); events.emplace("choose_starter", choose_starter); + events.emplace("starter_rng", starter_rng); events.emplace("catch_tutorial", console_event(catch_tutorial)); diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp index 9e10c1ac1f..32051ab4dd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp @@ -9,11 +9,13 @@ #include #include #include +#include #include "CommonFramework/Exceptions/OperationFailedException.h" #include "CommonFramework/Notifications/ProgramNotifications.h" #include "CommonFramework/VideoPipeline/VideoOverlay.h" #include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" #include "Pokemon/AutoStory/Pokemon_StoryPreflight.h" +#include "Pokemon/AutoStory/Pokemon_StoryRngHandoff.h" #include "Pokemon/AutoStory/Pokemon_StoryRun.h" #include "Pokemon/AutoStory/Pokemon_AutoStorySelect.h" #include "Pokemon/AutoStory/Pokemon_AutoStoryStats.h" @@ -22,6 +24,7 @@ #include "Pokemon/Options/Pokemon_GameLanguages.h" #include "Pokemon/Options/Pokemon_StoryRunOptions.h" #include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" +#include "PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h" #include "PokemonBDSP/Programs/AutoStory/Actions/PokemonBDSP_AutoStory_Actions.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_Location.h" #include "PokemonBDSP/Programs/AutoStory/Utils/PokemonBDSP_AutoStory_StoryLanguage.h" @@ -56,6 +59,14 @@ std::unique_ptr BDSPAutoStory_Descriptor::make_stats() const{ namespace{ +// What the user does around Starter RNG when the run stops for it: the +// option's help and the run's closing message. +constexpr std::string_view STARTER_RNG_HANDOFF_TEXT = + "At the end of 00.01 save at the Verity Lakefront (17, 14), facing Lake Verity's entrance, and stop. " + "Run the Starter RNG program from that save (Start point: Verity Lakefront). " + "When it is done, close the Summary page and the menu, let Rowan's scene finish so the player stands " + "on the Verity Lakefront overworld, save, and start AutoStory at 00.03."; + // The start and end dropdowns' entries: segments 00 and 01 joined, 00.00 // to 01.11. The options hold a reference to it. const StringSelectDatabase& checkpoint_database(){ @@ -69,9 +80,11 @@ const StringSelectDatabase& checkpoint_database(){ return database; } -std::set rows_that_stop(const std::vector& rows){ - std::set ids; - for (const StoryCheckpoint& row : rows){ +// The rows whose failure ends the program: the rows that save nothing and +// retry nothing, and the plan's own (Starter RNG's, which resets by itself). +std::set rows_that_stop(const StoryRunPlan& plan){ + std::set ids = plan.fatal_rows; + for (const StoryCheckpoint& row : plan.rows){ if (row.on_failure == StoryFailure::STOP){ ids.insert(row.id); } @@ -123,6 +136,10 @@ std::string verify_story_checkpoint( } // namespace +BDSPAutoStory::~BDSPAutoStory(){ + STARTER_RNG.run().remove_listener(*this); +} + BDSPAutoStory::BDSPAutoStory() : RUN(checkpoint_database(), Pokemon::Gen8ToGen9Languages_Database()) , NEW_GAME_INTRO( @@ -142,7 +159,16 @@ BDSPAutoStory::BDSPAutoStory() LockMode::LOCK_WHILE_RUNNING, StarterChoice::CHIMCHAR ) + , STOP_FOR_STARTER_RNG( + std::format( + "Stop for Starter RNG:
Off by default. Ignored while Run Starter RNG in AutoStory is on. {}", + STARTER_RNG_HANDOFF_TEXT + ), + LockMode::LOCK_WHILE_RUNNING, + false + ) , NOTIFICATIONS({ + &STARTER_RNG.notification_shiny(), &NOTIFICATION_PROGRAM_FINISH, &NOTIFICATION_ERROR_RECOVERABLE, &NOTIFICATION_ERROR_FATAL, @@ -152,7 +178,23 @@ BDSPAutoStory::BDSPAutoStory() PA_ADD_OPTION(NEW_GAME_INTRO); PA_ADD_OPTION(PLAYER_NAME); PA_ADD_OPTION(STARTER); + PA_ADD_OPTION(STOP_FOR_STARTER_RNG); + add_option(STARTER_RNG.run(), "RUN_STARTER_RNG"); + add_option(STARTER_RNG.player_model(), "STARTER_RNG_PLAYER_MODEL"); + add_option(STARTER_RNG.max_resets(), "MAX_RESETS"); + add_option(STARTER_RNG.filters(), "STARTER_RNG_FILTERS"); PA_ADD_OPTION(NOTIFICATIONS); + + BDSPAutoStory::on_config_value_changed(this); + STARTER_RNG.run().add_listener(*this); +} + +// Run Starter RNG takes precedence over Stop for Starter RNG: the stop +// option is greyed out while it is on, and the plan ignores it. +void BDSPAutoStory::on_config_value_changed(void*){ + const bool run_in_story = STARTER_RNG.run(); + STARTER_RNG.set_details_visible(run_in_story); + STOP_FOR_STARTER_RNG.set_visibility(run_in_story ? ConfigOptionState::DISABLED : ConfigOptionState::ENABLED); } namespace{ @@ -246,30 +288,56 @@ void BDSPAutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerCo // The reads that use text (Location.h) take the game's language from here. set_story_language(RUN.language()); - StoryEnv story{env, context, STARTER, PLAYER_NAME}; + StoryEnv story{env, context, STARTER, PLAYER_NAME, {}}; + if (STARTER_RNG.run()){ + story.run_starter_rng = make_starter_rng_hook( + env, context, STARTER_RNG, STARTER_RNG.config(RUN.language(), STARTER), NOTIFICATION_ERROR_RECOVERABLE + ); + } StoryExecutor executor(story); - executor.set_stop_rows(rows_that_stop(checkpoints)); + const StoryRunPlan plan = plan_story_run( + checkpoints, first, last, + StoryHandoffs{.starter_rng = Pokemon::rng_handoff_mode({.stop = STOP_FOR_STARTER_RNG, .run = STARTER_RNG.run()})} + ); + executor.set_stop_rows(rows_that_stop(plan)); + run_plan(env, context, plan, first == 0 && NEW_GAME_INTRO, executor); +} + +void BDSPAutoStory::run_plan( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StoryRunPlan& plan, bool new_game, StoryExecutor& executor +){ // A start with a save always loads it first, so the run never walks // from wherever the game was left (console B, 2026-11-11: a run from // 00.04b walked from 00.04d's position). - const bool new_game = first == 0 && NEW_GAME_INTRO; const Pokemon::StoryStart start = new_game ? Pokemon::StoryStart::NEW_GAME : Pokemon::StoryStart::FROM_SAVE; if (new_game && RUN.VERIFY.policy()){ throw UserSetupError(env.console, "Verify mode reloads the start's save between runs: turn off \"Start a new game first\"."); } - std::set saved = saved_before_the_run(checkpoints, first, start); - Pokemon::Segment segment = make_story_segment(checkpoints, executor, saved); + if (plan.stop != StoryHandoff::NONE && RUN.VERIFY.policy()){ + throw UserSetupError(env.console, "Verify mode repeats the start's checkpoint, and its extra save at the end of 00.01 would overwrite the Verity Lakefront save: turn off \"Stop for Starter RNG\"."); + } + std::set saved = saved_before_the_run(plan.rows, 0, start); + Pokemon::Segment segment = make_story_segment(plan.rows, executor, saved); Pokemon::StoryGameHooks game = story_game(env, context); Pokemon::RunState state; - start_story(env, context, checkpoints[first], start, game, state); + start_story(env, context, plan.rows.front(), start, game, state); if (const std::optional verify = RUN.VERIFY.policy()){ - const std::string summary = verify_story_checkpoint(checkpoints[first].id, *verify, segment, game, state); + const std::string summary = verify_story_checkpoint(plan.rows.front().id, *verify, segment, game, state); send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, summary); return; } const std::string done = run_story( - Pokemon::SegmentRange{checkpoints[first].id, checkpoints[last].id}, RUN.policy(), segment, game, state, env + Pokemon::SegmentRange{plan.rows.front().id, plan.rows.back().id}, RUN.policy(), segment, game, state, env ); + if (plan.stop == StoryHandoff::STARTER_RNG){ + const std::string handoff = Pokemon::report_rng_handoff_stop( + env.console, std::format("Stopped for Starter RNG. {}", STARTER_RNG_HANDOFF_TEXT), {}, + [&](const std::string& line){ env.console.overlay().add_log(line); } + ); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, handoff); + return; + } send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, done); } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h index 154eccade4..88ccce0d08 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h @@ -19,7 +19,9 @@ #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "Pokemon/Options/Pokemon_StoryRunOptions.h" +#include "PokemonBDSP_AutoStory_StarterRng.h" #include "PokemonBDSP_AutoStory_StoryExecutor.h" +#include "PokemonBDSP_AutoStory_StoryTable.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -36,19 +38,31 @@ class BDSPAutoStory_Descriptor : public SingleSwitchProgramDescriptor{ // Single-switch program instance executing BDSP story automation. -class BDSPAutoStory : public SingleSwitchProgramInstance{ +class BDSPAutoStory : public SingleSwitchProgramInstance, public ConfigOption::Listener{ public: using Descriptor = BDSPAutoStory_Descriptor; + ~BDSPAutoStory(); BDSPAutoStory(); virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; private: + virtual void on_config_value_changed(void* object) override; + + // Starts the plan's story and runs it to its end or its stop. + void run_plan( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StoryRunPlan& plan, bool new_game, StoryExecutor& executor + ); + // The start and end checkpoints, attempts, checks and language. Pokemon::StoryRunOptions RUN; BooleanCheckBoxOption NEW_GAME_INTRO; StringOption PLAYER_NAME; EnumDropdownOption STARTER; + // The RNG program the run stops for (StoryHandoff), or runs in 00.02. + BooleanCheckBoxOption STOP_FOR_STARTER_RNG; + StoryStarterRngOptions STARTER_RNG; EventNotificationsOption NOTIFICATIONS; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp new file mode 100644 index 0000000000..8ceb126ce8 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp @@ -0,0 +1,174 @@ +/* BDSP AutoStory: Starter RNG + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonBDSP_AutoStory_StarterRng.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +BdspStarter bdsp_starter_for_choice(StarterChoice choice){ + switch (choice){ + case StarterChoice::TURTWIG: + return BdspStarter::Turtwig; + case StarterChoice::CHIMCHAR: + return BdspStarter::Chimchar; + case StarterChoice::PIPLUP: + return BdspStarter::Piplup; + } + return BdspStarter::Chimchar; +} + + +StoryStarterRngOptions::StoryStarterRngOptions() + : RUN( + "Run Starter RNG in AutoStory:
Off by default. In 00.02, run Starter RNG from the Verity Lakefront " + "save using the stop conditions below, then continue the story at 00.03. " + "Takes precedence over Stop for Starter RNG. If it fails the program stops: it does not reload 00.02.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , MAX_RESETS( + "Starter RNG Maximum Resets:
0 means no limit.", + LockMode::LOCK_WHILE_RUNNING, + 0, 0, 9999 + ) + , FILTERS( + "Starter RNG Stop Conditions:
Stop Starter RNG when the starter matches any row in this table.", + Pokemon::StatsHuntMiscFeatureFlags{ + /*action*/ false, /*shiny*/ true, /*gender*/ true, /*nature*/ true + } + ) + , NOTIFICATION_SHINY( + "Shiny Starter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) +{ + set_default_shiny_row(FILTERS); +} + +void StoryStarterRngOptions::set_details_visible(bool visible){ + const ConfigOptionState state = visible ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN; + PLAYER_MODEL.set_visibility(state); + MAX_RESETS.set_visibility(state); + FILTERS.set_visibility(state); +} + +StoryStarterRngConfig StoryStarterRngOptions::config(Language language, StarterChoice starter) const{ + return StoryStarterRngConfig{ + .language = language, + .player_model = PLAYER_MODEL.model_number(), + .starter = starter, + .max_resets = MAX_RESETS, + }; +} + + +StarterRngSettings make_starter_rng_settings(const StoryStarterRngConfig& config, const BdspRngFilterSnapshot& filters){ + StarterRngSettings settings; + settings.language = config.language; + settings.player_model = config.player_model; + settings.start_point = BdspStartPoint::Lakefront; + settings.starter = bdsp_starter_for_choice(config.starter); + settings.filters = &filters; + settings.max_resets = config.max_resets; + settings.reset_first = false; + settings.finish_battle_on_shiny = true; + settings.close_summary_after_read = true; + return settings; +} + +std::string starter_rng_failure(const StarterRngRunResult& result){ + switch (result.outcome){ + case StarterRngOutcome::HIT: + return ""; + case StarterRngOutcome::SHINY: + if (!result.settled){ + return "Caught a shiny starter, but the Starly battle or Rowan's scene did not finish: " + "stopped with the shiny in the party; the game is not on the Verity Lakefront overworld."; + } + return ""; + case StarterRngOutcome::OUT_OF_RESETS: + case StarterRngOutcome::ABANDONED: + break; + } + if (result.last_failure_reason.empty()){ + return std::format("Starter RNG stopped after {} reset(s) without hitting a target.", result.resets_used); + } + return result.last_failure_reason; +} + + +Pokemon::RngHandoffResult starter_rng_handoff_result(const StarterRngRunResult& result){ + Pokemon::RngHandoffResult handoff; + handoff.failure = starter_rng_failure(result); + if (handoff.failure.empty()){ + handoff.summary = std::format( + "after {} reset(s) on advance {}: {}.", + result.resets_used, result.target_advance, result.target.to_string() + ); + } + return handoff; +} + + +namespace{ + +// What the hook keeps between its calls: the filters, copied once so that +// edits made while running do not apply, and the aim that Starter RNG's +// calibration builds up across them. +struct StarterRngHookState{ + StarterRngHookState(StoryStarterRngOptions& options, const StoryStarterRngConfig& config) + : filters(options.filters().make_snapshot()) + , settings(make_starter_rng_settings(config, filters)) + {} + + RngAim aim; + BdspRngFilterSnapshot filters; + StarterRngSettings settings; +}; + +} // namespace + + +std::function make_starter_rng_hook( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryStarterRngOptions& options, const StoryStarterRngConfig& config, + EventNotificationOption& error_notification +){ + if (options.filters().current_rows() == 0){ + throw UserSetupError( + env.console, + "Starter RNG Stop Conditions is empty, so no starter would ever match: add a row, such as a shiny of any nature." + ); + } + std::shared_ptr state = std::make_shared(options, config); + return [&env, &context, &options, &error_notification, state]() -> Pokemon::Outcome{ + uint64_t resets_logged = 0; + StarterRngAttemptIO io; + io.notification_shiny = &options.notification_shiny(); + io.notification_error = &error_notification; + io.on_reset = [&]{ + resets_logged++; + env.console.overlay().add_log(std::format("Starter RNG: try {}", resets_logged)); + }; + return Pokemon::run_rng_handoff(env.logger(), "Starter RNG", [&]{ + const StarterRngRunResult result = run_starter_rng_attempts(env, context, state->settings, io, state->aim); + return starter_rng_handoff_result(result); + }); + }; +} + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h new file mode 100644 index 0000000000..fc2df841e0 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h @@ -0,0 +1,99 @@ +/* BDSP AutoStory: Starter RNG + * + * From: https://github.com/PokemonAutomation/ + * + * Run Starter RNG in AutoStory: its options, and the action that 00.02 runs + * in place of its Lake Verity steps (the Starter RNG program's reset loop, + * PokemonBDSP_StarterRngAttempts.h, called from the story). + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutoStory_StarterRng_H +#define PokemonAutomation_PokemonBDSP_AutoStory_StarterRng_H + +#include +#include +#include +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "Pokemon/AutoStory/Pokemon_StoryOutcome.h" +#include "Pokemon/AutoStory/Pokemon_StoryRngHandoff.h" +#include "PokemonBDSP/Options/PokemonBDSP_PlayerModelOption.h" +#include "PokemonBDSP/Options/PokemonBDSP_RngFilter.h" +#include "PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h" +#include "PokemonBDSP_AutoStory_StoryExecutor.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Maps AutoStory's starter option to Starter RNG's starter enum. +BdspStarter bdsp_starter_for_choice(StarterChoice choice); + + +// What the story tells Starter RNG about the game it plays. +struct StoryStarterRngConfig{ + Language language = Language::English; + // The player's appearance, 1 to 8: the lake's eye templates depend on it. + uint8_t player_model = 1; + StarterChoice starter = StarterChoice::CHIMCHAR; + uint16_t max_resets = 0; +}; + + +// AutoStory's options for Starter RNG. Only RUN is always shown; the rest +// show while it is on. +class StoryStarterRngOptions{ +public: + StoryStarterRngOptions(); + + void set_details_visible(bool visible); + // The options' values, for a story in `language` with `starter`. + StoryStarterRngConfig config(Language language, StarterChoice starter) const; + + BooleanCheckBoxOption& run(){ return RUN; } + PlayerModelOption& player_model(){ return PLAYER_MODEL; } + SimpleIntegerOption& max_resets(){ return MAX_RESETS; } + BdspRngFilterTable& filters(){ return FILTERS; } + EventNotificationOption& notification_shiny(){ return NOTIFICATION_SHINY; } + +private: + BooleanCheckBoxOption RUN; + PlayerModelOption PLAYER_MODEL; + SimpleIntegerOption MAX_RESETS; + BdspRngFilterTable FILTERS; + EventNotificationOption NOTIFICATION_SHINY; +}; + + +// Starter RNG's settings for the run in 00.02: from the Verity Lakefront +// save, through the Starly battle and Rowan's scene on a shiny or not, to +// the Lakefront overworld with the menu closed. +StarterRngSettings make_starter_rng_settings(const StoryStarterRngConfig& config, const BdspRngFilterSnapshot& filters); + +// Why the story cannot go on after Starter RNG ended as `result`; empty if +// it can: a starter was caught and the game stands on the Lakefront. +std::string starter_rng_failure(const StarterRngRunResult& result); + +// Starter RNG's end as the shared handoff contract has it +// (Pokemon_StoryRngHandoff.h): starter_rng_failure() and, on success, the +// resets used and the target hit. +Pokemon::RngHandoffResult starter_rng_handoff_result(const StarterRngRunResult& result); + +// The action 00.02 runs. Throws a UserSetupError now if the filter table is +// empty. The action itself throws when Starter RNG fails, so that no row +// retry reruns the whole reset loop. +std::function make_starter_rng_hook( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryStarterRngOptions& options, const StoryStarterRngConfig& config, + EventNotificationOption& error_notification +); + + +} // namespace PokemonBDSP +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h index bc8e9b535e..65c74a2f02 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryExecutor.h @@ -22,6 +22,7 @@ #ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryExecutor_H #define PokemonAutomation_PokemonBDSP_AutoStory_StoryExecutor_H +#include #include #include #include @@ -78,6 +79,7 @@ struct StoryEnv{ ProControllerContext& context; StarterChoice starter = StarterChoice::CHIMCHAR; std::string player_name; + std::function run_starter_rng; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp index 79bab21f0a..64dcab1c23 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StorySimulation_Tests.cpp @@ -442,6 +442,57 @@ UnitTestResult test_start_and_end(Logger&){ if (!report.completed || one.begun() != std::vector{"00.02"}){ return "Expected 00.02 alone:" + joined(one.begun()); } + // With Stop for Starter RNG on, a 00.00..01.11 run stops after 00.01 + // saves at the Verity Lakefront (17, 14) facing north. + Simulation handoff_sim; + const StoryRunPlan plan = plan_story_run( + story_checkpoints(), 0, story_checkpoints().size() - 1, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::STOP} + ); + Pokemon::Segment handoff_segment = make_story_segment(plan.rows, handoff_sim.game, handoff_sim.saved); + Pokemon::SegmentHooks hooks; + hooks.reload = [&](RunState&){ return Pokemon::outcome_ok(); }; + RunState handoff_state; + const Pokemon::SegmentReport handoff_report = Pokemon::run_segment( + {.from = plan.rows.front().id, .to = plan.rows.back().id}, handoff_sim.policy, handoff_segment, hooks, handoff_state + ); + if (!handoff_report.completed || plan.stop != StoryHandoff::STARTER_RNG || + handoff_sim.begun() != std::vector{"00.00", "00.01"} || + handoff_sim.count("00.01/save_for_starter_rng") != 1 || + handoff_sim.count("card for 00.01: Verity Lakefront") != 1 || + handoff_state.pose.map != "VerityLakefront" || + Pokemon::tiles_of(handoff_state.pose) != std::vector{{17, 14}} + ){ + return std::format("Expected Starter RNG handoff to stop after 00.01 saved at VerityLakefront (17, 14), checking the Verity Lakefront card:{}", joined(handoff_sim.trace)); + } + return true; +} + +// With Run Starter RNG in AutoStory on, 00.02 saves at the Verity +// Lakefront, runs 00.02/starter_rng, and chains into 00.03. +UnitTestResult test_run_starter_rng_in_story(Logger&){ + Pokemon::SegmentHooks hooks; + hooks.reload = [&](RunState&){ return Pokemon::outcome_ok(); }; + Simulation in_program_sim; + const StoryRunPlan in_program_plan = plan_story_run( + story_checkpoints(), 0, 3, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::RUN} + ); + Pokemon::Segment in_program_segment = make_story_segment(in_program_plan.rows, in_program_sim.game, in_program_sim.saved); + RunState in_program_state; + const Pokemon::SegmentReport in_program_report = Pokemon::run_segment( + {.from = "00.00", .to = "00.03"}, in_program_sim.policy, in_program_segment, hooks, in_program_state + ); + if (!in_program_report.completed || + in_program_sim.begun() != std::vector{"00.00", "00.01", "00.02", "00.03"} || + in_program_sim.count("save in 00.02") != 1 || + in_program_sim.count("card for 00.02: Verity Lakefront") != 1 || + in_program_sim.count("00.02/starter_rng") != 1 || + in_program_sim.count("00.02/choose_starter") != 0 + ){ + return std::format( + "Expected 00.02 with Run Starter RNG in AutoStory to save at Verity Lakefront, run 00.02/starter_rng, and continue to 00.03:{}", + joined(in_program_sim.trace) + ); + } return true; } @@ -644,6 +695,10 @@ const AutoStoryStorySimulationCase AUTO_STORY_STORY_SIMULATION_CASES[] = { .input = {"start and end checkpoints", test_start_and_end}, .expectation = {}, }, + { + .input = {"Run Starter RNG in AutoStory chains 00.02 into 00.03", test_run_starter_rng_in_story}, + .expectation = {}, + }, { .input = {"a blackout in 00.04b's training resets to its save", test_training_blackout}, .expectation = {}, diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp index 3977dedaa1..80a864315c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.cpp @@ -7,6 +7,8 @@ * */ +#include "Pokemon/AutoStory/Pokemon_BuiltinStoryActions.h" +#include "Pokemon/AutoStory/Types/Pokemon_GridPose.h" #include "PokemonBDSP_AutoStory_StoryData.h" #include "PokemonBDSP_AutoStory_StoryTable.h" @@ -15,11 +17,85 @@ namespace NintendoSwitch{ namespace PokemonBDSP{ +namespace{ + +// 00.02 is the Lake Verity starter and Starly battle checkpoint, which Run +// Starter RNG in AutoStory replaces with the game event STARTER_RNG_ACTION. +constexpr std::string_view STARTER_RNG_CHECKPOINT_ROW = "00.02"; +constexpr std::string_view STARTER_RNG_ACTION = "starter_rng"; + +// `row` with a save appended at its end, where the next checkpoint starts: +// in BDSP rows normally save at their start, so a run that stops after +// 00.01 for Starter RNG makes 00.02's Lakefront save before stopping. As +// every start save does, it checks that the save card names `saves_in` +// (the next row's), and stops the program if not. +StoryCheckpoint with_handoff_save(StoryCheckpoint row, const std::string& saves_in){ + Pokemon::StoryStep save; + save.kind = Pokemon::StoryStepKind::SAVE; + save.name = "save_for_starter_rng"; + save.action = saves_in; + save.why = "the save at the Verity Lakefront where Starter RNG starts"; + if (!row.steps.empty()){ + const Pokemon::StoryStep& last = row.steps.back(); + if (last.pose_after){ + save.pose_after = last.pose_after; + }else if (last.kind == Pokemon::StoryStepKind::ROUTE){ + const Pokemon::GridPose& target = Pokemon::story_arg(last.args, "target"); + save.pose_after = Pokemon::TileDeclared{ + .map = target.map, .tiles = target.tiles, .facing = target.facing + }; + } + } + row.steps.push_back(std::move(save)); + return row; +} + +// `row` (00.02) with its Lake Verity steps replaced by the in-program +// Starter RNG action, keeping 00.02's start save at VerityLakefront (17, 14) +// and its end pose at VerityLakefront (17, 14..15). +StoryCheckpoint with_starter_rng_step(StoryCheckpoint row){ + Pokemon::StoryStep step; + step.kind = Pokemon::StoryStepKind::GAME; + step.name = std::string(STARTER_RNG_ACTION); + step.action = std::string(STARTER_RNG_ACTION); + step.why = "Starter RNG at Lake Verity through the Starly battle and Rowan's scene"; + if (!row.steps.empty()){ + step.pose_after = row.steps.back().pose_after; + } + row.steps = {std::move(step)}; + return row; +} + +} // namespace + + const std::vector& story_checkpoints(){ static const std::vector checkpoints = load_authored_story(); return checkpoints; } +StoryRunPlan plan_story_run( + const std::vector& checkpoints, size_t first, size_t last, const StoryHandoffs& handoffs +){ + StoryRunPlan plan; + for (size_t c = first; c <= last && c < checkpoints.size(); c++){ + const StoryCheckpoint& row = checkpoints[c]; + if (row.id == STARTER_RNG_HANDOFF_ROW && handoffs.starter_rng == Pokemon::RngHandoffMode::STOP){ + const std::string saves_in = c + 1 < checkpoints.size() ? checkpoints[c + 1].saves_in : std::string(); + plan.rows.push_back(with_handoff_save(row, saves_in)); + plan.stop = StoryHandoff::STARTER_RNG; + return plan; + } + if (row.id == STARTER_RNG_CHECKPOINT_ROW && handoffs.starter_rng == Pokemon::RngHandoffMode::RUN){ + plan.rows.push_back(with_starter_rng_step(row)); + plan.fatal_rows.insert(row.id); + continue; + } + plan.rows.push_back(row); + } + return plan; +} + } // namespace PokemonBDSP } // namespace NintendoSwitch diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h index 72504da1b8..39f744058c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h @@ -14,8 +14,11 @@ #ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryTable_H #define PokemonAutomation_PokemonBDSP_AutoStory_StoryTable_H +#include +#include #include #include +#include "Pokemon/AutoStory/Pokemon_StoryRngHandoff.h" #include "PokemonBDSP_AutoStory_StoryExecutor.h" namespace PokemonAutomation{ @@ -33,6 +36,45 @@ inline constexpr std::string_view RUNNING_SHOES_ROW = "00.03"; // Story step name in which Mom gives the Running Shoes. inline constexpr std::string_view RUNNING_SHOES_STEP = "rowan_and_dawn"; +// 00.01 ends at the Verity Lakefront (17, 14) facing north, where 00.02 and +// Starter RNG (Start point: Verity Lakefront) start. +inline constexpr std::string_view STARTER_RNG_HANDOFF_ROW = "00.01"; + +// An upstream RNG program the user may run part-way through the story. +enum class StoryHandoff{ + NONE, + // The run stops after 00.01 saves at the Verity Lakefront (17, 14), + // facing Lake Verity's entrance, where Starter RNG starts. + STARTER_RNG, +}; + +// The handoffs a run stops for or runs in-program (AutoStory's options). +struct StoryHandoffs{ + // STOP: the run stops after 00.01 for the user's Starter RNG. RUN: 00.02 + // runs it in the program. The mode of the options: Pokemon::rng_handoff_mode(). + Pokemon::RngHandoffMode starter_rng = Pokemon::RngHandoffMode::OFF; +}; + +// What a run from table row `first` to `last` does. +struct StoryRunPlan{ + // The checkpoints to run, in order. Copies, not pointers: a row the plan + // changes (the handoff save) must not change the table, and the run's + // steps capture these rows, which outlive the call. + std::vector rows; + // NONE: the run ends after `rows`. STARTER_RNG: the run stops after + // `rows`, the last of which (00.01) saves at the Verity Lakefront. + StoryHandoff stop = StoryHandoff::NONE; + // Rows whose failure ends the program though they save at their start: + // a failed 00.02 with Run Starter RNG, whose reset loop is the retry. + std::set fatal_rows; +}; + +// The rows of `table` from `first` to `last`, both inclusive, as a +// run with `handoffs` takes them: a run that reaches 00.01 with +// `handoffs.starter_rng` STOP saves at the Verity Lakefront at the end of +// 00.01 and stops there for Starter RNG. +StoryRunPlan plan_story_run(const std::vector& table, size_t first, size_t last, const StoryHandoffs& handoffs = {}); + } // namespace PokemonBDSP diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp index 09f4e95ba9..9f3c7c56fa 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable_Tests.cpp @@ -24,6 +24,7 @@ #include "Data/PokemonBDSP_AutoStory_StoryMaps.h" #include "Actions/PokemonBDSP_AutoStory_Events.h" #include "Data/PokemonBDSP_AutoStory_WalkRules.h" +#include "PokemonBDSP_AutoStory.h" #include "PokemonBDSP_AutoStory_StoryTable.h" #include "PokemonBDSP_AutoStory_StoryTable_Tests.h" @@ -231,6 +232,165 @@ UnitTestResult test_route204_north_line(Logger& logger){ return true; } +// plan_story_run() with Starter RNG handoff: off leaves the range unchanged; +// on stops after 00.01 with a save at the Verity Lakefront (17, 14) facing +// north, where 00.02 and Starter RNG start; starting past 00.01 runs on. +UnitTestResult test_plan_story_run_starter_rng(Logger&){ + const std::vector& table = story_checkpoints(); + const StoryRunPlan full = plan_story_run(table, 0, table.size() - 1, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::OFF}); + if (full.stop != StoryHandoff::NONE || full.rows.size() != table.size()){ + return "With Starter RNG handoff off, expected the full table with no stop."; + } + const StoryRunPlan handoff = plan_story_run(table, 0, table.size() - 1, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::STOP}); + if (handoff.stop != StoryHandoff::STARTER_RNG || handoff.rows.size() != 2 || + handoff.rows[0].id != "00.00" || handoff.rows[1].id != "00.01" + ){ + return "Expected a 00.00..01.11 run with Starter RNG handoff to stop after 00.01."; + } + const StoryCheckpoint& lakefront_row = handoff.rows.back(); + const std::vector problems = Pokemon::lint_story_checkpoint(lakefront_row); + if (!problems.empty()){ + return std::format("00.01 with Starter RNG handoff save: {}", problems[0]); + } + if (lakefront_row.steps.empty() || lakefront_row.steps.back().kind != StoryStepKind::SAVE || + lakefront_row.steps.back().name != "save_for_starter_rng" + ){ + return "Expected 00.01 with Starter RNG handoff to end with save_for_starter_rng."; + } + // The save card is checked as every other start save is: it must name + // 00.02's map. + if (lakefront_row.steps.back().action != table[2].saves_in || table[2].saves_in.empty()){ + return std::format( + "Expected the handoff save to check the card for \"{}\", got \"{}\".", + table[2].saves_in, lakefront_row.steps.back().action + ); + } + const std::optional end = end_pose(lakefront_row); + const std::optional next_start = table[2].start + ? std::make_optional(Pokemon::pose_of(*table[2].start)) + : std::nullopt; + if (!end || !next_start || end->map != "VerityLakefront" || + Pokemon::to_string(*end) != Pokemon::to_string(*next_start) + ){ + return "Expected 00.01's Starter RNG handoff save to end at 00.02's VerityLakefront (17, 14) start pose."; + } + const StoryRunPlan from_0002 = plan_story_run(table, 2, 4, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::STOP}); + if (from_0002.stop != StoryHandoff::NONE || from_0002.rows.size() != 3 || from_0002.rows.front().id != "00.02"){ + return "Expected a run starting at 00.02 to pass through without stopping for 00.01's handoff."; + } + return true; +} + +// plan_story_run() with Run Starter RNG in AutoStory: 00.02 runs the +// starter_rng event after its Verity Lakefront start save and ends where +// 00.03 starts; the handoff stop is not taken. +UnitTestResult test_plan_story_run_in_program(Logger&){ + const std::vector& table = story_checkpoints(); + const StoryRunPlan in_program = plan_story_run( + table, 0, table.size() - 1, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::RUN} + ); + if (in_program.stop != StoryHandoff::NONE || in_program.rows.size() != table.size()){ + return "With Run Starter RNG in AutoStory on, expected the full table with no handoff stop."; + } + const StoryCheckpoint& rng_row = in_program.rows[2]; + const std::vector rng_problems = Pokemon::lint_story_checkpoint(rng_row); + if (!rng_problems.empty()){ + return std::format("00.02 with Run Starter RNG in AutoStory: {}", rng_problems[0]); + } + if (rng_row.id != "00.02" || rng_row.saves_in != "Verity Lakefront" || rng_row.steps.size() != 1 || + rng_row.steps[0].kind != StoryStepKind::GAME || rng_row.steps[0].action != "starter_rng" || + !story_events().contains(rng_row.steps[0].action) + ){ + return "Expected 00.02 with Run Starter RNG in AutoStory to run the starter_rng game event after its Verity Lakefront start save."; + } + const std::optional rng_end = end_pose(rng_row); + const std::optional row0003_start = table[3].start + ? std::make_optional(Pokemon::pose_of(*table[3].start)) + : std::nullopt; + if (!rng_end || !row0003_start || Pokemon::to_string(*rng_end) != Pokemon::to_string(*row0003_start)){ + return "Expected 00.02's starter_rng step to end at 00.03's VerityLakefront (17, 14..15) start pose."; + } + if (bdsp_starter_for_choice(StarterChoice::TURTWIG) != BdspStarter::Turtwig || + bdsp_starter_for_choice(StarterChoice::CHIMCHAR) != BdspStarter::Chimchar || + bdsp_starter_for_choice(StarterChoice::PIPLUP) != BdspStarter::Piplup + ){ + return "Expected StarterChoice to map 1-to-1 to BdspStarter."; + } + return true; +} + + +// The Starter RNG run's settings: the player's model, the starter and the +// reset limit come from AutoStory's options, and the run ends where 00.03 +// starts (Lakefront overworld, menu closed). +UnitTestResult test_starter_rng_settings(Logger&){ + BdspRngFilterTable table("Filters", Pokemon::StatsHuntMiscFeatureFlags{false, true, true, true}); + set_default_shiny_row(table); + const BdspRngFilterSnapshot filters = table.make_snapshot(); + const StoryStarterRngConfig config{ + .language = Language::French, .player_model = 5, .starter = StarterChoice::PIPLUP, .max_resets = 7 + }; + const StarterRngSettings settings = make_starter_rng_settings(config, filters); + if (settings.player_model != 5){ + return std::format("Expected the story's player model 5 to reach Starter RNG, got {}.", settings.player_model); + } + if (settings.starter != BdspStarter::Piplup || settings.language != Language::French || settings.max_resets != 7){ + return "Expected the starter, language and reset limit to come from the story's options."; + } + if (settings.filters != &filters || settings.start_point != BdspStartPoint::Lakefront){ + return "Expected the filter snapshot and the Verity Lakefront start point."; + } + if (settings.reset_first || !settings.finish_battle_on_shiny || !settings.close_summary_after_read){ + return "Expected a run that starts from the loaded save and leaves the Lakefront overworld on a shiny or not."; + } + return true; +} + +// What Starter RNG ending means for the story: a starter in hand and the +// game on the Lakefront lets it go on; anything else stops it with a reason. +UnitTestResult test_starter_rng_failure(Logger&){ + StarterRngRunResult result; + result.outcome = StarterRngOutcome::HIT; + if (!starter_rng_failure(result).empty()){ + return "Expected a hit to let the story go on."; + } + result.outcome = StarterRngOutcome::SHINY; + if (!starter_rng_failure(result).empty()){ + return "Expected a settled shiny to let the story go on."; + } + result.settled = false; + if (starter_rng_failure(result).empty()){ + return "Expected a shiny that did not settle (the game is mid-scene) to stop the story."; + } + for (const StarterRngOutcome outcome : {StarterRngOutcome::ABANDONED, StarterRngOutcome::OUT_OF_RESETS}){ + StarterRngRunResult failed; + failed.outcome = outcome; + failed.resets_used = 3; + if (starter_rng_failure(failed).empty()){ + return "Expected a run with no starter to stop the story."; + } + } + return true; +} + +// A failed Run Starter RNG ends the program: 00.02's row retry would rerun +// the whole reset loop. Without it no row is fatal on top of the table's. +UnitTestResult test_starter_rng_row_is_fatal(Logger&){ + const std::vector& table = story_checkpoints(); + const StoryRunPlan in_program = plan_story_run( + table, 0, 3, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::RUN} + ); + if (in_program.fatal_rows != std::set{"00.02"}){ + return "Expected 00.02 to be fatal when Run Starter RNG in AutoStory is on."; + } + const StoryRunPlan plain = plan_story_run(table, 0, 3, StoryHandoffs{.starter_rng = Pokemon::RngHandoffMode::STOP}); + const StoryRunPlan off = plan_story_run(table, 0, 3); + if (!plain.fatal_rows.empty() || !off.fatal_rows.empty()){ + return "Expected no fatal rows unless Run Starter RNG in AutoStory is on."; + } + return true; +} + struct AutoStoryStoryTableInput{ std::string name; @@ -283,6 +443,26 @@ const AutoStoryStoryTableCase AUTO_STORY_STORY_TABLE_CASES[] = { .input = {"Route 204 North: the line into Floaroma", test_route204_north_line}, .expectation = {}, }, + { + .input = {"Starter RNG handoff: stops after 00.01 saved at the Verity Lakefront", test_plan_story_run_starter_rng}, + .expectation = {}, + }, + { + .input = {"Run Starter RNG: 00.02 runs the starter_rng event", test_plan_story_run_in_program}, + .expectation = {}, + }, + { + .input = {"Run Starter RNG: settings come from the story's options", test_starter_rng_settings}, + .expectation = {}, + }, + { + .input = {"Run Starter RNG: what lets the story go on", test_starter_rng_failure}, + .expectation = {}, + }, + { + .input = {"Run Starter RNG: a failed 00.02 ends the program", test_starter_rng_row_is_fatal}, + .expectation = {}, + }, }; void add_tests_AutoStory_StoryTable(UnitTestDatabase& database){ diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.cpp new file mode 100644 index 0000000000..2e11e5261b --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.cpp @@ -0,0 +1,77 @@ +/* BDSP RNG Aim + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "PokemonBDSP_RngAim.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +uint64_t aimed_advance(uint64_t press, uint64_t span, int64_t bias){ + int64_t advance = (int64_t)(press + span) + bias; + return advance < 0 ? 0 : (uint64_t)advance; +} + +int64_t press_for_advance(uint64_t target, uint64_t span, int64_t bias){ + return (int64_t)target - (int64_t)span - bias; +} + + +RngAim::RngAim(size_t minimum_samples, double threshold) + : m_minimum_samples(minimum_samples) + , m_threshold(threshold) +{} + +void RngAim::reset(){ + m_bias = 0; + m_offsets.clear(); +} + +bool RngAim::record_offset(Logger& logger, int64_t offset, bool enabled){ + m_offsets.emplace_back(offset); + if (!enabled || m_offsets.size() < m_minimum_samples){ + return false; + } + double mean = 0; + for (int64_t o : m_offsets){ + mean += (double)o; + } + mean /= (double)m_offsets.size(); + if (std::abs(mean) < m_threshold){ + return false; + } + int64_t shift = (int64_t)std::llround(mean); + if (shift == 0){ + return false; + } + m_bias += shift; + logger.log( + std::to_string(m_offsets.size()) + " measured attempt(s) average " + + tostr_fixed(mean, 2) + " advance(s) off, so the aim shifts by " + + std::to_string(shift) + " to " + std::to_string(m_bias) + ".", + COLOR_BLUE + ); + m_offsets.clear(); + return true; +} + +std::string RngAim::describe_correction() const{ + if (m_bias == 0){ + return ""; + } + return ", plus " + std::to_string(m_bias) + " measured"; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.h new file mode 100644 index 0000000000..608f448315 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.h @@ -0,0 +1,52 @@ +/* BDSP RNG Aim + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngAim_H +#define PokemonAutomation_PokemonBDSP_RngAim_H + +#include +#include +#include +#include + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// The advance where a press will generate the target Pokemon +uint64_t aimed_advance(uint64_t press, uint64_t span, int64_t bias); + +// The press that would reach "target" through a schedule of a certain length +int64_t press_for_advance(uint64_t target, uint64_t span, int64_t bias); + + +class RngAim{ +public: + explicit RngAim(size_t minimum_samples = 3, double threshold = 1.0); + + int64_t bias() const{ return m_bias; } + + void reset(); + + bool record_offset(Logger& logger, int64_t offset, bool enabled); + + std::string describe_correction() const; + +private: + size_t m_minimum_samples; + double m_threshold; + + int64_t m_bias = 0; + std::vector m_offsets; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.cpp new file mode 100644 index 0000000000..1e427daf5a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.cpp @@ -0,0 +1,188 @@ +/* BDSP RNG Calibration + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonBDSP_RngCalibration.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +NatureAdjustment bdsp_nature_adjustment(uint8_t nature, size_t stat_index){ + if (nature >= 25 || stat_index >= 5){ + return NatureAdjustment::NEUTRAL; + } + size_t raised = nature / 5; + size_t lowered = nature % 5; + if (raised == lowered){ + // Hardy, Docile, Serious, Bashful, Quirky. + return NatureAdjustment::NEUTRAL; + } + if (stat_index == raised){ + return NatureAdjustment::POSITIVE; + } + if (stat_index == lowered){ + return NatureAdjustment::NEGATIVE; + } + return NatureAdjustment::NEUTRAL; +} + + +// The nature index orders stats [Atk, Def, Spe, SpA, SpD]; +static const size_t NATURE_INDEX_ATTACK = 0; +static const size_t NATURE_INDEX_DEFENSE = 1; +static const size_t NATURE_INDEX_SPEED = 2; +static const size_t NATURE_INDEX_SPATK = 3; +static const size_t NATURE_INDEX_SPDEF = 4; + + +StatReads bdsp_expected_stats( + const BdspPokemonResult& generated, + const BaseStats& base_stats, + uint8_t level +){ + StatReads ret; + ret.hp = (int16_t)calc_stats_hp(base_stats.hp, level, generated.ivs.hp, 0); + ret.attack = (int16_t)calc_stats_nonhp( + base_stats.attack, level, generated.ivs.attack, 0, + bdsp_nature_adjustment(generated.nature, NATURE_INDEX_ATTACK) + ); + ret.defense = (int16_t)calc_stats_nonhp( + base_stats.defense, level, generated.ivs.defense, 0, + bdsp_nature_adjustment(generated.nature, NATURE_INDEX_DEFENSE) + ); + ret.spatk = (int16_t)calc_stats_nonhp( + base_stats.spatk, level, generated.ivs.spatk, 0, + bdsp_nature_adjustment(generated.nature, NATURE_INDEX_SPATK) + ); + ret.spdef = (int16_t)calc_stats_nonhp( + base_stats.spdef, level, generated.ivs.spdef, 0, + bdsp_nature_adjustment(generated.nature, NATURE_INDEX_SPDEF) + ); + ret.speed = (int16_t)calc_stats_nonhp( + base_stats.speed, level, generated.ivs.speed, 0, + bdsp_nature_adjustment(generated.nature, NATURE_INDEX_SPEED) + ); + return ret; +} + + +bool advances_between( + const Xorshift128State& from, + const Xorshift128State& to, + uint64_t search_max, + uint64_t& advances +){ + Xorshift128 rng(from); + for (uint64_t c = 0; c <= search_max; c++){ + if (rng.state() == to){ + advances = c; + return true; + } + rng.next(); + } + return false; +} + + +const BaseStats& starter_base_stats(BdspStarter starter){ + // Order: HP, Atk, Def, SpA, SpD, Spe. + static const BaseStats TURTWIG {55, 68, 64, 45, 55, 31}; + static const BaseStats CHIMCHAR{44, 58, 44, 58, 44, 61}; + static const BaseStats PIPLUP {53, 51, 53, 61, 56, 40}; + switch (starter){ + case BdspStarter::Turtwig: return TURTWIG; + case BdspStarter::Chimchar: return CHIMCHAR; + case BdspStarter::Piplup: return PIPLUP; + } + return TURTWIG; +} + + +// A reading of -1 was not taken, so it rules nothing out. +static bool stat_fits(int16_t observed, int16_t expected){ + return observed < 0 || observed == expected; +} + + +bool consistent_with( + const BdspPokemonResult& generated, + const BdspObservedStarter& observed +){ + if (observed.nature != NatureCheckerValue::UnableToDetect + && bdsp_nature_to_checker_value(generated.nature) != observed.nature + ){ + return false; + } + if (observed.gender_known && generated.gender != observed.gender){ + return false; + } + if (observed.shiny_known && (generated.shiny != BdspShiny::None) != observed.shiny){ + return false; + } + + StatReads expected = bdsp_expected_stats(generated, observed.base_stats, observed.level); + return stat_fits(observed.stats.hp, expected.hp) + && stat_fits(observed.stats.attack, expected.attack) + && stat_fits(observed.stats.defense, expected.defense) + && stat_fits(observed.stats.spatk, expected.spatk) + && stat_fits(observed.stats.spdef, expected.spdef) + && stat_fits(observed.stats.speed, expected.speed); +} + + +BdspHitIdentification identify_hit_advance( + const Xorshift128State& state, + const BdspStaticTemplate& tmpl, + uint64_t intended_advance, + uint64_t radius, + const BdspObservedStarter& observed +){ + BdspHitIdentification ret; + + uint64_t first = intended_advance > radius ? intended_advance - radius : 0; + uint64_t last = intended_advance + radius; + + BdspStaticSearcher searcher(state, tmpl, 0); + + std::vector matches = searcher.scan( + first, last, + [&](const BdspPokemonResult& candidate){ return consistent_with(candidate, observed); } + ); + ret.candidates = matches.size(); + + if (ret.candidates == 0){ + ret.failure_reason = "no advance within " + std::to_string(radius) + + " of " + std::to_string(intended_advance) + + " produces that Pokemon. Either the recovered state was wrong, or the press " + "missed by more than the search covered."; + return ret; + } + if (ret.candidates > 1){ + ret.failure_reason = std::to_string(ret.candidates) + + " advances fit what was read ("; + for (size_t c = 0; c < matches.size(); c++){ + ret.failure_reason += (c == 0 ? "" : ", ") + std::to_string(matches[c].advances); + } + ret.failure_reason += "), so which one was hit cannot be told apart here."; + return ret; + } + + ret.success = true; + ret.advance = matches[0].advances; + ret.offset = (int64_t)ret.advance - (int64_t)intended_advance; + return ret; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.h new file mode 100644 index 0000000000..8687e695de --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.h @@ -0,0 +1,79 @@ +/* BDSP RNG Calibration + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngCalibration_H +#define PokemonAutomation_PokemonBDSP_RngCalibration_H + +#include +#include +#include "Pokemon/Pokemon_BdspRng.h" +#include "Pokemon/Pokemon_NatureChecker.h" +#include "Pokemon/Pokemon_StatsCalculation.h" +#include "PokemonBDSP_StarterNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +Pokemon::NatureAdjustment bdsp_nature_adjustment(uint8_t nature, size_t stat_index); + +Pokemon::StatReads bdsp_expected_stats( + const Pokemon::BdspPokemonResult& generated, + const Pokemon::BaseStats& base_stats, + uint8_t level +); + +struct BdspObservedStarter{ + Pokemon::NatureCheckerValue nature = Pokemon::NatureCheckerValue::UnableToDetect; + Pokemon::BdspGender gender = Pokemon::BdspGender::Genderless; + bool gender_known = false; + Pokemon::StatReads stats; + Pokemon::BaseStats base_stats; + uint8_t level = 5; + bool shiny = false; + bool shiny_known = false; +}; + + +struct BdspHitIdentification{ + bool success = false; + uint64_t advance = 0; + int64_t offset = 0; + size_t candidates = 0; + std::string failure_reason; +}; + + +BdspHitIdentification identify_hit_advance( + const Pokemon::Xorshift128State& state, + const Pokemon::BdspStaticTemplate& tmpl, + uint64_t intended_advance, + uint64_t radius, + const BdspObservedStarter& observed +); + + +bool advances_between( + const Pokemon::Xorshift128State& from, + const Pokemon::Xorshift128State& to, + uint64_t search_max, + uint64_t& advances +); + + +const Pokemon::BaseStats& starter_base_stats(BdspStarter starter); + +bool consistent_with( + const Pokemon::BdspPokemonResult& generated, + const BdspObservedStarter& observed +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.cpp new file mode 100644 index 0000000000..6827c5a889 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.cpp @@ -0,0 +1,130 @@ +/* BDSP RNG Execution + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/PrettyPrint.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP_RngExecution.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +static size_t first_free_blink(const BdspTimelineContext& timeline){ + size_t before_blinks = 1 + (timeline.plus_one_on_menu_close ? 1 : 0) + + timeline.advance_delay + timeline.pokemon_models; + size_t last_waited = before_blinks + timeline.advance_delay_2_after_events - 1; + return last_waited + 1 + timeline.advance_delay_2; +} + + +static size_t timeline_depth(const BdspTimelineContext& timeline, size_t max_schedules){ + return first_free_blink(timeline) + 4 * max_schedules + 2; +} + +void schedule_span_bounds( + const BdspTimelineContext& timeline, size_t max_schedules, + uint64_t& lowest, uint64_t& highest +){ + lowest = first_free_blink(timeline) + 1 + timeline.advances_after_accept; + highest = timeline_depth(timeline, max_schedules) - 1 + timeline.advances_after_accept; +} + + +std::vector schedule_presses( + const Pokemon::Xorshift128State& state, + const BdspTimelineContext& timeline, + const NavigationTimings& timings, + uint64_t press, + size_t max_schedules +){ + std::vector schedules; + + size_t first_free = first_free_blink(timeline); + size_t last_waited = first_free - 1 - timeline.advance_delay_2; + + Pokemon::Xorshift128 rng(state); + rng.advance(press); + BdspTimelineResult simulated = simulate_timeline( + rng, timeline, timeline_depth(timeline, max_schedules) + ); + const std::vector& at = simulated.advance_times; + if (at.size() < first_free + 2){ + return schedules; + } + + // The second press goes between the last blink it waits for and the next. + double starly = (at[last_waited] + at[last_waited + 1]) / 2; + if (starly < timings.ready_seconds){ + return schedules; + } + double earliest_select = starly + timings.move_seconds; + + for (size_t blink = first_free; + blink + 1 < at.size() && schedules.size() < max_schedules; + blink++ + ){ + double gap_start = at[blink]; + double gap_end = at[blink + 1]; + + // Centred in the gap when there is room, pushed as late as the navigation + // demands when there is not. + double select_at = std::max( + (gap_start + gap_end - timings.prompt_seconds) / 2, earliest_select + ); + double confirm_at = select_at + timings.prompt_seconds; + if (select_at - gap_start < timings.guard_seconds + || gap_end - confirm_at < timings.guard_seconds + ){ + continue; + } + + schedules.push_back(PressSchedule{ + /*span*/ blink + 1 + timeline.advances_after_accept, + /*starly_seconds*/ starly, + /*select_seconds*/ select_at, + /*confirm_seconds*/ confirm_at, + /*blinks_before_confirm*/ blink + 1 - first_free, + }); + } + + return schedules; +} + + +bool wait_until_moment(ProControllerContext& context, Logger& logger, WallClock when){ + context.wait_for_all_requests(); + + WallClock now = current_time(); + if (when < now){ + double late = std::chrono::duration_cast>( + now - when + ).count(); + logger.log( + "The moment passed " + tostr_fixed(late, 3) + " seconds ago. " + "Abandoning the attempt rather than starting late.", + COLOR_ORANGE + ); + return false; + } + + Milliseconds wait = std::chrono::duration_cast(when - now); + pbf_wait(context, wait); + logger.log("Waiting " + std::to_string(wait.count()) + " ms for the timeline.", + COLOR_BLUE); + return true; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.h new file mode 100644 index 0000000000..c5ab0d7ebe --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.h @@ -0,0 +1,59 @@ +/* BDSP RNG Execution + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngExecution_H +#define PokemonAutomation_PokemonBDSP_RngExecution_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "PokemonBDSP_RngTimeline.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +struct PressSchedule{ + uint64_t span = 0; + double starly_seconds = 0; + double select_seconds = 0; + double confirm_seconds = 0; + uint64_t blinks_before_confirm = 0; +}; + +struct NavigationTimings{ + double ready_seconds = 0; + double move_seconds = 0; + double prompt_seconds = 0; + double guard_seconds = 0.30; +}; + + +void schedule_span_bounds( + const BdspTimelineContext& timeline, size_t max_schedules, + uint64_t& lowest, uint64_t& highest +); + +std::vector schedule_presses( + const Pokemon::Xorshift128State& state, + const BdspTimelineContext& timeline, + const NavigationTimings& timings, + uint64_t press, + size_t max_schedules +); + + +bool wait_until_moment(ProControllerContext& context, Logger& logger, WallClock when); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.cpp new file mode 100644 index 0000000000..b0d9785d0a --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.cpp @@ -0,0 +1,155 @@ +/* BDSP RNG Targets + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "PokemonBDSP_RngTargets.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +static BdspStaticTemplate starter_template(){ + BdspStaticTemplate ret; + ret.species = "starter"; + ret.level = 5; + ret.guaranteed_ivs = 0; + ret.ability_kind = 3; + ret.gender_ratio = 31; // Seven males to one female. + return ret; +} + +static BdspStaticTemplate legendary_template(const char* species, uint8_t level){ + BdspStaticTemplate ret; + ret.species = species; + ret.level = level; + ret.guaranteed_ivs = 3; + ret.ability_kind = 3; + ret.gender_ratio = 255; // Genderless. + return ret; +} + + +static const BdspRngTargetInfo& target_table(BdspRngTarget target){ + static const BdspRngTargetInfo STARTER{ + "starter", "Starter", + starter_template(), + BdspTimelineContext{ + /*npcs*/ 0, + /*pokemon_models*/ 2, + /*white_delay_seconds*/ 0.0, + /*advance_delay*/ 41, + /*advance_delay_2*/ 48, + /*advance_delay_2_after_events*/ 10, + /*plus_one_on_menu_close*/ false, + /*advances_after_accept*/ 65, + }, + /*observation_npcs*/ 2, + /*has_timeline*/ true, + }; + + static const BdspRngTargetInfo DIALGA{ + "dialga", "Dialga", + legendary_template("dialga", 47), + BdspTimelineContext{1, 1, 2.0, 0, 0, 10, false}, + /*observation_npcs*/ 1, + /*has_timeline*/ true, + }; + static const BdspRngTargetInfo PALKIA{ + "palkia", "Palkia", + legendary_template("palkia", 47), + BdspTimelineContext{1, 1, 2.0, 0, 0, 10, false}, + 1, true, + }; + + static const BdspRngTargetInfo GIRATINA{ + "giratina", "Giratina", + legendary_template("giratina", 47), + BdspTimelineContext{1, 1, 2.0, 2, 0, 10, false}, + 1, true, + }; + + static const BdspRngTargetInfo REGIROCK{ + "regirock", "Regirock", + legendary_template("regirock", 30), + BdspTimelineContext{1, 1, 3.0, 3, 0, 10, false}, + 1, true, + }; + static const BdspRngTargetInfo REGICE{ + "regice", "Regice", + legendary_template("regice", 30), + BdspTimelineContext{1, 1, 3.0, 3, 0, 10, false}, + 1, true, + }; + static const BdspRngTargetInfo REGISTEEL{ + "registeel", "Registeel", + legendary_template("registeel", 30), + BdspTimelineContext{1, 1, 3.0, 3, 0, 10, false}, + 1, true, + }; + + static const BdspRngTargetInfo CRESSELIA{ + "cresselia", "Cresselia", + [](){ + BdspStaticTemplate ret = legendary_template("cresselia", 50); + ret.gender_ratio = 254; // Always female. + ret.roamer = true; + return ret; + }(), + BdspTimelineContext{}, + 1, false, + }; + + static const BdspRngTargetInfo TRAINER_ID{ + "trainer-id", "Trainer ID / SID", + BdspStaticTemplate{}, + BdspTimelineContext{}, + /*observation_npcs*/ 0, + /*has_timeline*/ false, + }; + + switch (target){ + case BdspRngTarget::Starter: return STARTER; + case BdspRngTarget::Dialga: return DIALGA; + case BdspRngTarget::Palkia: return PALKIA; + case BdspRngTarget::Giratina: return GIRATINA; + case BdspRngTarget::Regirock: return REGIROCK; + case BdspRngTarget::Regice: return REGICE; + case BdspRngTarget::Registeel: return REGISTEEL; + case BdspRngTarget::Cresselia: return CRESSELIA; + case BdspRngTarget::TrainerId: return TRAINER_ID; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RNG target."); +} + +const BdspRngTargetInfo& bdsp_rng_target_info(BdspRngTarget target){ + return target_table(target); +} + + +const EnumDropdownDatabase& BdspRngTarget_Database(){ + static const EnumDropdownDatabase database{ + {BdspRngTarget::Starter, "starter", "Starter"}, + {BdspRngTarget::Dialga, "dialga", "Dialga"}, + {BdspRngTarget::Palkia, "palkia", "Palkia"}, + {BdspRngTarget::Giratina, "giratina", "Giratina"}, + {BdspRngTarget::Regirock, "regirock", "Regirock"}, + {BdspRngTarget::Regice, "regice", "Regice"}, + {BdspRngTarget::Registeel, "registeel", "Registeel"}, + {BdspRngTarget::Cresselia, "cresselia", "Cresselia"}, + {BdspRngTarget::TrainerId, "trainer-id", "Trainer ID / SID"}, + }; + return database; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.h new file mode 100644 index 0000000000..f3f557f881 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.h @@ -0,0 +1,52 @@ +/* BDSP RNG Targets + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngTargets_H +#define PokemonAutomation_PokemonBDSP_RngTargets_H + +#include +#include +#include "Common/Cpp/Options/EnumDropdownDatabase.h" +#include "Pokemon/Pokemon_BdspRng.h" +#include "PokemonBDSP_RngTimeline.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +enum class BdspRngTarget{ + Starter, + Dialga, + Palkia, + Giratina, + Regirock, + Regice, + Registeel, + Cresselia, + TrainerId, +}; + + +struct BdspRngTargetInfo{ + const char* slug; + const char* display_name; + Pokemon::BdspStaticTemplate pokemon; + BdspTimelineContext timeline; + uint8_t observation_npcs; + bool has_timeline; +}; + + +const BdspRngTargetInfo& bdsp_rng_target_info(BdspRngTarget target); + +const EnumDropdownDatabase& BdspRngTarget_Database(); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.cpp new file mode 100644 index 0000000000..99d0dfee73 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.cpp @@ -0,0 +1,140 @@ +/* BDSP RNG Timeline + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "PokemonBDSP_BlinkModel.h" +#include "PokemonBDSP_RngTimeline.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +namespace{ + +enum class TimelineEventType : uint8_t{ + NpcTick = 0, + PokemonBlink = 1, +}; + +struct TimelineEvent{ + double time_seconds; + TimelineEventType type; + uint8_t index; + + // Member order is the tie-break + auto operator<=>(const TimelineEvent&) const = default; +}; + +using TimelineQueue = std::priority_queue< + TimelineEvent, std::vector, std::greater +>; + +} + + +static void spend_advances( + BdspTimelineResult& result, Xorshift128& rng, + double now_seconds, uint64_t count +){ + for (uint64_t c = 0; c < count; c++){ + rng.next(); + result.advance_times.emplace_back(now_seconds); + } +} + + +BdspTimelineResult simulate_timeline( + Xorshift128 rng, + const BdspTimelineContext& context, + uint64_t max_advances +){ + BdspTimelineResult result; + double now = 0.0; + + spend_advances(result, rng, now, 1); + if (context.plus_one_on_menu_close){ + spend_advances(result, rng, now, 1); + } + + now += context.white_delay_seconds; + + spend_advances(result, rng, now, context.advance_delay); + + TimelineQueue queue; + for (uint8_t c = 0; c < context.npcs; c++){ + queue.push(TimelineEvent{now + BDSP_NPC_TICK_SECONDS, TimelineEventType::NpcTick, c}); + } + for (uint8_t c = 0; c < context.pokemon_models; c++){ + double interval = bdsp_pokemon_blink_interval(rng.next()); + result.advance_times.emplace_back(now); + queue.push(TimelineEvent{now + interval, TimelineEventType::PokemonBlink, c}); + } + + uint64_t events_handled = 0; + bool second_delay_spent = false; + + while (result.advance_times.size() < max_advances){ + if (queue.empty()){ + result.end_state = rng.state(); + return result; + } + + TimelineEvent event = queue.top(); + queue.pop(); + now = event.time_seconds; + + if (context.advance_delay_2 != 0 + && !second_delay_spent + && events_handled >= context.advance_delay_2_after_events + ){ + spend_advances(result, rng, now, context.advance_delay_2); + second_delay_spent = true; + } + + switch (event.type){ + case TimelineEventType::NpcTick: + rng.next(); + result.advance_times.emplace_back(now); + event.time_seconds += BDSP_NPC_TICK_SECONDS; + break; + + case TimelineEventType::PokemonBlink: + event.time_seconds += bdsp_pokemon_blink_interval(rng.next()); + result.advance_times.emplace_back(now); + break; + } + + queue.push(event); + events_handled++; + } + + result.end_state = rng.state(); + result.reached_target = true; + return result; +} + + +bool time_of_advance(const BdspTimelineResult& result, uint64_t advance, double& seconds){ + if (advance >= result.advance_times.size()){ + return false; + } + seconds = result.advance_times[(size_t)advance]; + return true; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.h new file mode 100644 index 0000000000..17bfffa6c7 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.h @@ -0,0 +1,57 @@ +/* BDSP RNG Timeline + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RngTimeline_H +#define PokemonAutomation_PokemonBDSP_RngTimeline_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Pokemon/Pokemon_Xorshift128.h" +#include "PokemonBDSP_BlinkModel.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +struct BdspTimelineContext{ + uint8_t npcs = 1; + uint8_t pokemon_models = 0; + double white_delay_seconds = 0; + uint32_t advance_delay = 0; + uint32_t advance_delay_2 = 0; + uint32_t advance_delay_2_after_events = 10; + bool plus_one_on_menu_close = false; + uint32_t advances_after_accept = 0; +}; + + +struct BdspTimelineResult{ + std::vector advance_times; + Pokemon::Xorshift128State end_state; + bool reached_target = false; + uint64_t advances() const{ return advance_times.size(); } + double duration_seconds() const{ + return advance_times.empty() ? 0.0 : advance_times.back(); + } +}; + + +BdspTimelineResult simulate_timeline( + Pokemon::Xorshift128 rng, + const BdspTimelineContext& context, + uint64_t max_advances +); + +bool time_of_advance(const BdspTimelineResult& result, uint64_t advance, double& seconds); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.cpp new file mode 100644 index 0000000000..e1eb1da88e --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.cpp @@ -0,0 +1,255 @@ +/* BDSP Starter Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h" +#include "PokemonBDSP_StarterNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +const Milliseconds AFTER_BRIEFCASE = 4000ms; +const Milliseconds PRE_BRIEFCASE_DURATION = 18200ms; +const Milliseconds PROMPT_ANIMATION = 1000ms; +const Milliseconds SCHEDULING_SLACK = 100ms; + + +uint8_t starter_cursor_steps(BdspStarter starter){ + switch (starter){ + case BdspStarter::Turtwig: return 0; + case BdspStarter::Chimchar: return 1; + case BdspStarter::Piplup: return 2; + } + return 0; +} + +const char* starter_slug(BdspStarter starter){ + switch (starter){ + case BdspStarter::Turtwig: return "turtwig"; + case BdspStarter::Chimchar: return "chimchar"; + case BdspStarter::Piplup: return "piplup"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown starter."); +} + +// behind the house to the north +void navigate_bedroom_to_skip_spot(Logger& logger, ProControllerContext& context){ + logger.log("Leaving the bedroom for the spot where advances pass quickly."); + pbf_mash_button(context, BUTTON_B, 1000ms); // exit dialogue with the Switch + pbf_wait(context, 1000ms); + pbf_press_dpad(context, DPAD_RIGHT, 1200ms, 1500ms); + pbf_press_dpad(context, DPAD_DOWN, 2300ms, 500ms); + pbf_press_dpad(context, DPAD_LEFT, 1100ms, 1000ms); + pbf_press_dpad(context, DPAD_DOWN, 750ms, 4000ms); + pbf_press_dpad(context, DPAD_LEFT, 850ms, 1000ms); + pbf_press_dpad(context, DPAD_UP, 4100ms, 1000ms); + pbf_press_dpad(context, DPAD_RIGHT, 950ms, 500ms); + context.wait_for_all_requests(); +} + + +void navigate_skip_spot_to_lakefront(Logger& logger, ProControllerContext& context){ + logger.log("Walking from the skip spot to the lakefront."); + pbf_press_dpad(context, DPAD_LEFT, 1350ms, 500ms); + pbf_press_dpad(context, DPAD_UP, 5000ms, 0ms); + + // Clearing the dialogue with Barry + pbf_mash_button(context, BUTTON_B, 5000ms); + pbf_wait(context, 1000ms); + + pbf_press_dpad(context, DPAD_UP, 600ms, 1000ms); + pbf_press_dpad(context, DPAD_LEFT, 8500ms, 1000ms); + pbf_press_dpad(context, DPAD_UP, 1950ms, 1000ms); + context.wait_for_all_requests(); +} + + +void navigate_to_lake_blinks(Logger& logger, ProControllerContext& context){ + logger.log("Walking into the lake, then advancing to the lake blink position."); + pbf_move_left_joystick(context, {0.0, 1.0}, 1600ms, 0ms); + + pbf_wait(context, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 4000ms); + pbf_press_button(context, BUTTON_A, 100ms, 2000ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 2500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 5500ms); + pbf_press_button(context, BUTTON_A, 100ms, 4500ms); + pbf_press_button(context, BUTTON_A, 100ms, 0ms); + context.wait_for_all_requests(); +} + +void navigate_to_pre_briefcase(Logger& logger, ProControllerContext& context){ + logger.log("Advancing to the pre-briefcase position."); + + // total duration equal to PRE_BRIEFCASE_DURATION (above) + pbf_wait(context, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 3500ms); + pbf_press_button(context, BUTTON_A, 100ms, 2000ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 1500ms); + pbf_press_button(context, BUTTON_A, 100ms, 5500ms); + pbf_press_button(context, BUTTON_A, 100ms, 2000ms); + pbf_press_button(context, BUTTON_A, 100ms, 0ms); + context.wait_for_all_requests(); +} + + +const Milliseconds BRIEFCASE_PRESS_TO_STARLY_READY = + 80ms + AFTER_BRIEFCASE + 100ms; +const Milliseconds SELECT_PRESS_TO_CONFIRM_READY = + 80ms + PROMPT_ANIMATION + 100ms + 200ms; + +static Milliseconds starly_press_to_select_ready(BdspStarter starter){ + return 80ms + 5500ms + 100ms + 1200ms + + starter_cursor_steps(starter) * (100ms + 600ms); +} + + +// The whole blind button press sequence +bool issue_starter_sequence( + ProControllerContext& context, + BdspStarter starter, + double starly_seconds, + double select_seconds, + double confirm_seconds, + std::string& failure_reason +){ + auto to_ms = [](double seconds){ + return std::chrono::duration_cast( + std::chrono::duration(seconds) + ); + }; + + // Where the run stands after each fixed stretch, + // measured from the moment the briefcase press is completed + Milliseconds starly_at = to_ms(starly_seconds); + Milliseconds select_at = to_ms(select_seconds); + Milliseconds confirm_at = to_ms(confirm_seconds); + Milliseconds after_dialog = BRIEFCASE_PRESS_TO_STARLY_READY; + Milliseconds after_starly = starly_at + starly_press_to_select_ready(starter); + Milliseconds after_select = select_at + SELECT_PRESS_TO_CONFIRM_READY; + + auto too_tight = [&](const char* what, Milliseconds needed, Milliseconds have){ + failure_reason = std::string(what) + " is scheduled " + + std::to_string((needed - have).count()) + + " ms before the navigation ahead of it can finish"; + return false; + }; + if (starly_at < after_dialog){ + return too_tight("the Starly press", after_dialog, starly_at); + } + if (select_at < after_starly){ + return too_tight("the selecting press", after_starly, select_at); + } + if (confirm_at < after_select){ + return too_tight("the confirming press", after_select, confirm_at); + } + + // The briefcase press + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + + // Past the briefcase dialogue + pbf_wait(context, AFTER_BRIEFCASE); + pbf_press_button(context, BUTTON_A, 100ms, 0ms); + + // The Starly press + pbf_wait(context, starly_at - after_dialog); + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + + // Open the briefcase and hover over the chosen ball + pbf_wait(context, 5500ms); + pbf_press_button(context, BUTTON_A, 100ms, 0ms); + pbf_wait(context, 1200ms); + for (uint8_t c = 0; c < starter_cursor_steps(starter); c++){ + pbf_press_dpad(context, DPAD_RIGHT, 100ms, 600ms); + } + + // The selecting press, then the cursor onto "Yes" + pbf_wait(context, select_at - after_starly); + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + pbf_wait(context, PROMPT_ANIMATION); + pbf_press_dpad(context, DPAD_UP, 100ms, 200ms); + + // The confirming press + pbf_wait(context, confirm_at - after_select); + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + + // battle start + pbf_wait(context, 3000ms); + pbf_press_button(context, BUTTON_A, 100ms, 0ms); + + context.wait_for_all_requests(); + return true; +} + + +// Where the blind run leaves off. Feedback-driven, since nothing past the +// confirming press is timed against the RNG. +bool clear_starter_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.log("Mashing A through the battle."); + EndBattleWatcher battle_over; + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 180s); + }, + {{battle_over}} + ); + if (ret < 0){ + env.log("The battle never ended.", COLOR_RED); + return false; + } + env.log("Battle over."); + return true; +} + + +double seconds_to_move_to_starter(BdspStarter starter){ + return std::chrono::duration_cast>( + starly_press_to_select_ready(starter) - 80ms + ).count(); +} + +// kept as short as the prompt animation allows to avoid extra blinks from the starter +double seconds_from_select_to_confirm(){ + return std::chrono::duration_cast>( + SELECT_PRESS_TO_CONFIRM_READY + SCHEDULING_SLACK + ).count(); +} + + +double seconds_to_pre_briefcase(){ + return std::chrono::duration_cast>( + PRE_BRIEFCASE_DURATION + ).count(); +} + + +double seconds_from_briefcase_to_starly_ready(){ + return std::chrono::duration_cast>( + BRIEFCASE_PRESS_TO_STARLY_READY + ).count(); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.h new file mode 100644 index 0000000000..dacda12b65 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.h @@ -0,0 +1,102 @@ +/* BDSP Starter Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_StarterNavigation_H +#define PokemonAutomation_PokemonBDSP_StarterNavigation_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +enum class BdspStarter{ + Turtwig, + Chimchar, + Piplup, +}; + + +uint8_t starter_cursor_steps(BdspStarter starter); +const char* starter_slug(BdspStarter starter); + + +// Measured over 14 attempts spanning 40k to 734k advances, +/-0.01% +const double BDSP_SKIP_ADVANCES_PER_MINUTE = 19653; + +// Measured over the same attempts, +/-29 +const double BDSP_SKIP_NAVIGATION_ADVANCES = 6902; + +// How far short of the target to stop quickly skipping advances +const double BDSP_SKIP_BUFFER_BASE = 750; +const double BDSP_SKIP_BUFFER_PER_ADVANCE = 0.0002; +inline uint64_t bdsp_skip_buffer(double advances_skipped){ + return (uint64_t)(BDSP_SKIP_BUFFER_BASE + BDSP_SKIP_BUFFER_PER_ADVANCE * advances_skipped); +} + + +const double BDSP_SKIP_RATE_SIGMA = 0.0001; +const double BDSP_SKIP_SCATTER_SIGMA = 67; +inline double bdsp_skip_landing_sigma(double advances_skipped){ + double from_rate = BDSP_SKIP_RATE_SIGMA * advances_skipped; + return std::sqrt(from_rate * from_rate + BDSP_SKIP_SCATTER_SIGMA * BDSP_SKIP_SCATTER_SIGMA); +} + + +inline uint64_t bdsp_lake_advances_needed(double advances_skipped){ + return bdsp_skip_buffer(advances_skipped) + + (uint64_t)(2 * bdsp_skip_landing_sigma(advances_skipped)); +} + + +void navigate_bedroom_to_skip_spot(Logger& logger, ProControllerContext& context); + +void navigate_skip_spot_to_lakefront(Logger& logger, ProControllerContext& context); + + +void navigate_to_lake_blinks(Logger& logger, ProControllerContext& context); + +void navigate_to_pre_briefcase(Logger& logger, ProControllerContext& context); + + +bool issue_starter_sequence( + ProControllerContext& context, + BdspStarter starter, + double starly_seconds, + double select_seconds, + double confirm_seconds, + std::string& failure_reason +); + + +// Mash A until the battle with the wild Starly is over. +bool clear_starter_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +double seconds_to_move_to_starter(BdspStarter starter); + + +double seconds_from_select_to_confirm(); + + +double seconds_from_briefcase_to_starly_ready(); + + +double seconds_to_pre_briefcase(); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp new file mode 100644 index 0000000000..1d19e14261 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp @@ -0,0 +1,207 @@ +/* BDSP Starter RNG + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/Inference/Rng/PokemonBDSP_SummaryReader.h" +#include "PokemonBDSP_StarterRng.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +const size_t CALIBRATION_MIN_SAMPLES = 3; +const double CALIBRATION_THRESHOLD = 1.0; + + +StarterRng_Descriptor::StarterRng_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:StarterRng", + STRING_POKEMON + " BDSP", "Starter RNG", + "", + "Starter RNG manipulation using blinks.", + PanelQualityStanding::OFFICIAL_BETA, + ProgramControllerClass::StandardController_RequiresPrecision, + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS + ) +{} + +std::unique_ptr StarterRng_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +StarterRng::StarterRng() + : m_aim(CALIBRATION_MIN_SAMPLES, CALIBRATION_THRESHOLD) + , LANGUAGE( + "Game Language:", + summary_nature_languages(), + LockMode::LOCK_WHILE_RUNNING, true + ) + , START_POINT( + "Start point:
" + "Where you have saved your game. Starting from the bedroom allows the possibility to skip advances quickly.", + { + {BdspStartPoint::Lakefront, "lakefront", "Verity Lakefront"}, + {BdspStartPoint::Bedroom, "bedroom", "Bedroom"}, + }, + LockMode::LOCK_WHILE_RUNNING, + BdspStartPoint::Lakefront + ) + , STARTER( + "Starter:
", + { + {BdspStarter::Turtwig, "turtwig", "Turtwig"}, + {BdspStarter::Chimchar, "chimchar", "Chimchar"}, + {BdspStarter::Piplup, "piplup", "Piplup"}, + }, + LockMode::LOCK_WHILE_RUNNING, + BdspStarter::Turtwig + ) + , FILTERS( + "Stop Conditions:
" + "If the " + STRING_POKEMON + " matches any one of these filters, the program will " + "stop.
", + StatsHuntMiscFeatureFlags{ + /*action*/ false, /*shiny*/ true, /*gender*/ true, /*nature*/ true + } + ) + , COLLECTION_DISPLAY(true) + , MAX_RESETS( + "Maximum resets:
" + "Set this to zero to keep going until a shiny is caught.", + LockMode::LOCK_WHILE_RUNNING, + 0, 0, 1000 + ) + , MAX_TARGET_WAIT_MINUTES( + "Wait at most (minutes) for a target:
" + "Time limit for waiting at Verity Lake. Rarer targets will require longer " + "wait times.", + LockMode::LOCK_WHILE_RUNNING, + 30, 5, 1440 + ) + , MAX_SKIP_MINUTES( + "Skip at most (minutes):
" + "Time limit for skipping advances in Twinleaf Town.", + LockMode::LOCK_WHILE_RUNNING, + 30, 5, 1440 + ) + , AUTO_CALIBRATE( + "Correct the timing automatically:
" + "Shift the target advances when several attempts miss.", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , USE_SOUND_DETECTION( + "Use sound detection:", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , TAKE_VIDEO( + "Take Video:
" + "Record a video when the shiny is found.", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_SHINY( + "Shiny Starter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + set_default_shiny_row(FILTERS); + + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(PLAYER_MODEL); + PA_ADD_OPTION(START_POINT); + PA_ADD_OPTION(STARTER); + PA_ADD_OPTION(FILTERS); + PA_ADD_OPTION(COLLECTION_DISPLAY); + PA_ADD_OPTION(STATE_DISPLAY); + PA_ADD_OPTION(TARGET_DISPLAY); + PA_ADD_OPTION(MAX_RESETS); + PA_ADD_OPTION(MAX_TARGET_WAIT_MINUTES); + PA_ADD_OPTION(MAX_SKIP_MINUTES); + PA_ADD_OPTION(AUTO_CALIBRATE); + PA_ADD_OPTION(USE_SOUND_DETECTION); + PA_ADD_OPTION(TAKE_VIDEO); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); + + START_POINT.add_listener(*this); + StarterRng::on_config_value_changed(this); +} + + +void StarterRng::on_config_value_changed(void*){ + MAX_SKIP_MINUTES.set_visibility( + START_POINT == BdspStartPoint::Bedroom + ? ConfigOptionState::ENABLED + : ConfigOptionState::HIDDEN + ); +} + + +void StarterRng::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + StarterRng_Descriptor::Stats& stats = env.current_stats(); + + require_player(env.console, context, BUTTON_B); + + m_aim.reset(); + + BdspRngFilterSnapshot filters = FILTERS.make_snapshot(); + StarterRngSettings settings{ + .language = LANGUAGE, + .player_model = PLAYER_MODEL.model_number(), + .start_point = START_POINT, + .starter = STARTER, + .wanted = [&filters](const BdspPokemonResult& result){ + return starter_wanted(filters, result); + }, + .filters = &filters, + .max_resets = MAX_RESETS, + .max_target_wait_minutes = MAX_TARGET_WAIT_MINUTES, + .max_skip_minutes = MAX_SKIP_MINUTES, + .auto_calibrate = AUTO_CALIBRATE, + .use_sound_detection = USE_SOUND_DETECTION, + .take_video = TAKE_VIDEO, + .reset_first = false, + .finish_battle_on_shiny = false, + .close_summary_after_read = false, + }; + StarterRngAttemptIO io{ + .collection_display = &COLLECTION_DISPLAY, + .state_display = &STATE_DISPLAY, + .target_display = &TARGET_DISPLAY, + .notification_shiny = &NOTIFICATION_SHINY, + .notification_error = &NOTIFICATION_ERROR_RECOVERABLE, + .stats = &stats, + }; + + run_starter_rng_attempts(env, context, settings, io, m_aim); + + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h new file mode 100644 index 0000000000..ba081486b2 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h @@ -0,0 +1,82 @@ +/* BDSP Starter RNG + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_StarterRng_H +#define PokemonAutomation_PokemonBDSP_StarterRng_H + +#include +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "PokemonBDSP/Options/PokemonBDSP_PlayerModelOption.h" +#include "PokemonBDSP/Options/PokemonBDSP_RngFilter.h" +#include "PokemonBDSP_RngAim.h" +#include "PokemonBDSP_RngDisplays.h" +#include "PokemonBDSP_StarterNavigation.h" +#include "PokemonBDSP_StarterRngAttempts.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class StarterRng_Descriptor : public SingleSwitchProgramDescriptor{ +public: + StarterRng_Descriptor(); + + using Stats = StarterRngStats; + virtual std::unique_ptr make_stats() const override; +}; + + +class StarterRng : public SingleSwitchProgramInstance, public ConfigOption::Listener{ +public: + using Descriptor = StarterRng_Descriptor; + StarterRng(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + virtual void on_config_value_changed(void* object) override; + +private: + RngAim m_aim; + +private: + OCR::LanguageOCROption LANGUAGE; + PlayerModelOption PLAYER_MODEL; + EnumDropdownOption START_POINT; + EnumDropdownOption STARTER; + + BdspRngFilterTable FILTERS; + + BlinkCollectionDisplay COLLECTION_DISPLAY; + RngStateDisplay STATE_DISPLAY; + RngTargetDisplay TARGET_DISPLAY; + + SimpleIntegerOption MAX_RESETS; + SimpleIntegerOption MAX_TARGET_WAIT_MINUTES; + SimpleIntegerOption MAX_SKIP_MINUTES; + + BooleanCheckBoxOption AUTO_CALIBRATE; + + BooleanCheckBoxOption USE_SOUND_DETECTION; + BooleanCheckBoxOption TAKE_VIDEO; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp new file mode 100644 index 0000000000..472708f58f --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp @@ -0,0 +1,767 @@ +/* BDSP Starter RNG Attempts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" +#include "Pokemon/Pokemon_NatureChecker.h" +#include "Pokemon/Pokemon_Notification.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Inference/Rng/PokemonBDSP_BlinkScenes.h" +#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" +#include "PokemonBDSP_BlinkRecovery.h" +#include "PokemonBDSP_RngCalibration.h" +#include "PokemonBDSP_RngExecution.h" +#include "PokemonBDSP_RngTargets.h" +#include "PokemonBDSP_RngTimeline.h" +#include "PokemonBDSP_StarterRngAttempts.h" +#include "PokemonBDSP_SummaryNavigation.h" +#include "PokemonBDSP_TargetSelection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +namespace{ + +const size_t LAKE_BLINKS_PRESS_RETRIES = 10; + +const double GAP_GUARD_SECONDS = 0.30; + +const uint64_t HIT_SEARCH_RADIUS = 20; +const size_t MAX_SCHEDULES = 8; + +const uint64_t SKIP_ARRIVAL_OVERSHOOT_ALLOWANCE = 200000; + + +std::function resolve_wanted_predicate( + const StarterRngSettings& settings +){ + if (settings.wanted){ + return settings.wanted; + } + if (settings.filters != nullptr){ + const BdspRngFilterSnapshot* filters = settings.filters; + return [filters](const BdspPokemonResult& result){ + return starter_wanted(*filters, result); + }; + } + return [](const BdspPokemonResult& result){ + return result.shiny != BdspShiny::None; + }; +} + + +BdspSkipResult skip_advances_from_bedroom( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const StarterRngSettings& settings, + const std::function& wanted_fn, + BlinkCollectionDisplay& collection_display, + RngStateDisplay& state_display, + RngTargetDisplay& target_display +){ + BdspSkipResult skip; + const BdspRngTargetInfo& target_info = bdsp_rng_target_info(BdspRngTarget::Starter); + + // Expected wait duration at the lake after a long skip + double longest_skip = settings.max_skip_minutes * BDSP_SKIP_ADVANCES_PER_MINUTE; + double lake_minutes = bdsp_lake_advances_needed(longest_skip) + * BDSP_NPC_TICK_SECONDS / (target_info.observation_npcs * 60.0); + if (lake_minutes > settings.max_target_wait_minutes){ + throw UserSetupError(env.logger(), + "A skip of up to " + std::to_string(settings.max_skip_minutes) + + " minutes can leave up to " + + tostr_fixed(lake_minutes, 1) + " minutes of waiting at the lake, but the target " + "wait is capped at " + std::to_string(settings.max_target_wait_minutes) + + ". Raise the target wait to at least " + + std::to_string((uint16_t)std::ceil(lake_minutes)) + + " minutes, or lower the skip limit." + ); + } + + env.log("Starting in the bedroom."); + pbf_press_button(context, BUTTON_A, 100ms, 2000ms); // open dialogue box + context.wait_for_all_requests(); + + std::vector setups = bedroom_eye_templates(settings.player_model); + std::vector eyes = load_eye_templates(setups); + + std::vector> watchers; + std::vector callbacks; + make_blink_watchers(setups, eyes, watchers, callbacks); + + BlinkRecoveryConfig bedroom_config; + bedroom_config.npcs = 1; + + BlinkRecovery recovery = recover_state_from_blinks( + env, context, watchers, callbacks, collection_display, bedroom_config + ); + if (!recovery.success){ + skip.failure_reason = "could not determine the RNG state in the bedroom: " + + recovery.failure_reason; + return skip; + } + skip.state = recovery.state; + env.log("Bedroom RNG state: " + recovery.state.to_string(), COLOR_BLUE); + state_display.set_state(recovery.state, recovery.clock.anchor_advance); + state_display.set_confidence_unique(); + + // take into account remaining navigation time and the desired buffer + uint64_t soonest = recovery.clock.advance_at(current_time()) + + (uint64_t)BDSP_SKIP_NAVIGATION_ADVANCES + bdsp_skip_buffer(0); + uint64_t furthest = soonest + + (uint64_t)(settings.max_skip_minutes * BDSP_SKIP_ADVANCES_PER_MINUTE); + + BdspStaticSearcher searcher(recovery.state, target_info.pokemon, 0); + std::vector hits = searcher.scan( + soonest, furthest, + wanted_fn, + true, &context + ); + if (hits.empty()){ + skip.failure_reason = "no target within " + std::to_string(settings.max_skip_minutes) + + " minutes of skipping"; + return skip; + } + const BdspRngHit& hit = hits[0]; + skip.target_advance = hit.advances; + target_display.set_target(hit.result, hit.advances); + + uint64_t start = recovery.clock.advance_at(current_time()); + + // The buffer depends on how far the skip runs, so size it from the raw distance. + double raw_skip = (double)hit.advances - (double)start - BDSP_SKIP_NAVIGATION_ADVANCES; + uint64_t buffer = bdsp_skip_buffer(raw_skip); + double to_skip = raw_skip - (double)buffer; + if (to_skip < 0){ + to_skip = 0; + } + double wait_seconds = to_skip * 60 / BDSP_SKIP_ADVANCES_PER_MINUTE; + skip.buffer = buffer; + + env.log("Target advance " + std::to_string(hit.advances) + ": " + hit.result.to_string(), + COLOR_BLUE); + env.log("Skipping " + std::to_string((uint64_t)to_skip) + " advances from " + + std::to_string(start) + ", which is " + tostr_fixed(wait_seconds, 1) + + "s on the spot, stopping " + std::to_string(buffer) + + " advances short to avoid overshooting.", COLOR_BLUE); + + navigate_bedroom_to_skip_spot(env.logger(), context); + + WallClock leave_at = current_time() + std::chrono::duration_cast( + std::chrono::duration(wait_seconds) + ); + + while (current_time() + 2s < leave_at){ + WallClock now = current_time(); + WallClock until = std::min(leave_at - 2s, now + 180s); + pbf_wait(context, std::chrono::duration_cast(until - now)); + context.wait_for_all_requests(); + } + WallClock now = current_time(); + if (now < leave_at){ + pbf_wait(context, std::chrono::duration_cast(leave_at - now)); + context.wait_for_all_requests(); + } + + navigate_skip_spot_to_lakefront(env.logger(), context); + skip.success = true; + return skip; +} + + +void report_skip_arrival( + SingleSwitchProgramEnvironment& env, + const BdspSkipResult& skip, + const BlinkRecovery& arrival +){ + // Generous enough to catch an overshoot, and a match is unique anyway. + uint64_t search_max = skip.target_advance + SKIP_ARRIVAL_OVERSHOOT_ALLOWANCE; + uint64_t travelled = 0; + if (!advances_between(skip.state, arrival.state, search_max, travelled)){ + env.log( + "Could not place the lake state against the bedroom one, so the skip " + "cannot be measured this attempt.", + COLOR_ORANGE + ); + return; + } + + uint64_t here = travelled + arrival.clock.advance_at(current_time()); + int64_t short_by = (int64_t)skip.target_advance - (int64_t)here; + env.log( + "Skip landed on advance " + std::to_string(here) + " of " + + std::to_string(skip.target_advance) + ": " + + (short_by >= 0 + ? std::to_string(short_by) + " short, aimed for " + std::to_string(skip.buffer) + : "OVERSHOT by " + std::to_string(-short_by)), + short_by >= 0 ? COLOR_BLUE : COLOR_ORANGE + ); +} + +} // namespace + + +StarterRngStats::StarterRngStats() + : resets(m_stats["Resets"]) + , missed(m_stats["Missed"]) + , hits(m_stats["Hit"]) + , shinies(m_stats["Shiny"]) + , errors(m_stats["Errors"]) +{ + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back(Stat("Missed", HIDDEN_IF_ZERO)); + m_display_order.emplace_back(Stat("Hit", HIDDEN_IF_ZERO)); + m_display_order.emplace_back(Stat("Shiny", HIDDEN_IF_ZERO)); + m_display_order.emplace_back(Stat("Errors", HIDDEN_IF_ZERO)); +} + + +bool starter_wanted( + const BdspRngFilterSnapshot& filters, + const BdspPokemonResult& pokemon +){ + auto exactly = [](uint8_t iv){ + return IvRange{(int8_t)iv, (int8_t)iv}; + }; + IvRanges ivs; + ivs.hp = exactly(pokemon.ivs.hp); + ivs.attack = exactly(pokemon.ivs.attack); + ivs.defense = exactly(pokemon.ivs.defense); + ivs.spatk = exactly(pokemon.ivs.spatk); + ivs.spdef = exactly(pokemon.ivs.spdef); + ivs.speed = exactly(pokemon.ivs.speed); + + StatsHuntGenderFilter gender = StatsHuntGenderFilter::Genderless; + switch (pokemon.gender){ + case BdspGender::Male: + gender = StatsHuntGenderFilter::Male; + break; + case BdspGender::Female: + gender = StatsHuntGenderFilter::Female; + break; + default: + break; + } + + return filters.get_action( + pokemon.shiny != BdspShiny::None, + gender, + bdsp_nature_to_checker_value(pokemon.nature), + pokemon.height, + ivs + ) != StatsHuntAction::Discard; +} + + +bool resolve_starter_rng_step( + const BdspStarterAttemptResult& attempt, + uint64_t resets_used, + uint16_t max_resets, + StarterRngRunResult& result +){ + result.resets_used = resets_used; + if (attempt.target_advance != 0){ + result.target = attempt.target; + result.target_advance = attempt.target_advance; + } + if (!attempt.failure_reason.empty()){ + result.last_failure_reason = attempt.failure_reason; + } + + if (attempt.outcome == BdspAttemptOutcome::Hit){ + result.settled = attempt.settled; + result.outcome = attempt.shiny + ? StarterRngOutcome::SHINY + : StarterRngOutcome::HIT; + return true; + } + + if (max_resets != 0 && resets_used >= max_resets){ + result.outcome = attempt.outcome == BdspAttemptOutcome::Abandoned + ? StarterRngOutcome::ABANDONED + : StarterRngOutcome::OUT_OF_RESETS; + return true; + } + + return false; +} + + +// Leaves the game as the settings ask after a shiny: battle finished and, if +// asked, the starter summary read and the menu closed. False if a step failed. +static bool settle_after_shiny( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, const StarterRngSettings& settings +){ + if (!settings.finish_battle_on_shiny){ + return true; + } + if (!clear_starter_battle(env, context)){ + return false; + } + if (settings.close_summary_after_read){ + if (!open_menu(env, context)){ + return false; + } + pbf_press_button(context, BUTTON_X, 160ms, 1000ms); + context.wait_for_all_requests(); + env.log("Closed the menu."); + } + return true; +} + +BdspStarterAttemptResult run_starter_rng_attempt( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const StarterRngSettings& settings, + const StarterRngAttemptIO& io, + RngAim& aim +){ + BlinkCollectionDisplay fallback_collection(true); + RngStateDisplay fallback_state; + RngTargetDisplay fallback_target; + + BlinkCollectionDisplay& collection_display = io.collection_display != nullptr + ? *io.collection_display + : fallback_collection; + RngStateDisplay& state_display = io.state_display != nullptr + ? *io.state_display + : fallback_state; + RngTargetDisplay& target_display = io.target_display != nullptr + ? *io.target_display + : fallback_target; + + collection_display.reset(); + state_display.reset(); + target_display.reset(); + + auto record_miss = [&](){ + if (io.stats != nullptr){ + io.stats->missed++; + } + if (io.on_miss){ + io.on_miss(); + } + }; + auto record_hit = [&](){ + if (io.stats != nullptr){ + io.stats->hits++; + } + if (io.on_hit){ + io.on_hit(); + } + }; + auto record_shiny = [&](){ + if (io.stats != nullptr){ + io.stats->shinies++; + } + if (io.on_shiny){ + io.on_shiny(); + } + }; + auto record_error = [&](){ + if (io.stats != nullptr){ + io.stats->errors++; + } + if (io.on_error){ + io.on_error(); + } + }; + + auto abandon = [&](const std::string& reason) -> BdspStarterAttemptResult{ + env.log("Abandoning this attempt: " + reason, COLOR_ORANGE); + target_display.set_note(reason); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Abandoned, + .failure_reason = reason, + }; + }; + + std::function wanted_fn = resolve_wanted_predicate(settings); + const BdspRngTargetInfo& target_info = bdsp_rng_target_info(BdspRngTarget::Starter); + + BdspSkipResult skip; + if (settings.start_point == BdspStartPoint::Bedroom){ + skip = skip_advances_from_bedroom( + env, context, settings, wanted_fn, + collection_display, state_display, target_display + ); + if (!skip.success){ + return abandon(skip.failure_reason); + } + } + + navigate_to_lake_blinks(env.logger(), context); + + std::vector setups = lake_eye_templates(settings.player_model); + std::vector eyes = load_eye_templates(setups); + + // The rival's dialogue box being up is what says the pair have stopped walking. + ShortDialogDetector dialog; + BlinkSceneConfig scene; + scene.frame_filter = [&dialog](const ImageViewRGB32& frame){ + return dialog.detect(frame); + }; + scene.press_retries = LAKE_BLINKS_PRESS_RETRIES; + + if (!wait_for_blink_scene(env, context, setups, eyes, scene, "Lake blinks")){ + return abandon("never reached the lake blink position"); + } + + // Now blink watchers can be created safely + std::vector> watchers; + std::vector callbacks; + make_blink_watchers(setups, eyes, watchers, callbacks); + + BlinkRecoveryConfig blink_config; + blink_config.npcs = target_info.observation_npcs; + + BlinkRecovery recovery = recover_state_from_blinks( + env, context, watchers, callbacks, collection_display, blink_config + ); + if (!recovery.success){ + return abandon("could not determine the RNG state: " + recovery.failure_reason); + } + + uint64_t seed0 = 0; + uint64_t seed1 = 0; + xorshift128_state_to_seed_pair(recovery.state, seed0, seed1); + env.log("RNG state: " + recovery.state.to_string(), COLOR_BLUE); + env.log("PokeFinder seeds: " + tostr_hex_padded(16, seed0) + + " " + tostr_hex_padded(16, seed1), COLOR_BLUE); + env.log("Tick fitted at " + tostr_default(recovery.clock.tick_seconds) + "s over " + + std::to_string(recovery.events) + " rolls.", COLOR_BLUE); + env.log("Anchored on advance " + std::to_string(recovery.clock.anchor_advance) + + "; now at advance " + std::to_string(recovery.clock.advance_at(current_time())) + + ".", COLOR_BLUE); + state_display.set_state(recovery.state, recovery.clock.anchor_advance); + state_display.set_confidence_unique(); + + if (skip.success){ + report_skip_arrival(env, skip, recovery); + } + + const BdspTimelineContext& timeline = target_info.timeline; + + NavigationTimings timings; + timings.ready_seconds = seconds_from_briefcase_to_starly_ready(); + timings.move_seconds = seconds_to_move_to_starter(settings.starter) + 0.25; // small buffer + timings.prompt_seconds = seconds_from_select_to_confirm(); + timings.guard_seconds = GAP_GUARD_SECONDS; + + BdspStaticSearcher searcher(recovery.state, target_info.pokemon, 0); + + // A press cannot be sooner than the walk to the pre-briefcase position takes + double lead_seconds = seconds_to_pre_briefcase() + 15; + uint64_t lead_advances = (uint64_t)( + lead_seconds * recovery.clock.npcs / recovery.clock.tick_seconds + ) + 1; + + TargetSearchRequest search; + search.state = recovery.state; + search.timeline = timeline; + search.timings = timings; + search.pokemon = target_info.pokemon; + search.npcs = recovery.clock.npcs; + search.tick_seconds = recovery.clock.tick_seconds; + search.bias = aim.bias(); + search.first_press = recovery.clock.advance_at(current_time()) + lead_advances; + search.window_advances = (uint64_t)( + (double)settings.max_target_wait_minutes * 60 * recovery.clock.npcs / recovery.clock.tick_seconds + ); + search.max_schedules = MAX_SCHEDULES; + search.wanted = wanted_fn; + + TargetSelectionResult selection = select_target(search); + + if (selection.matches_found != 0){ + env.log( + std::to_string(selection.matches_found) + " matching advance(s) in " + + std::to_string(selection.advances_scanned), + COLOR_BLUE + ); + } + if (!selection.success){ + return abandon(selection.failure_reason); + } + + uint64_t press_advance = selection.press_advance; + uint64_t target_advance = selection.target_advance; + const PressSchedule& schedule = selection.schedule; + const BdspPokemonResult& target = selection.target; + + double wait_seconds = std::chrono::duration_cast>( + recovery.clock.time_of_advance(press_advance) - current_time() + ).count(); + env.log("Target advance " + std::to_string(target_advance) + ": " + target.to_string(), + COLOR_BLUE); + env.log("Pressing at advance " + std::to_string(press_advance) + ", in " + + tostr_default(wait_seconds) + "s.", COLOR_BLUE); + env.log("Schedule spans " + std::to_string(schedule.span) + " advances, confirming after " + + std::to_string(schedule.blinks_before_confirm) + " Starly blink(s), " + + tostr_default(schedule.confirm_seconds) + "s in" + + aim.describe_correction() + ".", COLOR_BLUE); + target_display.set_target(target, target_advance); + + hold_and_reanchor( + env, context, watchers, callbacks, recovery, blink_config, + press_advance, lead_seconds, state_display + ); + + navigate_to_pre_briefcase(env.logger(), context); + + // FIRST PRESS, centred in the advance rather than aimed right at the beginning of it + WallClock briefcase_time = recovery.clock.middle_of_advance(press_advance); + + while (current_time() + 3s < briefcase_time){ + state_display.set_advances(recovery.clock.advance_at(current_time())); + pbf_wait(context, 1000ms); + context.wait_for_all_requests(); + } + + state_display.set_advances(press_advance); + + env.log("Timeline starts at advance " + std::to_string(press_advance) + + ". Blind from here: Starly press at " + tostr_default(schedule.starly_seconds) + + "s, selecting at " + tostr_default(schedule.select_seconds) + + "s, confirming at " + tostr_default(schedule.confirm_seconds) + + "s, on advance " + std::to_string(target_advance - timeline.advances_after_accept) + + ".", COLOR_BLUE); + + std::string sequence_failure; + if (!wait_until_moment(context, env.logger(), briefcase_time)){ + return abandon("the briefcase press moment passed before it could be sent"); + } + if (!issue_starter_sequence( + context, settings.starter, + schedule.starly_seconds, schedule.select_seconds, schedule.confirm_seconds, + sequence_failure + )){ + return abandon(sequence_failure); + } + env.log("Timeline finished; the starter should be in hand.", COLOR_BLUE); + + state_display.set_advances(target_advance); + + // Check what was actually obtained. + DoublesShinyDetection wild; + ShinyDetectionResult own; + detect_shiny_battle( + env, env.console, context, + wild, own, + io.notification_error != nullptr ? *io.notification_error : EventNotificationOption_NOOP(), + YOUR_POKEMON, + 30s, + settings.use_sound_detection + ); + bool shiny_known = own.shiny_type != ShinyType::UNKNOWN; + + if (is_likely_shiny(own.shiny_type)){ + record_shiny(); + if (io.notification_shiny != nullptr){ + send_program_notification( + env, *io.notification_shiny, + COLOR_STAR_SHINY, "Shiny Starter", + {{"Advance", std::to_string(target_advance)}, {"Details", target.to_string()}}, + "", own.get_best_screenshot() + ); + } + if (settings.take_video){ + pbf_wait(context, 5000ms); + pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 5000ms); + context.wait_for_all_requests(); + } + const bool settled = settle_after_shiny(env, context, settings); + if (!settled){ + record_error(); + } + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = true, + .target = target, + .target_advance = target_advance, + .settled = settled, + }; + } + + BdspObservedStarter observed; + if (!clear_starter_battle(env, context) + || !read_observed_pokemon( + env, context, settings.language, + starter_base_stats(settings.starter), 5, false, shiny_known, observed + ) + ){ + record_error(); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Unverifiable, + .shiny = false, + .target = target, + .target_advance = target_advance, + .failure_reason = "could not verify the obtained starter", + }; + } + + if (settings.close_summary_after_read){ + if (!close_starter_summary(env, context)){ + record_error(); + } + } + + BdspHitIdentification hit = identify_hit_advance( + recovery.state, target_info.pokemon, target_advance, HIT_SEARCH_RADIUS, observed + ); + if (!hit.success){ + env.log("Could not tell which advance that was: " + hit.failure_reason, COLOR_ORANGE); + if (consistent_with(target, observed)){ + env.log("What was read matches the target, so it counts as a hit.", COLOR_BLUE); + record_hit(); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = false, + .target = target, + .target_advance = target_advance, + }; + } + env.log("What was read is not the target, so it counts as a miss.", COLOR_ORANGE); + record_miss(); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Missed, + .shiny = false, + .target = target, + .target_advance = target_advance, + .failure_reason = hit.failure_reason, + }; + } + if (aim.record_offset(env.logger(), hit.offset, settings.auto_calibrate)){ + target_display.set_correction(aim.bias()); + } + + if (hit.offset == 0){ + env.log("Landed on advance " + std::to_string(target_advance) + ", as aimed.", + COLOR_BLUE); + record_hit(); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = false, + .target = target, + .target_advance = target_advance, + }; + } + + env.log( + "Landed on advance " + std::to_string(hit.advance) + " instead of " + + std::to_string(target_advance) + " — " + + (hit.offset > 0 ? "late by " : "early by ") + + std::to_string(hit.offset > 0 ? hit.offset : -hit.offset) + " advance(s).", + COLOR_ORANGE + ); + record_miss(); + + BdspPokemonResult actual = searcher.generate(hit.advance); + if (wanted_fn(actual)){ + env.log("It passes the filter anyway, so this one will do. Stopping.", COLOR_BLUE); + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = false, + .target = actual, + .target_advance = hit.advance, + }; + } + return BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Missed, + .shiny = false, + .target = target, + .target_advance = target_advance, + }; +} + + +StarterRngRunResult run_starter_rng_attempts( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const StarterRngSettings& settings, + const StarterRngAttemptIO& io, + RngAim& aim +){ + StarterRngRunResult result; + bool reset = settings.reset_first; + uint64_t resets = 0; + BdspStarterAttemptResult last_attempt; + + while (true){ + if (settings.max_resets != 0 && resets >= settings.max_resets){ + env.log("Reached the reset limit.", COLOR_ORANGE); + resolve_starter_rng_step(last_attempt, resets, settings.max_resets, result); + break; + } + resets++; + + bool started = true; + if (reset){ + go_home(env.console, context); + if (!reset_game_from_home( + env, env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + )){ + started = false; + } + } + + if (started){ + reset = true; + last_attempt = run_starter_rng_attempt(env, context, settings, io, aim); + }else{ + last_attempt = BdspStarterAttemptResult{ + .outcome = BdspAttemptOutcome::Abandoned, + .failure_reason = "failed to reset the game from the Home screen", + }; + } + + if (io.stats != nullptr){ + io.stats->resets++; + } + if (io.on_reset){ + io.on_reset(); + } + env.update_stats(); + + if (last_attempt.outcome == BdspAttemptOutcome::Hit){ + resolve_starter_rng_step(last_attempt, resets, settings.max_resets, result); + break; + } + if (!last_attempt.failure_reason.empty()){ + result.last_failure_reason = last_attempt.failure_reason; + } + result.resets_used = resets; + if (last_attempt.target_advance != 0){ + result.target = last_attempt.target; + result.target_advance = last_attempt.target_advance; + } + } + + env.update_stats(); + return result; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h new file mode 100644 index 0000000000..1e88d9b277 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h @@ -0,0 +1,216 @@ +/* BDSP Starter RNG Attempts + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_StarterRngAttempts_H +#define PokemonAutomation_PokemonBDSP_StarterRngAttempts_H + +#include +#include +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Pokemon_BdspRng.h" +#include "Pokemon/Pokemon_Xorshift128.h" +#include "PokemonBDSP/Options/PokemonBDSP_RngFilter.h" +#include "PokemonBDSP_RngAim.h" +#include "PokemonBDSP_RngDisplays.h" +#include "PokemonBDSP_StarterNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +enum class BdspStartPoint{ + Lakefront, + Bedroom, +}; + + +struct BdspSkipResult{ + bool success = false; + Pokemon::Xorshift128State state; + uint64_t target_advance = 0; + uint64_t buffer = 0; + std::string failure_reason; +}; + + +enum class BdspAttemptOutcome{ + Abandoned, + Missed, + Hit, + Unverifiable, +}; + + +struct StarterRngStats : public StatsTracker{ + StarterRngStats(); + + std::atomic& resets; + std::atomic& missed; + std::atomic& hits; + std::atomic& shinies; + std::atomic& errors; +}; + + +// Evaluates whether a generated starter satisfies the filter snapshot. +// Takes a snapshot rather than the table because scanning millions of +// advances cannot afford cloning the table on every query. +bool starter_wanted( + const BdspRngFilterSnapshot& filters, + const Pokemon::BdspPokemonResult& pokemon +); + + +// Settings for a Starter RNG attempt loop. +// +// In-game state traversal after the starter is chosen and the wild Starly +// battle begins at Lake Verity: +// - Shiny hit (`Outcome::SHINY`): +// `detect_shiny_battle(...)` finishes at the start of the Starly battle. +// * When `finish_battle_on_shiny == false` (standalone `StarterRng` default): +// returns immediately while still inside the Starly battle at Lake Verity. +// * When `finish_battle_on_shiny == true` (for AutoStory): +// calls `clear_starter_battle(env, context)`, which mashes A until +// `EndBattleWatcher` detects the black-screen battle exit transition, and +// when `close_summary_after_read == true` also advances through Rowan's +// post-battle scene (`open_menu`) to `VerityLakefront (17, 14..15)` and +// closes the X menu so both `SHINY` and `HIT` end on the `VerityLakefront` +// overworld ready for checkpoint `00.03`. +// - Non-shiny starter (`clear_starter_battle` + `read_observed_pokemon`): +// 1. `clear_starter_battle(env, context)` mashes A until `EndBattleWatcher` +// detects the end of the Starly battle. +// 2. `read_observed_pokemon(...)` calls `open_menu(env, context)`, which +// mashes `B, B, X` until `MenuWatcher` detects the overworld X menu. +// Because the X menu cannot open during the post-battle Lake Verity +// cutscene or the warp out of the lake, `open_menu` advances through +// all of Rowan's and Barry's post-battle dialogue (`after_starly`) and +// the warp back to `VerityLakefront (17, 14..15)`, then opens the X menu +// once the player has overworld control on `VerityLakefront`. +// 3. `open_starter_summary(env, context)` selects `POKEMON` (one entry left +// on the 2-icon pre-Pokedex X menu), opens the starter's Summary screen, +// reads Nature & Gender on the 2nd tab (Trainer Memo), and presses Right +// to read the 6 stats on the 3rd tab (Skills/Stats). +// * When `close_summary_after_read == false` (standalone `StarterRng` default): +// leaves the game on the 3rd tab of the starter's Summary screen. +// * When `close_summary_after_read == true` (for AutoStory): +// calls `close_starter_summary(env, context)` after reading the summary, +// which presses B back to the X menu and X to close it, leaving the +// player standing on the `VerityLakefront` overworld at `(17, 14..15)` +// (with `after_starly` already completed, ready for checkpoint `00.03`). +struct StarterRngSettings{ + Language language = Language::English; + uint8_t player_model = 1; + BdspStartPoint start_point = BdspStartPoint::Lakefront; + BdspStarter starter = BdspStarter::Turtwig; + + // Predicate for target selection and hit verification. If `wanted` is + // empty and `filters` is non-null, `starter_wanted(*filters, ...)` is used. + std::function wanted; + const BdspRngFilterSnapshot* filters = nullptr; + + uint16_t max_resets = 0; + uint16_t max_target_wait_minutes = 30; + uint16_t max_skip_minutes = 30; + + bool auto_calibrate = true; + bool use_sound_detection = true; + bool take_video = true; + + bool reset_first = false; + bool finish_battle_on_shiny = false; + bool close_summary_after_read = false; +}; + + +struct StarterRngAttemptIO{ + BlinkCollectionDisplay* collection_display = nullptr; + RngStateDisplay* state_display = nullptr; + RngTargetDisplay* target_display = nullptr; + EventNotificationOption* notification_shiny = nullptr; + EventNotificationOption* notification_error = nullptr; + StarterRngStats* stats = nullptr; + + std::function on_reset; + std::function on_miss; + std::function on_hit; + std::function on_shiny; + std::function on_error; +}; + + +enum class StarterRngOutcome{ + HIT, + SHINY, + OUT_OF_RESETS, + ABANDONED, +}; + + +struct StarterRngRunResult{ + using Outcome = StarterRngOutcome; + using enum StarterRngOutcome; + + Outcome outcome = Outcome::ABANDONED; + Pokemon::BdspPokemonResult target{}; + uint64_t target_advance = 0; + uint64_t resets_used = 0; + std::string last_failure_reason; + // False when a shiny was caught but the game was not left where + // `finish_battle_on_shiny` and `close_summary_after_read` promise: the + // caller must not go on from it. + bool settled = true; +}; + + +struct BdspStarterAttemptResult{ + BdspAttemptOutcome outcome = BdspAttemptOutcome::Abandoned; + bool shiny = false; + Pokemon::BdspPokemonResult target{}; + uint64_t target_advance = 0; + std::string failure_reason; + // See StarterRngRunResult::settled. + bool settled = true; +}; + + +// Pure helper that maps the latest attempt result and reset count to a +// finished `StarterRngRunResult` when the loop should terminate, or returns +// `false` when the loop should continue to the next reset. +bool resolve_starter_rng_step( + const BdspStarterAttemptResult& attempt, + uint64_t resets_used, + uint16_t max_resets, + StarterRngRunResult& result +); + + +BdspStarterAttemptResult run_starter_rng_attempt( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const StarterRngSettings& settings, + const StarterRngAttemptIO& io, + RngAim& aim +); + + +StarterRngRunResult run_starter_rng_attempts( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const StarterRngSettings& settings, + const StarterRngAttemptIO& io, + RngAim& aim +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp new file mode 100644 index 0000000000..c561e57bc1 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp @@ -0,0 +1,362 @@ +/* BDSP Starter RNG Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonBDSP_RngAim.h" +#include "PokemonBDSP_RngCalibration.h" +#include "PokemonBDSP_StarterNavigation.h" +#include "PokemonBDSP_StarterRngAttempts.h" +#include "PokemonBDSP_StarterRng_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +namespace{ + +struct StarterTableRow{ + BdspStarter starter; + std::string slug; + uint8_t cursor_steps; + BaseStats base_stats; + double move_seconds; +}; + +const std::vector STARTER_TABLE_ROWS = { + { + .starter = BdspStarter::Turtwig, + .slug = "turtwig", + .cursor_steps = 0, + .base_stats = {55, 68, 64, 45, 55, 31}, + .move_seconds = 6.8, + }, + { + .starter = BdspStarter::Chimchar, + .slug = "chimchar", + .cursor_steps = 1, + .base_stats = {44, 58, 44, 58, 44, 61}, + .move_seconds = 7.5, + }, + { + .starter = BdspStarter::Piplup, + .slug = "piplup", + .cursor_steps = 2, + .base_stats = {53, 51, 53, 61, 56, 40}, + .move_seconds = 8.2, + }, +}; + + +UnitTestResult test_starter_tables(Logger&){ + for (const StarterTableRow& row : STARTER_TABLE_ROWS){ + const std::string got_slug = starter_slug(row.starter); + if (got_slug != row.slug){ + return std::format("starter_slug mismatch: got {}, expected {}", got_slug, row.slug); + } + const uint8_t got_steps = starter_cursor_steps(row.starter); + if (got_steps != row.cursor_steps){ + return std::format( + "starter_cursor_steps({}) = {}, expected {}", + row.slug, got_steps, row.cursor_steps + ); + } + const BaseStats& stats = starter_base_stats(row.starter); + if (stats.hp != row.base_stats.hp + || stats.attack != row.base_stats.attack + || stats.defense != row.base_stats.defense + || stats.spatk != row.base_stats.spatk + || stats.spdef != row.base_stats.spdef + || stats.speed != row.base_stats.speed + ){ + return std::format( + "starter_base_stats({}) = {}/{}/{}/{}/{}/{}, expected {}/{}/{}/{}/{}/{}", + row.slug, + stats.hp, stats.attack, stats.defense, stats.spatk, stats.spdef, stats.speed, + row.base_stats.hp, row.base_stats.attack, row.base_stats.defense, + row.base_stats.spatk, row.base_stats.spdef, row.base_stats.speed + ); + } + const double move_s = seconds_to_move_to_starter(row.starter); + if (std::abs(move_s - row.move_seconds) > 1e-9){ + return std::format( + "seconds_to_move_to_starter({}) = {}, expected {}", + row.slug, move_s, row.move_seconds + ); + } + } + return true; +} + + +UnitTestResult test_skip_buffer_and_landing_math(Logger&){ + if (bdsp_skip_buffer(0.0) != 750){ + return std::format("bdsp_skip_buffer(0) = {}, expected 750", bdsp_skip_buffer(0.0)); + } + if (bdsp_skip_buffer(100000.0) != 770){ + return std::format("bdsp_skip_buffer(100000) = {}, expected 770", bdsp_skip_buffer(100000.0)); + } + + const double sigma0 = bdsp_skip_landing_sigma(0.0); + if (std::abs(sigma0 - 67.0) > 1e-9){ + return std::format("bdsp_skip_landing_sigma(0) = {}, expected 67.0", sigma0); + } + + const uint64_t lake0 = bdsp_lake_advances_needed(0.0); + if (lake0 != 750 + 2 * 67){ + return std::format("bdsp_lake_advances_needed(0) = {}, expected {}", lake0, 750 + 2 * 67); + } + + // At 1,000,000 advances skipped: buffer = 750 + 200 = 950, + // sigma = sqrt(100^2 + 67^2) = sqrt(14489) ~ 120.37, 2*sigma = 240, total = 1190. + const uint64_t lake1m = bdsp_lake_advances_needed(1000000.0); + if (lake1m != 1190){ + return std::format("bdsp_lake_advances_needed(1e6) = {}, expected 1190", lake1m); + } + return true; +} + + +UnitTestResult test_aim_and_calibration(Logger& logger){ + if (aimed_advance(1000, 200, 0) != 1200){ + return "aimed_advance(1000, 200, 0) != 1200"; + } + if (aimed_advance(1000, 200, 3) != 1203){ + return "aimed_advance(1000, 200, 3) != 1203"; + } + if (press_for_advance(1203, 200, 3) != 1000){ + return "press_for_advance(1203, 200, 3) != 1000"; + } + + RngAim aim(3, 1.0); + if (aim.bias() != 0){ + return "initial bias != 0"; + } + if (aim.record_offset(logger, 2, true) || aim.record_offset(logger, 2, true)){ + return "should not adjust before 3 samples"; + } + if (!aim.record_offset(logger, 2, true)){ + return "expected adjustment on 3rd sample of +2"; + } + if (aim.bias() != 2){ + return std::format("bias after three +2 offsets = {}, expected 2", aim.bias()); + } + return true; +} + + +// A shiny whose post-battle scene did not finish still ends the loop (the +// shiny must not be reset away), and says so. +UnitTestResult test_shiny_unsettled(Logger&){ + BdspStarterAttemptResult shiny{ + .outcome = BdspAttemptOutcome::Hit, .shiny = true, .target_advance = 9, .settled = false + }; + StarterRngRunResult result; + if (!resolve_starter_rng_step(shiny, 1, 3, result) || result.outcome != StarterRngOutcome::SHINY){ + return "expected a shiny to end the loop"; + } + if (result.settled){ + return "expected the unsettled shiny to say that the game is not settled"; + } + shiny.settled = true; + StarterRngRunResult settled; + if (!resolve_starter_rng_step(shiny, 1, 3, settled) || !settled.settled){ + return "expected a settled shiny to be settled"; + } + return true; +} + +UnitTestResult test_attempt_loop_transitions(Logger&){ + BdspPokemonResult sample_target{}; + sample_target.ec = 0x12345678; + sample_target.pid = 0x87654321; + sample_target.nature = 3; + + // 1. Miss when below max_resets continues the loop. + { + StarterRngRunResult result; + BdspStarterAttemptResult miss{ + .outcome = BdspAttemptOutcome::Missed, + .shiny = false, + .target = sample_target, + .target_advance = 1500, + }; + if (resolve_starter_rng_step(miss, 1, 3, result)){ + return "expected loop to continue on miss 1 of 3"; + } + if (result.resets_used != 1 || result.target_advance != 1500){ + return "expected resets_used = 1 and target_advance = 1500 after miss"; + } + } + + // 2. Non-shiny hit stops with Outcome::HIT. + { + StarterRngRunResult result; + BdspStarterAttemptResult hit{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = false, + .target = sample_target, + .target_advance = 1505, + }; + if (!resolve_starter_rng_step(hit, 2, 3, result)){ + return "expected loop to terminate on non-shiny hit"; + } + if (result.outcome != StarterRngOutcome::HIT + || result.resets_used != 2 + || result.target_advance != 1505 + || result.target.pid != sample_target.pid + ){ + return "unexpected result fields on non-shiny hit"; + } + } + + // 3. Shiny hit stops with Outcome::SHINY. + { + StarterRngRunResult result; + BdspStarterAttemptResult shiny_hit{ + .outcome = BdspAttemptOutcome::Hit, + .shiny = true, + .target = sample_target, + .target_advance = 2048, + }; + if (!resolve_starter_rng_step(shiny_hit, 1, 0, result)){ + return "expected loop to terminate on shiny hit"; + } + if (result.outcome != StarterRngOutcome::SHINY + || result.resets_used != 1 + || result.target_advance != 2048 + ){ + return "unexpected result fields on shiny hit"; + } + } + + // 4. Miss reaching max_resets stops with Outcome::OUT_OF_RESETS. + { + StarterRngRunResult result; + BdspStarterAttemptResult miss{ + .outcome = BdspAttemptOutcome::Missed, + .shiny = false, + .target = sample_target, + .target_advance = 1600, + }; + if (!resolve_starter_rng_step(miss, 3, 3, result)){ + return "expected loop to terminate when resets_used == max_resets"; + } + if (result.outcome != StarterRngOutcome::OUT_OF_RESETS || result.resets_used != 3){ + return "expected OUT_OF_RESETS on miss at reset limit"; + } + } + + // 5. Abandoned attempt reaching max_resets stops with Outcome::ABANDONED and preserves reason. + { + StarterRngRunResult result; + BdspStarterAttemptResult abandoned{ + .outcome = BdspAttemptOutcome::Abandoned, + .shiny = false, + .failure_reason = "no matching target within the allowed wait time", + }; + if (!resolve_starter_rng_step(abandoned, 1, 1, result)){ + return "expected loop to terminate on abandoned single attempt"; + } + if (result.outcome != StarterRngOutcome::ABANDONED + || result.resets_used != 1 + || result.last_failure_reason != "no matching target within the allowed wait time" + ){ + return "expected ABANDONED with failure_reason preserved"; + } + } + + return true; +} + + +// The default filter row: a table that has it stops for a shiny of any +// nature and gender, and no other starter; an empty table never stops, which +// is why a caller must seed it. +UnitTestResult test_default_shiny_row(Logger&){ + BdspRngFilterTable empty("Filters", Pokemon::StatsHuntMiscFeatureFlags{false, true, true, true}); + BdspPokemonResult shiny{}; + shiny.shiny = BdspShiny::Star; + shiny.nature = 7; + BdspPokemonResult plain{}; + plain.nature = 7; + if (starter_wanted(empty.make_snapshot(), shiny)){ + return "an empty filter table must not match a shiny"; + } + + BdspRngFilterTable table("Filters", Pokemon::StatsHuntMiscFeatureFlags{false, true, true, true}); + set_default_shiny_row(table); + if (table.current_rows() != 1){ + return std::format("expected one default row, got {}", table.current_rows()); + } + const BdspRngFilterSnapshot snapshot = table.make_snapshot(); + if (!starter_wanted(snapshot, shiny)){ + return "the default row must match a shiny of any nature"; + } + shiny.nature = 20; + if (!starter_wanted(snapshot, shiny)){ + return "the default row must match a shiny of another nature"; + } + if (starter_wanted(snapshot, plain)){ + return "the default row must not match a non-shiny"; + } + return true; +} + + +struct StarterRngTestCase{ + std::string name; + std::function body; +}; + +class Test_StarterRng : public UnitTest{ +public: + explicit Test_StarterRng(StarterRngTestCase test_case) + : UnitTest("PokemonBDSP::StarterRng - " + test_case.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger& logger, CancellableScope&) const override{ + try{ + return m_case.body(logger); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + StarterRngTestCase m_case; +}; + +const StarterRngTestCase STARTER_RNG_CASES[] = { + {"per-starter tables and timings", test_starter_tables}, + {"bedroom skip buffer and landing math", test_skip_buffer_and_landing_math}, + {"aim offset and calibration bias", test_aim_and_calibration}, + {"attempt loop outcome resolution", test_attempt_loop_transitions}, + {"default filter row is shiny of any nature", test_default_shiny_row}, + {"a shiny that did not settle ends the loop unsettled", test_shiny_unsettled}, +}; + +} // namespace + + +void add_tests_StarterRng(UnitTestDatabase& database){ + for (const StarterRngTestCase& test_case : STARTER_RNG_CASES){ + database.add(test_case); + } +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h new file mode 100644 index 0000000000..be4c4fa2dd --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h @@ -0,0 +1,23 @@ +/* BDSP Starter RNG Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_StarterRng_Tests_H +#define PokemonAutomation_PokemonBDSP_StarterRng_Tests_H + +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +void add_tests_StarterRng(UnitTestDatabase& database); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp new file mode 100644 index 0000000000..3d9737b4ee --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp @@ -0,0 +1,185 @@ +/* BDSP Summary Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_NatureChecker.h" +#include "PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h" +#include "PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h" +#include "PokemonBDSP/Inference/Rng/PokemonBDSP_SummaryReader.h" +#include "PokemonBDSP_SummaryNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; + + +const size_t MENU_ATTEMPTS = 3; + + +bool open_menu(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.log("Mashing B through dialogue, trying the menu as we go."); + MenuWatcher menu(COLOR_RED, true); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + for (size_t c = 0; c < 40; c++){ + pbf_press_button(context, BUTTON_B, 100ms, 700ms); + pbf_press_button(context, BUTTON_B, 100ms, 700ms); + pbf_press_button(context, BUTTON_X, 100ms, 1200ms); + } + }, + {{menu}} + ); + if (ret < 0){ + env.log("Never got back to the overworld menu.", COLOR_RED); + return false; + } + env.log("Menu is open."); + return true; +} + + +bool open_starter_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + for (size_t attempt = 0; attempt < MENU_ATTEMPTS; attempt++){ + pbf_wait(context, 1200ms); + context.wait_for_all_requests(); + + env.log("Moving one entry left, then opening it."); + pbf_press_dpad(context, DPAD_LEFT, 160ms, 840ms); + pbf_press_button(context, BUTTON_A, 160ms, 1500ms); + + pbf_press_button(context, BUTTON_A, 100ms, 1000ms); + context.wait_for_all_requests(); + + SelectionArrowFinder arrow(env.console, {0.360, 0.110, 0.200, 0.290}, COLOR_RED); + if (wait_until(env.console, context, 10s, {{arrow}}) >= 0){ + break; + } + if (attempt + 1 >= MENU_ATTEMPTS){ + env.log("Never reached the party from the menu.", COLOR_RED); + return false; + } + env.log("That was not the party. Backing out and trying again.", COLOR_ORANGE); + bool back_at_menu = false; + for (size_t c = 0; c < 5 && !back_at_menu; c++){ + pbf_press_button(context, BUTTON_B, 160ms, 1000ms); + context.wait_for_all_requests(); + MenuWatcher menu(COLOR_RED, true); + back_at_menu = wait_until(env.console, context, 2s, {{menu}}) >= 0; + } + if (!back_at_menu){ + env.log("Backing out never returned to the menu.", COLOR_RED); + return false; + } + } + + env.log("Opening the summary."); + pbf_press_button(context, BUTTON_A, 100ms, 2000ms); + context.wait_for_all_requests(); + + env.log("Moving to the Trainer Memo page."); + pbf_press_dpad(context, DPAD_RIGHT, 100ms, 1500ms); + context.wait_for_all_requests(); + return true; +} + + +bool navigate_to_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + return open_menu(env, context) + && open_starter_summary(env, context); +} + + +bool close_starter_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.log("Backing out of the summary screen to the overworld."); + bool back_at_menu = false; + for (size_t c = 0; c < 6 && !back_at_menu; c++){ + pbf_press_button(context, BUTTON_B, 160ms, 1000ms); + context.wait_for_all_requests(); + MenuWatcher menu(COLOR_RED, true); + back_at_menu = wait_until(env.console, context, 2s, {{menu}}) >= 0; + } + if (!back_at_menu){ + env.log("Never returned to the X menu from the summary.", COLOR_ORANGE); + return false; + } + pbf_press_button(context, BUTTON_X, 160ms, 1000ms); + context.wait_for_all_requests(); + env.log("Closed the menu."); + return true; +} + + +bool read_observed_pokemon( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + Language language, + const Pokemon::BaseStats& base_stats, + uint8_t level, + bool shiny, + bool shiny_known, + BdspObservedStarter& observed +){ + if (!navigate_to_summary(env, context)){ + env.log("Could not reach the summary, so this attempt says nothing about timing.", + COLOR_ORANGE); + return false; + } + + SummaryReader reader; + + // 2nd page: nature and gender + { + VideoSnapshot memo = env.console.video().snapshot(); + observed.nature = reader.read_nature(env.logger(), language, memo); + Pokemon::BdspGender gender = reader.read_gender(env.logger(), memo); + observed.gender = gender; + observed.gender_known = gender != Pokemon::BdspGender::Genderless; + } + // 3rd page: stats + { + pbf_press_dpad(context, DPAD_RIGHT, 100ms, 1500ms); + context.wait_for_all_requests(); + VideoSnapshot skills = env.console.video().snapshot(); + observed.stats = reader.read_stats(env.logger(), skills); + } + observed.base_stats = base_stats; + observed.level = level; + observed.shiny = shiny; + observed.shiny_known = shiny_known; + + auto stat = [](int16_t value){ + return value < 0 ? std::string("?") : std::to_string(value); + }; + bool nature_read = observed.nature != Pokemon::NatureCheckerValue::UnableToDetect; + env.log( + "Read from the summary: nature " + + (nature_read + ? Pokemon::NATURE_CHECKER_VALUE_STRINGS().get_string(observed.nature) + : std::string("UNREAD")) + + ", gender " + + (observed.gender_known + ? std::string(Pokemon::bdsp_gender_name(observed.gender)) + : std::string("UNREAD")) + + ", stats " + stat(observed.stats.hp) + "/" + stat(observed.stats.attack) + + "/" + stat(observed.stats.defense) + "/" + stat(observed.stats.spatk) + + "/" + stat(observed.stats.spdef) + "/" + stat(observed.stats.speed) + ".", + nature_read && observed.gender_known ? COLOR_BLUE : COLOR_ORANGE + ); + return true; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h new file mode 100644 index 0000000000..0c1933c3d5 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h @@ -0,0 +1,44 @@ +/* BDSP Summary Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_SummaryNavigation_H +#define PokemonAutomation_PokemonBDSP_SummaryNavigation_H + +#include "CommonFramework/Language.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Pokemon_StatsCalculation.h" +#include "PokemonBDSP_RngCalibration.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +bool open_menu(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +bool open_starter_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +bool navigate_to_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +// Backs out of the Pokemon summary screen (3rd page -> party -> X menu -> overworld). +bool close_starter_summary(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +bool read_observed_pokemon( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + Language language, + const Pokemon::BaseStats& base_stats, + uint8_t level, + bool shiny, + bool shiny_known, + BdspObservedStarter& observed +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.cpp new file mode 100644 index 0000000000..39420aa7fc --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.cpp @@ -0,0 +1,122 @@ +/* BDSP Target Selection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "PokemonBDSP_RngAim.h" +#include "PokemonBDSP_TargetSelection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +TargetSelectionResult select_target(const TargetSearchRequest& request){ + TargetSelectionResult result; + + if (!request.wanted){ + result.failure_reason = "No filter was supplied, so nothing can be searched for."; + return result; + } + + BdspStaticSearcher searcher(request.state, request.pokemon, 0); + + // How many advances the scene can spend between the press and the generation + uint64_t lowest_span = 0; + uint64_t highest_span = 0; + schedule_span_bounds(request.timeline, request.max_schedules, lowest_span, highest_span); + + int64_t last_press = (int64_t)(request.first_press + request.window_advances); + + // One sweep, walking the RNG forward rather than jumping to each advance. + uint64_t scan_from = (uint64_t)std::max( + 0, (int64_t)request.first_press + (int64_t)lowest_span + request.bias + ); + uint64_t scan_to = (uint64_t)std::max( + 0, last_press + (int64_t)highest_span + request.bias + ); + std::map wanted_targets; + for (const BdspRngHit& hit : searcher.scan(scan_from, scan_to, request.wanted)){ + wanted_targets.emplace(hit.advances, hit.result); + } + + result.advances_scanned = scan_to - scan_from + 1; + result.matches_found = wanted_targets.size(); + + if (wanted_targets.empty()){ + result.failure_reason = "no matches found within " + + std::to_string(result.advances_scanned) + " advances."; + return result; + } + + uint8_t press_step = request.npcs == 0 ? 1 : request.npcs; + std::set candidate_presses; + for (const auto& item : wanted_targets){ + int64_t lowest_press = std::max( + press_for_advance(item.first, highest_span, request.bias), + (int64_t)request.first_press + ); + int64_t highest_press = std::min( + press_for_advance(item.first, lowest_span, request.bias), + last_press + ); + for (int64_t press = lowest_press; press <= highest_press; press++){ + if (press % press_step != 0){ + continue; + } + candidate_presses.insert((uint64_t)press); + } + } + + double seconds_per_advance = request.tick_seconds / (double)press_step; + bool found = false; + double best_seconds = 0; + for (uint64_t press : candidate_presses){ + double press_at_seconds = (double)(press - request.first_press) * seconds_per_advance; + if (found && press_at_seconds >= best_seconds){ + break; + } + for (const PressSchedule& option : schedule_presses( + request.state, request.timeline, request.timings, press, request.max_schedules + )){ + auto hit = wanted_targets.find(aimed_advance(press, option.span, request.bias)); + if (hit == wanted_targets.end()){ + continue; + } + if (!found || press_at_seconds + option.confirm_seconds < best_seconds){ + found = true; + best_seconds = press_at_seconds + option.confirm_seconds; + result.press_advance = press; + result.schedule = option; + result.target = hit->second; + } + // the first hit is the best this press has to offer + break; + } + } + if (!found){ + // Around one advance in fifty is unreachable due to rapid blinks + result.failure_reason = std::to_string(wanted_targets.size()) + + " matching advance(s) in range, but none reachable"; + return result; + } + + result.target_advance = aimed_advance( + result.press_advance, result.schedule.span, request.bias + ); + result.success = true; + return result; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.h new file mode 100644 index 0000000000..7c1fb044d0 --- /dev/null +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.h @@ -0,0 +1,57 @@ +/* BDSP Target Selection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_TargetSelection_H +#define PokemonAutomation_PokemonBDSP_TargetSelection_H + +#include +#include +#include +#include +#include "Pokemon/Pokemon_BdspRng.h" +#include "Pokemon/Pokemon_Xorshift128.h" +#include "PokemonBDSP_RngExecution.h" +#include "PokemonBDSP_RngTimeline.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +struct TargetSearchRequest{ + Pokemon::Xorshift128State state; + BdspTimelineContext timeline; + NavigationTimings timings; + Pokemon::BdspStaticTemplate pokemon; + uint8_t npcs = 1; + double tick_seconds = BDSP_NPC_TICK_SECONDS; + int64_t bias = 0; + uint64_t first_press = 0; + uint64_t window_advances = 0; + size_t max_schedules = 8; + std::function wanted; +}; + + +struct TargetSelectionResult{ + bool success = false; + uint64_t press_advance = 0; + uint64_t target_advance = 0; + PressSchedule schedule; + Pokemon::BdspPokemonResult target; + size_t matches_found = 0; + uint64_t advances_scanned = 0; + std::string failure_reason; +}; + + +TargetSelectionResult select_target(const TargetSearchRequest& request); + + +} +} +} +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index eae67abbf3..189dfe3e1f 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1563,6 +1563,10 @@ file(GLOB LIBRARY_SOURCES Source/Pokemon/AutoStory/Pokemon_AutoStorySelect.h Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.cpp Source/Pokemon/AutoStory/Pokemon_AutoStorySelect_Tests.h + Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp + Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h + Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp + Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.h Source/Pokemon/AutoStory/Pokemon_StoryRun.cpp Source/Pokemon/AutoStory/Pokemon_StoryRun.h Source/Pokemon/AutoStory/Pokemon_StoryRun_Tests.cpp @@ -1769,6 +1773,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/AutoStory/Detect/PokemonBDSP_AutoStory_OverworldDetector.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.h + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.cpp + Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StarterRng.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.cpp Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_Maps_Tests.h Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_PlannedRoute_Tests.cpp @@ -1898,6 +1904,8 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Options/PokemonBDSP_LearnMove.h Source/PokemonBDSP/Options/PokemonBDSP_PlayerModelOption.cpp Source/PokemonBDSP/Options/PokemonBDSP_PlayerModelOption.h + Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.cpp + Source/PokemonBDSP/Options/PokemonBDSP_RngFilter.h Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.cpp Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h Source/PokemonBDSP/PokemonBDSP_Panels.cpp @@ -1968,12 +1976,34 @@ file(GLOB LIBRARY_SOURCES Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_BlinkRecovery.h Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_IntroSeedFinder.cpp Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_IntroSeedFinder.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngAim.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngCalibration.h Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngDisplays.cpp Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngDisplays.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngExecution.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTargets.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_RngTimeline.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterNavigation.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StateReidentifier.cpp Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StateReidentifier.h Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StateSolver.cpp Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StateSolver.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_SummaryNavigation.h + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.cpp + Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_TargetSelection.h Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.cpp Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.h Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.cpp diff --git a/devtools/runtime-map-tests/CMakeLists.txt b/devtools/runtime-map-tests/CMakeLists.txt index 8a91248664..eb200ef5cc 100644 --- a/devtools/runtime-map-tests/CMakeLists.txt +++ b/devtools/runtime-map-tests/CMakeLists.txt @@ -11,6 +11,7 @@ add_library(RuntimeMapDecoder STATIC "${NAV}/Pokemon_RuntimeMap.cpp" "${NAV}/Pokemon_MapData.cpp" "${NAV}/Pokemon_Grid.cpp" + "${NAV}/Pokemon_Direction.cpp" "${ROOT}/Common/Cpp/Exceptions.cpp" "${ROOT}/Common/Cpp/Json/JsonValue.cpp" "${ROOT}/Common/Cpp/Json/JsonObject.cpp" 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():