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_StoryRngHandoff.cpp b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp new file mode 100644 index 0000000000..67fc164c82 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.cpp @@ -0,0 +1,53 @@ +/* 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(); +} + + +} // 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..7887658546 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff.h @@ -0,0 +1,86 @@ +/* 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 "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 +); + + +} // 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..e6d72119a4 --- /dev/null +++ b/SerialPrograms/Source/Pokemon/AutoStory/Pokemon_StoryRngHandoff_Tests.cpp @@ -0,0 +1,163 @@ +/* Story RNG Handoff Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#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"; +} + +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 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/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..99e99f6f08 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include "CommonFramework/Exceptions/OperationFailedException.h" #include "CommonFramework/Notifications/ProgramNotifications.h" #include "CommonFramework/VideoPipeline/VideoOverlay.h" @@ -22,6 +23,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 +58,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 +79,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 +135,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 +158,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 +177,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 +287,54 @@ 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 = STOP_FOR_STARTER_RNG, .run_starter_rng = 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 = std::format("Stopped for Starter RNG. {}", STARTER_RNG_HANDOFF_TEXT); + env.log(handoff, COLOR_BLUE); + 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..54c04262f2 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 = true} + ); + 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 = true, .run_starter_rng = true} + ); + 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..e6d946f3d4 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 && !handoffs.run_starter_rng){ + 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.run_starter_rng){ + 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..4412f1ea73 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/AutoStory/PokemonBDSP_AutoStory_StoryTable.h @@ -14,6 +14,8 @@ #ifndef PokemonAutomation_PokemonBDSP_AutoStory_StoryTable_H #define PokemonAutomation_PokemonBDSP_AutoStory_StoryTable_H +#include +#include #include #include #include "PokemonBDSP_AutoStory_StoryExecutor.h" @@ -33,6 +35,44 @@ 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{ + bool starter_rng = false; + bool run_starter_rng = false; +}; + +// 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` on 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..61975459a5 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 = false}); + 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 = true}); + 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 = true}); + 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 = true, .run_starter_rng = true} + ); + 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 = true, .run_starter_rng = true} + ); + 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 = true}); + 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_StarterRngAttempts.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp index 1f15c57748..472708f58f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.cpp @@ -288,6 +288,7 @@ bool resolve_starter_rng_step( } if (attempt.outcome == BdspAttemptOutcome::Hit){ + result.settled = attempt.settled; result.outcome = attempt.shiny ? StarterRngOutcome::SHINY : StarterRngOutcome::HIT; @@ -305,6 +306,28 @@ bool resolve_starter_rng_step( } +// 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, @@ -566,16 +589,16 @@ BdspStarterAttemptResult run_starter_rng_attempt( pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 5000ms); context.wait_for_all_requests(); } - if (settings.finish_battle_on_shiny){ - if (!clear_starter_battle(env, context)){ - record_error(); - } + 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, }; } diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h index c1c7977194..1e88d9b277 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRngAttempts.h @@ -79,10 +79,11 @@ bool starter_wanted( // 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. -// The player ends up right at the start of the post-battle Lake Verity -// cutscene (Rowan's lines and walking out of the lake to VerityLakefront -// `(17, 14..15)`), ready for AutoStory's `after_starly` step. +// `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. @@ -162,6 +163,10 @@ struct StarterRngRunResult{ 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; }; @@ -171,6 +176,8 @@ struct BdspStarterAttemptResult{ Pokemon::BdspPokemonResult target{}; uint64_t target_advance = 0; std::string failure_reason; + // See StarterRngRunResult::settled. + bool settled = true; }; diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp index c8cfd5182c..c561e57bc1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/RngManipulation/PokemonBDSP_StarterRng_Tests.cpp @@ -155,6 +155,27 @@ UnitTestResult test_aim_and_calibration(Logger& logger){ } +// 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; @@ -323,6 +344,7 @@ const StarterRngTestCase STARTER_RNG_CASES[] = { {"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 diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index bf438c7d97..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