From 18df05d1b1ddad8cda4e45df1b8c76ea3298bafb Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 16:15:49 -0800 Subject: [PATCH 01/10] FRLG AutoStory: run Starter RNG in the program A new option, Run Starter RNG in AutoStory (off by default), runs what the two RNG stops leave to the user: - At 00.01, with the RNG plan's SID empty: SID Helper's steps on the player's keyboard, then the TID read off the Trainer Card; the run goes on at 00.01b. - At the end of 00.04, saved under Squirtle's ball: the RNG plan's attempts, each with StarterRngAttempts, fed to RngPlanTracker. A shiny goes on to the rival's battle (00.04b from the rival's trigger), which saves, and the rest of the run. A hit without a shiny moves on to the next attempt, a miss retries it, up to 2 retries; every attempt has a 3-hour cap and the loop a 12-hour one. Otherwise the run stops with the save under the ball and what to do next. Every attempt logs an "RngPlan: result" line, and a shiny that leaves one SID logs "RngPlan: confirmed ... candidate=k of=N". The loop's decisions run against injected steps in the new AutoStoryRngLoop tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonFRLG/PokemonFRLG_Tests.cpp | 2 + .../AutoStory/PokemonFRLG_AutoStory.cpp | 227 ++++++++++--- .../AutoStory/PokemonFRLG_AutoStory.h | 20 ++ .../PokemonFRLG_AutoStoryRngLoop.cpp | 205 ++++++++++++ .../AutoStory/PokemonFRLG_AutoStoryRngLoop.h | 150 +++++++++ .../PokemonFRLG_AutoStoryRngLoop_Tests.cpp | 298 ++++++++++++++++++ .../PokemonFRLG_AutoStoryRngOptions.cpp | 13 +- .../PokemonFRLG_AutoStoryRngOptions.h | 4 + SerialPrograms/cmake/SourceFiles.cmake | 5 +- 9 files changed, 885 insertions(+), 39 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index 9dae84cf7b..172abaf5ac 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -40,6 +40,7 @@ #include "Programs/PokemonFRLG_NamingScreenKeyboard.h" #include "PokemonFRLG_Navigation.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryBattle.h" +#include "Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryRngPlan.h" #include "Programs/AutoStory/PokemonFRLG_AutoStoryTable.h" #include "Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h" @@ -705,6 +706,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_AutoStorySimulation(database); add_tests_AutoStoryItems(database); add_tests_AutoStoryRngPlan(database); + add_tests_AutoStoryRngLoop(database); add_tests_NamingCursor(database); add_tests_NamingPlan(database); add_tests_NamingKeys(database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index a005262e15..7f84cb57d5 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -16,8 +16,11 @@ #include "Pokemon/Pokemon_Strings.h" #include "VideoGames/PokemonFRLG/PokemonFRLG_Navigation.h" #include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_NamingScreenKeyboard.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h" #include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryRngLoop.h" #include "PokemonFRLG_AutoStoryTable.h" #include "PokemonFRLG_AutoStory.h" @@ -55,6 +58,13 @@ const StringSelectDatabase& checkpoint_database(){ } +const char* const RUN_STARTER_RNG_TEXT = + "Run Starter RNG in AutoStory:
Off by default. Instead of stopping for them, run SID Helper's steps on the " + "new game's keyboard when the RNG plan has no SID, and Starter RNG's attempts from a save south of the table at the " + "end of 00.04, as the RNG plan lists them. A shiny Squirtle goes on to the rival's battle, saves after it and the run " + "goes on; otherwise the run stops with the save south of the table.
" + "SID Helper's timing needs the text speed and button settings already saved, as with Stop for SID Helper."; + AutoStory::AutoStory() : RUN(checkpoint_database()) , NEW_GAME_FROM_TITLE( @@ -87,16 +97,17 @@ AutoStory::AutoStory() LockMode::LOCK_WHILE_RUNNING, false ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) + , RUN_STARTER_RNG(RUN_STARTER_RNG_TEXT, LockMode::LOCK_WHILE_RUNNING, false) + , NOTIFICATION_SHINY("Shiny found", true, true, ImageAttachmentMode::JPG, {"Notifs", "Showcase"}) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({&NOTIFICATION_SHINY, &NOTIFICATION_STATUS_UPDATE, &NOTIFICATION_PROGRAM_FINISH, &NOTIFICATION_ERROR_FATAL}) { PA_ADD_OPTION(RUN); PA_ADD_OPTION(NEW_GAME_FROM_TITLE); PA_ADD_OPTION(PLAYER_NAME); PA_ADD_OPTION(STOP_FOR_SID_HELPER); PA_ADD_OPTION(STOP_FOR_STARTER_RNG); + PA_ADD_OPTION(RUN_STARTER_RNG); PA_ADD_OPTION(RNG_PLAN); PA_ADD_OPTION(NOTIFICATIONS); } @@ -235,8 +246,6 @@ static void stop_for_handoff( send_program_finished_notification(env, notification, full); } -// SID Helper's set_sid_from_name_screen(), still file-static in -// PokemonFRLG_SidHelper.cpp, could run here instead of stopping. static void stop_for_sid_helper( SingleSwitchProgramEnvironment& env, ProControllerContext& context, EventNotificationOption& notification, const std::string& player_name @@ -275,15 +284,15 @@ static uint16_t starter_rng_tid( return *tid; } -// The Starter RNG attempts, as lines for the stop. Run under the ball before -// 00.04 saves there, so a failure ends the run with 00.03's save kept. -static std::vector starter_rng_attempts( +// The Starter RNG attempts. Run under the ball before 00.04 saves there, so +// a failure ends the run with 00.03's save kept. +static StarterRngPlanned plan_starter_rng_attempts( SingleSwitchProgramEnvironment& env, ProControllerContext& context, const StarterRngPlanOptions& options, Language language ){ const uint16_t tid = starter_rng_tid(env, context, options, language); try{ - return rng_attempt_lines(options.plan(env.console, language, tid)); + return StarterRngPlanned{.tid = tid, .attempts = options.plan(env.console, language, tid)}; }catch (UserSetupError& e){ throw UserSetupError(env.console, e.message() + " Nothing was saved: fix the RNG plan and start AutoStory at 00.04 again."); } @@ -302,8 +311,7 @@ static void before_last_save(Pokemon::Segment& segment, std::function be }; } -// Starter RNG runs its own reset and calibration loop in its program(), so -// the attempts are the user's to run until that loop can be called from here. +// The attempts are the user's to run, with Run Starter RNG in AutoStory off. // TODO: LeafGreen and Bulbasaur/Charmander, with AutoStory's starter choice. static void stop_for_starter_rng( SingleSwitchProgramEnvironment& env, EventNotificationOption& notification, @@ -319,55 +327,202 @@ static void stop_for_starter_rng( ); } +static size_t checkpoint_index(const std::vector& checkpoints, const std::string& id){ + for (size_t c = 0; c < checkpoints.size(); c++){ + if (checkpoints[c].id == id){ + return c; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No checkpoint " + id + "."); +} + +// Runs `rows` as one segment, calling `before` (if set) just before the +// last row saves. Throws if a checkpoint fails for good. +static void run_story_rows( + SingleSwitchProgramEnvironment& env, StoryEnv& story, StoryExecutor& executor, + const std::vector& rows, const Pokemon::SegmentPolicy& policy, + std::function before +){ + Pokemon::Segment segment = make_story_segment(rows, executor); + if (before){ + before_last_save(segment, std::move(before)); + } + Pokemon::SegmentHooks hooks = story_hooks(env, story); + + Pokemon::RunState state; + const Pokemon::SegmentReport report = run_segment( + state, segment, Pokemon::SegmentRange{rows.front().id, rows.back().id}, policy, hooks + ); + Pokemon::record_story_stats(env.current_stats(), report); + env.update_stats(); + throw_if_failed(report); +} + +// SID Helper's steps in the program, from the player's keyboard: the name +// typed, then the intro at SID Helper's timing into the bedroom, and the +// Trainer Card opened to read the TID. Ends on the card, where 00.01b +// starts. +static void set_sid_in_program( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const std::string& player_name, const StarterRngPlanOptions& options, Language language +){ + const uint32_t target_advances = options.SID_HELPER_ADVANCES; + if (target_advances % 2 == 0){ + throw UserSetupError(env.console, "RNG plan: SID Helper's Target Advances must be odd."); + } + play_new_game_to_player_name(env.console, context, player_name); + const SidTiming timing = sid_timing(language, target_advances); + env.log("SID Helper's steps: delay " + std::to_string(timing.delay_ms) + "ms"); + set_sid_from_name_screen(context, timing); + finish_intro_animations(env, context); + + navigate_to_trainer_card(env.console, context); + const std::optional tid = try_read_trainer_card_tid(env.console, context, language); + if (!tid){ + env.console.log("Couldn't read the TID on the Trainer Card; 00.04 reads it again.", COLOR_ORANGE); + return; + } + env.console.log(rng_log_tid(*tid, true)); + env.console.log(rng_log_sid_helper(*tid, target_advances, options.helper_candidates(*tid))); +} + +namespace{ + +// Run Starter RNG in AutoStory: an attempt's misses before the run stops, +// Starter RNG's default Max Resets per attempt, and the time caps. +const size_t STARTER_RNG_MAX_RETRIES = 2; +const uint64_t STARTER_RNG_MAX_RESETS = 50; +const StarterRngLoopLimits STARTER_RNG_LIMITS{ + .attempt_time = std::chrono::hours(3), + .total_time = std::chrono::hours(12), +}; + +} + +// Starter RNG's attempts in the program, from the save south of the table. +// Returns true for a shiny Squirtle, the game on its summary; otherwise the +// run has stopped with what to do next. +static bool run_starter_rng_in_program( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StarterRngPlanned& planned, const StarterRngPlanOptions& options, Language language, + const StarterRngNotifications& notifications, EventNotificationOption& finished +){ + RngPlanTracker tracker( + planned.attempts, options.plan_candidates(env.console, planned.tid), options.SHINY_REQUIRED, STARTER_RNG_MAX_RETRIES + ); + ConsoleStarterRngSteps steps( + env, context, + StarterRngConsoleSettings{.language = language, .sound = options.SOUND, .max_resets = STARTER_RNG_MAX_RESETS}, + notifications + ); + const StarterRngLoopResult result = run_starter_rng_plan( + env.console, tracker, steps, STARTER_RNG_LIMITS, planned.tid, options.helper_candidates(planned.tid) + ); + const std::string message = starter_rng_loop_message(result); + if (result.end != StarterRngLoopEnd::SHINY){ + stop_for_handoff(env, finished, message); + return false; + } + env.console.log(message, COLOR_BLUE); + env.console.overlay().add_log(message); + return true; +} + +// After a shiny Squirtle: off its summary, then the rival's battle, which +// saves (00.04b), and the rows after it to `last`. Until that save, a +// reload would load the save under the ball and lose the shiny, so a +// failure stops the run instead. Returns the last row's id. +static std::string run_after_shiny_starter( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryEnv& story, StoryExecutor& executor, const Pokemon::SegmentPolicy& policy, size_t ball_row, size_t last +){ + const std::vector rows = rows_after_starter_rng(story_checkpoints(), ball_row, last); + // As Starter RNG leaves the summary for the overworld. + pbf_mash_button(context, BUTTON_B, 5000ms); + context.wait_for_all_requests(); + env.console.log("The shiny Squirtle isn't saved until " + rows.front().id + " saves after the rival's battle. " + "If it fails before then, the run stops without reloading: save by hand.", COLOR_BLUE); + story.has_save = false; + run_story_rows(env, story, executor, rows, policy, nullptr); + return rows.back().id; +} + +StoryHandoffs AutoStory::story_handoffs() const{ + // Running Starter RNG here splits 00.04 at the ball as its stop does, + // and sets the SID at 00.01 when it isn't known. + return StoryHandoffs{ + .sid_helper = RUN_STARTER_RNG ? static_cast(RNG_PLAN.SID).empty() : bool(STOP_FOR_SID_HELPER), + .starter_rng = STOP_FOR_STARTER_RNG || RUN_STARTER_RNG, + }; +} + void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ const std::vector& checkpoints = story_checkpoints(); - const size_t first = RUN.start_index(); + size_t first = RUN.start_index(); const size_t last = RUN.end_index(); const std::string player_name = PLAYER_NAME; check_setup(env.console, checkpoints, first, last, NEW_GAME_FROM_TITLE, player_name); - const StoryRunPlan plan = plan_story_run( - checkpoints, first, last, StoryHandoffs{.sid_helper = STOP_FOR_SID_HELPER, .starter_rng = STOP_FOR_STARTER_RNG} - ); - if (plan.stop == StoryHandoff::SID_HELPER){ + const StoryHandoffs handoffs = story_handoffs(); + StoryRunPlan plan = plan_story_run(checkpoints, first, last, handoffs); + if (plan.stop == StoryHandoff::SID_HELPER && !RUN_STARTER_RNG){ stop_for_sid_helper(env, context, NOTIFICATION_PROGRAM_FINISH, player_name); return; } - if (plan.stop == StoryHandoff::STARTER_RNG){ + if (plan.stop != StoryHandoff::NONE){ // The options' text, before anything is pressed. RNG_PLAN.check(env.console); } + if (plan.stop == StoryHandoff::SID_HELPER){ + set_sid_in_program(env, context, player_name, RNG_PLAN, RUN.language()); + first = checkpoint_index(checkpoints, "00.01b"); + plan = plan_story_run(checkpoints, first, last, handoffs); + } StoryEnv story{env.console, context, checkpoints[first].supplies, checkpoints[first].supplies, false, RUN.checks()}; story.player_name = player_name; prepare_start(env, context, checkpoints, first, story); - StoryExecutor executor(story); executor.set_checks(RUN.checks()); executor.set_language(RUN.language()); - Pokemon::Segment segment = make_story_segment(plan.rows, executor); - std::vector rng_attempts; + + StarterRngPlanned planned; + std::function before; if (plan.stop == StoryHandoff::STARTER_RNG){ - before_last_save(segment, [&]{ - rng_attempts = starter_rng_attempts(env, context, RNG_PLAN, RUN.language()); - }); + before = [&]{ planned = plan_starter_rng_attempts(env, context, RNG_PLAN, RUN.language()); }; } - Pokemon::SegmentHooks hooks = story_hooks(env, story); - - Pokemon::RunState state; - const Pokemon::SegmentReport report = run_segment( - state, segment, Pokemon::SegmentRange{plan.rows.front().id, plan.rows.back().id}, RUN.policy(), hooks - ); - Pokemon::record_story_stats(env.current_stats(), report); - env.update_stats(); - throw_if_failed(report); + run_story_rows(env, story, executor, plan.rows, RUN.policy(), std::move(before)); + std::string done_through = plan.rows.back().id; if (plan.stop == StoryHandoff::STARTER_RNG){ - stop_for_starter_rng(env, NOTIFICATION_PROGRAM_FINISH, RNG_PLAN.sound_name(), rng_attempts); - return; + std::optional done = after_starter_ball( + env, context, story, executor, planned, checkpoint_index(checkpoints, done_through) + ); + if (!done){ + return; + } + done_through = *done; } - env.console.log("AutoStory: done through " + plan.rows.back().id + "."); + env.console.log("AutoStory: done through " + done_through + "."); send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); } +std::optional AutoStory::after_starter_ball( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryEnv& story, StoryExecutor& executor, const StarterRngPlanned& planned, size_t ball_row +){ + if (!RUN_STARTER_RNG){ + stop_for_starter_rng(env, NOTIFICATION_PROGRAM_FINISH, RNG_PLAN.sound_name(), rng_attempt_lines(planned.attempts)); + return std::nullopt; + } + const StarterRngNotifications notifications{ + .shiny = NOTIFICATION_SHINY, .status_update = NOTIFICATION_STATUS_UPDATE, .error_recoverable = NOTIFICATION_ERROR_RECOVERABLE, + }; + if (!run_starter_rng_in_program(env, context, planned, RNG_PLAN, RUN.language(), notifications, NOTIFICATION_PROGRAM_FINISH)){ + return std::nullopt; + } + return run_after_shiny_starter(env, context, story, executor, RUN.policy(), ball_row, RUN.end_index()); +} + + } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h index 274ad9e61e..c25edad269 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.h @@ -12,6 +12,8 @@ #ifndef PokemonAutomation_PokemonFRLG_AutoStory_H #define PokemonAutomation_PokemonFRLG_AutoStory_H +#include +#include #include "Common/Cpp/Options/BooleanCheckBoxOption.h" #include "Common/Cpp/Options/EnumDropdownOption.h" #include "Common/Cpp/Options/StringOption.h" @@ -19,6 +21,8 @@ #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "Pokemon/Options/Pokemon_StoryRunOptions.h" #include "PokemonFRLG_AutoStoryActions.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryRngLoop.h" #include "PokemonFRLG_AutoStoryRngOptions.h" namespace PokemonAutomation{ @@ -43,6 +47,17 @@ class AutoStory : public SingleSwitchProgramInstance{ ) override{} private: + // The RNG programs' handoffs the run takes, from the options. + StoryHandoffs story_handoffs() const; + // After 00.04 saved under Squirtle's ball (row `ball_row`): the stop + // for Starter RNG, or its attempts run here and, for a shiny, the run + // on to the end checkpoint. Returns the last checkpoint run, or nothing + // once the run has stopped. + std::optional after_starter_ball( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + StoryEnv& story, StoryExecutor& executor, const StarterRngPlanned& planned, size_t ball_row + ); + // The start and end checkpoints, attempts, checks and language, as in // every game's AutoStory. Pokemon::StoryRunOptions RUN; @@ -51,7 +66,12 @@ class AutoStory : public SingleSwitchProgramInstance{ // The RNG programs the run stops for (StoryHandoff). BooleanCheckBoxOption STOP_FOR_SID_HELPER; BooleanCheckBoxOption STOP_FOR_STARTER_RNG; + // Runs SID Helper's steps and Starter RNG's attempts in the program + // instead of stopping for them. + BooleanCheckBoxOption RUN_STARTER_RNG; StarterRngPlanOptions RNG_PLAN; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; EventNotificationsOption NOTIFICATIONS; }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp new file mode 100644 index 0000000000..49338aa207 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp @@ -0,0 +1,205 @@ +/* AutoStory RNG Loop + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "PokemonFRLG_AutoStoryRngLoop.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +RngAttemptOutcome plan_outcome(StarterRngOutcome outcome){ + switch (outcome){ + case StarterRngOutcome::shiny: + return RngAttemptOutcome::SHINY; + case StarterRngOutcome::target_hit: + return RngAttemptOutcome::HIT_NOT_SHINY; + case StarterRngOutcome::wild_shiny: + case StarterRngOutcome::out_of_resets: + case StarterRngOutcome::no_matches: + return RngAttemptOutcome::MISSED; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Starter RNG outcome."); +} + + +namespace{ + +std::string join_sids(const std::vector& sids){ + std::string text; + for (uint16_t sid : sids){ + text += (text.empty() ? "" : ",") + std::to_string(sid); + } + return text; +} + +std::optional loop_end(RngPlanStep step){ + switch (step){ + case RngPlanStep::RUN_ATTEMPT: + return std::nullopt; + case RngPlanStep::GOT_SHINY: + return StarterRngLoopEnd::SHINY; + case RngPlanStep::GOT_TARGET: + return StarterRngLoopEnd::TARGET; + case RngPlanStep::OUT_OF_ATTEMPTS: + return StarterRngLoopEnd::OUT_OF_ATTEMPTS; + case RngPlanStep::OUT_OF_RETRIES: + return StarterRngLoopEnd::OUT_OF_RETRIES; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RNG plan step."); +} + +} + + +StarterRngLoopResult run_starter_rng_plan( + Logger& logger, RngPlanTracker& tracker, StarterRngLoopSteps& steps, + const StarterRngLoopLimits& limits, uint16_t tid, const std::vector& sid_helper_candidates +){ + StarterRngLoopResult result; + const WallClock total_deadline = steps.now() + limits.total_time; + while (true){ + std::optional end = loop_end(tracker.step()); + if (end){ + result.end = *end; + break; + } + const WallClock start = steps.now(); + if (start >= total_deadline){ + logger.log("RngPlan: out of time before attempt " + std::to_string(tracker.attempt_index() + 1)); + result.end = StarterRngLoopEnd::OUT_OF_TIME; + break; + } + const size_t index = tracker.attempt_index(); + const WallClock deadline = std::min(start + limits.attempt_time, total_deadline); + const RngAttemptOutcome outcome = plan_outcome(steps.run_attempt(index, tracker.current_attempt(), deadline)); + result.attempts_run++; + logger.log(rng_log_result(index, outcome)); + tracker.record(outcome); + } + result.remaining_sids = tracker.remaining_sids(); + result.sid = tracker.confirmed_sid(); + if (result.end == StarterRngLoopEnd::SHINY && result.sid){ + logger.log(rng_log_confirmed(tid, *result.sid, sid_helper_candidates)); + } + return result; +} + +std::string starter_rng_loop_message(const StarterRngLoopResult& result){ + const std::string sids = join_sids(result.remaining_sids); + switch (result.end){ + case StarterRngLoopEnd::SHINY: + return result.sid + ? std::format("Starter RNG: shiny Squirtle. The SID is {}: enter it as the RNG plan's SID.", *result.sid) + : std::format("Starter RNG: shiny Squirtle. The SID is one of {}.", sids); + case StarterRngLoopEnd::TARGET: + return "Starter RNG hit the target (shiny not required). Nothing was saved after it: the game is where " + "Starter RNG's calibration left it. Play to the rival's battle and save by hand, then start AutoStory at 00.05."; + case StarterRngLoopEnd::OUT_OF_ATTEMPTS: + return std::format( + "Starter RNG: every planned attempt hit its target and none was shiny. SIDs left: {}. " + "The save is still south of the table: raise the RNG plan's max attempts and start AutoStory at 00.04 again.", sids + ); + case StarterRngLoopEnd::OUT_OF_RETRIES: + return "Starter RNG: one attempt missed its target more often than the retries allow. " + "The save is still south of the table: check the RNG plan's sound setting and start AutoStory at 00.04 again."; + case StarterRngLoopEnd::OUT_OF_TIME: + return std::format( + "Starter RNG: out of time after {} attempts. The save is still south of the table: start AutoStory at 00.04 again.", + result.attempts_run + ); + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Starter RNG loop end."); +} + + +std::vector rows_after_starter_rng( + const std::vector& checkpoints, size_t ball_row, size_t last +){ + if (ball_row + 1 >= checkpoints.size()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No checkpoint after the starter's ball."); + } + StoryCheckpoint row = checkpoints[ball_row + 1]; + auto taken = std::find_if(row.steps.begin(), row.steps.end(), [](const StoryStep& step){ + return step.name == "rival_takes_bulbasaur"; + }); + if (taken == row.steps.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, row.id + " has no rival_takes_bulbasaur step."); + } + row.steps.erase(row.steps.begin(), taken + 1); + row.title = "after Starter RNG in AutoStory: the rival's battle"; + + std::vector rows{std::move(row)}; + if (last > ball_row + 1){ + StoryRunPlan rest = plan_story_run(checkpoints, ball_row + 2, last, StoryHandoffs{}); + rows.insert(rows.end(), rest.rows.begin(), rest.rows.end()); + } + return rows; +} + + +ConsoleStarterRngSteps::ConsoleStarterRngSteps( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StarterRngConsoleSettings& settings, const StarterRngNotifications& notifications +) + : m_env(env) + , m_context(context) + , m_settings(settings) + , m_notifications(notifications) + // TODO: LeafGreen, once AutoStory plays it. + , m_seeds(seeds_json_path(true, settings.language)) +{} + +WallClock ConsoleStarterRngSteps::now(){ + return current_time(); +} + +StarterRngOutcome ConsoleStarterRngSteps::run_attempt(size_t index, const RngAttempt& attempt, WallClock deadline){ + // Starter RNG's default Nearby Seed Radius. + const int SEED_RADIUS = 5; + const SeedMatch seed_match = m_seeds.find_seed(attempt.target.seed.seed, m_settings.sound, SEED_RADIUS); + if (!seed_match.found){ + throw InternalProgramError(&m_env.logger(), PA_CURRENT_FUNCTION, "The plan's seed isn't in the seed list it came from."); + } + m_env.log(std::format("Starter RNG attempt {}: seed {:04X}, advances {}.", index + 1, attempt.target.seed.seed, attempt.target.advances)); + + const uint64_t max_resets = m_settings.max_resets; + StarterRngStats stats; + StarterRngAttempts attempts( + StarterRngTarget{ + .starter = StarterSpecies::squirtle, + .seed = attempt.target.seed.seed, + .advances = attempt.target.advances, + .seed_match = seed_match, + }, + StarterRngSettings{ + .language = m_settings.language, + .profile = 0, + .ignore_wild_shinies = true, + .take_video = false, + .max_resets = [deadline, max_resets]{ + return current_time() >= deadline ? uint64_t(0) : max_resets; + }, + }, + StarterRngDisplays{ + .target = m_target_display, + .filters = m_filter_display, + .calibration = m_calibration_display, + }, + m_notifications, + stats + ); + return attempts.run(m_env, m_context).outcome; +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h new file mode 100644 index 0000000000..576e2cedc6 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h @@ -0,0 +1,150 @@ +/* AutoStory RNG Loop + * + * From: https://github.com/PokemonAutomation/ + * + * AutoStory's Starter RNG stop, run in the program: the RNG plan's + * attempts (PokemonFRLG_AutoStoryRngPlan.h), each run with Starter RNG's + * attempt loop (StarterRngAttempts) from the save under Squirtle's ball, + * until one comes out shiny or the plan, its retries or the time run out. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_AutoStoryRngLoop_H +#define PokemonAutomation_PokemonFRLG_AutoStoryRngLoop_H + +#include +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/Time.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngDisplays.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h" +#include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryRngPlan.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The Starter RNG plan, for the TID it was made for. +struct StarterRngPlanned{ + uint16_t tid = 0; + std::vector attempts; +}; + +// Starter RNG's outcome as the RNG plan counts it. Out of resets, no +// matches and a wild shiny are misses, which the plan runs again. +RngAttemptOutcome plan_outcome(StarterRngOutcome outcome); + + +struct StarterRngLoopLimits{ + // An attempt makes no more resets after this long, and counts as missed. + Milliseconds attempt_time = Milliseconds(0); + // No attempt starts after this long. + Milliseconds total_time = Milliseconds(0); +}; + +// The game steps of the loop, injected so that its decisions run in tests +// without a Switch. +class StarterRngLoopSteps{ +public: + virtual ~StarterRngLoopSteps() = default; + virtual WallClock now() = 0; + // Runs Starter RNG's attempts at attempt `index` (from 0) from the save + // under the ball, making no reset after `deadline`. + virtual StarterRngOutcome run_attempt(size_t index, const RngAttempt& attempt, WallClock deadline) = 0; +}; + +enum class StarterRngLoopEnd{ + // The starter is shiny; the game is on its summary, not saved. + SHINY, + // Shiny not required, and the target was hit. The game is where + // Starter RNG's calibration left it, not saved. + TARGET, + // Every attempt was hit and none was shiny. + OUT_OF_ATTEMPTS, + // One attempt missed more often than the retries allow. + OUT_OF_RETRIES, + // The total time ran out with attempts left. + OUT_OF_TIME, +}; + +struct StarterRngLoopResult{ + StarterRngLoopEnd end = StarterRngLoopEnd::OUT_OF_TIME; + // Attempts run, retries included. + size_t attempts_run = 0; + // The SID candidates not ruled out. + std::vector remaining_sids; + // The SID, once a shiny leaves one candidate. + std::optional sid; +}; + +// Runs `tracker`'s attempts through `steps` until the plan ends or +// `limits.total_time` has passed. Logs an "RngPlan: result" line per +// attempt and, when a shiny leaves one SID, an "RngPlan: confirmed" line +// placing it among SID Helper's candidates for `tid`. +StarterRngLoopResult run_starter_rng_plan( + Logger& logger, RngPlanTracker& tracker, StarterRngLoopSteps& steps, + const StarterRngLoopLimits& limits, uint16_t tid, const std::vector& sid_helper_candidates +); + +// What the run says when the loop ends with `result`. +std::string starter_rng_loop_message(const StarterRngLoopResult& result); + +// The rows a run takes after a shiny from the loop, which leaves the player +// under Squirtle's ball with the rival's ball taken: the row after +// `ball_row` (00.04b) from its step after "rival_takes_bulbasaur", then +// the rows after it to `last` as plan_story_run() takes them. Throws +// InternalProgramError for a table without that row or step. +std::vector rows_after_starter_rng( + const std::vector& checkpoints, size_t ball_row, size_t last +); + + +struct StarterRngConsoleSettings{ + Language language = Language::English; + SoundSetting sound = SoundSetting::Mono; + uint64_t max_resets = 0; +}; + +// The loop's steps on the console, with Starter RNG's displays, stats and +// calibration kept here (AutoStory doesn't show them). Squirtle, FireRed, +// the Switch's default profile. +class ConsoleStarterRngSteps : public StarterRngLoopSteps{ +public: + ConsoleStarterRngSteps( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StarterRngConsoleSettings& settings, const StarterRngNotifications& notifications + ); + + virtual WallClock now() override; + virtual StarterRngOutcome run_attempt(size_t index, const RngAttempt& attempt, WallClock deadline) override; + +private: + SingleSwitchProgramEnvironment& m_env; + ProControllerContext& m_context; + StarterRngConsoleSettings m_settings; + StarterRngNotifications m_notifications; + SeedsDatabase m_seeds; + RngTargetDisplay m_target_display; + RngFilterDisplay m_filter_display; + RngCalibrationDisplay m_calibration_display; +}; + + +void add_tests_AutoStoryRngLoop(UnitTestDatabase& database); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp new file mode 100644 index 0000000000..9f12d992e2 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp @@ -0,0 +1,298 @@ +/* AutoStory RNG Loop Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The Starter RNG loop's decisions on scripted attempt outcomes and a fake + * clock, and the rows a run takes after a shiny. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_AutoStoryTable.h" +#include "PokemonFRLG_AutoStoryRngLoop.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +class Test_AutoStoryRngLoop : public UnitTest{ +public: + Test_AutoStoryRngLoop(std::string name, std::function body) + : UnitTest("PokemonFRLG::AutoStoryRngLoop - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + + +class LineLogger : public Logger{ +public: + virtual void log(const std::string& msg, Color) override{ + lines.push_back(msg); + } + bool has(const std::string& line) const{ + return std::find(lines.begin(), lines.end(), line) != lines.end(); + } + + std::vector lines; +}; + +// Each attempt takes `minutes_per_attempt` on the clock and comes out as +// the next of `outcomes`. +class ScriptedSteps : public StarterRngLoopSteps{ +public: + ScriptedSteps(std::vector outcomes, int minutes_per_attempt) + : m_outcomes(std::move(outcomes)) + , m_minutes(minutes_per_attempt) + {} + + virtual WallClock now() override{ + return m_now; + } + virtual StarterRngOutcome run_attempt(size_t index, const RngAttempt&, WallClock deadline) override{ + if (m_next >= m_outcomes.size()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "More attempts than scripted."); + } + indices.push_back(index); + deadlines_min.push_back(int(std::chrono::duration_cast(deadline - START).count())); + m_now += std::chrono::minutes(m_minutes); + return m_outcomes[m_next++]; + } + + std::vector indices; + // Each attempt's deadline, in minutes from the start. + std::vector deadlines_min; + +private: + static inline const WallClock START = WallClock{} + std::chrono::hours(1000); + std::vector m_outcomes; + int m_minutes; + WallClock m_now = START; + size_t m_next = 0; +}; + +// SID Helper's candidates 100, 200, 300; attempt 1 is shiny for 100 and +// 200, attempt 2 for 300. +const std::vector CANDIDATES = {{100, 1}, {200, 2}, {300, 1}}; + +std::vector attempts(){ + RngAttempt first{}; + first.sids = {100, 200}; + RngAttempt second{}; + second.sids = {300}; + return {first, second}; +} + +// 60-minute attempts, 12 hours in all. +const StarterRngLoopLimits LIMITS{ + .attempt_time = std::chrono::minutes(60), + .total_time = std::chrono::hours(12), +}; + +std::string end_name(StarterRngLoopEnd end){ + switch (end){ + case StarterRngLoopEnd::SHINY: + return "SHINY"; + case StarterRngLoopEnd::TARGET: + return "TARGET"; + case StarterRngLoopEnd::OUT_OF_ATTEMPTS: + return "OUT_OF_ATTEMPTS"; + case StarterRngLoopEnd::OUT_OF_RETRIES: + return "OUT_OF_RETRIES"; + case StarterRngLoopEnd::OUT_OF_TIME: + return "OUT_OF_TIME"; + } + return "?"; +} + +std::string join(const std::vector& values){ + std::string text; + for (size_t value : values){ + text += (text.empty() ? "" : ",") + std::to_string(value + 1); + } + return text; +} + + +struct LoopRow{ + std::string name; + std::vector outcomes; + int minutes_per_attempt; + bool shiny_required; + StarterRngLoopEnd end; + // The attempts run, from 1, as "1,1,2". + std::string attempts_run; + // The SID confirmed, or 0 for none. + uint16_t sid; + // A log line the loop must write; empty for none. + std::string line; +}; + +const std::vector LOOP_ROWS = { + { + .name = "hit, then shiny confirms the SID", + .outcomes = {StarterRngOutcome::target_hit, StarterRngOutcome::shiny}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,2", .sid = 300, + .line = "RngPlan: confirmed tid=12345 sid=300 candidate=3 of=3", + }, + { + .name = "shiny for two SIDs confirms none", + .outcomes = {StarterRngOutcome::shiny}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1", .sid = 0, + .line = "RngPlan: result attempt=1 outcome=SHINY", + }, + { + .name = "misses retry the same attempt", + .outcomes = {StarterRngOutcome::out_of_resets, StarterRngOutcome::no_matches, StarterRngOutcome::shiny}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,1", .sid = 0, + .line = "RngPlan: result attempt=1 outcome=MISSED", + }, + { + .name = "too many misses stop", + .outcomes = {StarterRngOutcome::out_of_resets, StarterRngOutcome::out_of_resets, StarterRngOutcome::wild_shiny}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::OUT_OF_RETRIES, .attempts_run = "1,1,1", .sid = 0, + .line = "", + }, + { + .name = "every attempt hit, none shiny", + .outcomes = {StarterRngOutcome::target_hit, StarterRngOutcome::target_hit}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::OUT_OF_ATTEMPTS, .attempts_run = "1,2", .sid = 0, + .line = "RngPlan: result attempt=2 outcome=HIT_NOT_SHINY", + }, + { + .name = "a hit ends the plan with shiny not required", + .outcomes = {StarterRngOutcome::target_hit}, + .minutes_per_attempt = 30, .shiny_required = false, + .end = StarterRngLoopEnd::TARGET, .attempts_run = "1", .sid = 0, + .line = "", + }, + { + .name = "no attempt starts after the total time", + .outcomes = {StarterRngOutcome::out_of_resets, StarterRngOutcome::out_of_resets}, + .minutes_per_attempt = 400, .shiny_required = true, + .end = StarterRngLoopEnd::OUT_OF_TIME, .attempts_run = "1,1", .sid = 0, + .line = "RngPlan: out of time before attempt 1", + }, +}; + +UnitTestResult run_loop_row(const LoopRow& row){ + RngPlanTracker tracker(attempts(), CANDIDATES, row.shiny_required, 2); + ScriptedSteps steps(row.outcomes, row.minutes_per_attempt); + LineLogger logger; + StarterRngLoopResult result = run_starter_rng_plan(logger, tracker, steps, LIMITS, 12345, CANDIDATES); + + const std::string expected = std::format("end {}, attempts {}, sid {}", end_name(row.end), row.attempts_run, row.sid); + const std::string got = std::format( + "end {}, attempts {}, sid {}", end_name(result.end), join(steps.indices), result.sid.value_or(0) + ); + if (expected != got){ + return "Expected " + expected + "; got " + got; + } + if (!row.line.empty() && !logger.has(row.line)){ + return "Expected the log line \"" + row.line + "\""; + } + if (result.attempts_run != steps.indices.size()){ + return std::format("Expected attempts_run {}; got {}", steps.indices.size(), result.attempts_run); + } + return true; +} + + +// An attempt's deadline is an hour after it starts, or the end of the +// total time if sooner: attempts of 400 minutes start at 0 and 400, and +// none at 800, past the total of 430. +UnitTestResult test_deadlines(){ + RngPlanTracker tracker(attempts(), CANDIDATES, true, 5); + ScriptedSteps steps({StarterRngOutcome::out_of_resets, StarterRngOutcome::out_of_resets}, 400); + LineLogger logger; + const StarterRngLoopLimits limits{.attempt_time = std::chrono::minutes(60), .total_time = std::chrono::minutes(430)}; + run_starter_rng_plan(logger, tracker, steps, limits, 12345, CANDIDATES); + std::string got; + for (int deadline : steps.deadlines_min){ + got += (got.empty() ? "" : ",") + std::to_string(deadline); + } + if (got != "60,430"){ + return "Expected deadlines 60,430 minutes; got " + got; + } + return true; +} + + +// After a shiny, 00.04b picks up at the rival's trigger and runs on. +UnitTestResult test_rows_after_shiny(){ + const std::vector& checkpoints = story_checkpoints(); + size_t ball_row = 0; + size_t parcel_row = 0; + for (size_t c = 0; c < checkpoints.size(); c++){ + if (checkpoints[c].id == "00.04"){ + ball_row = c; + } + if (checkpoints[c].id == "00.05"){ + parcel_row = c; + } + } + struct Case{ + size_t last; + std::string ids; + }; + const std::vector cases = { + {.last = ball_row, .ids = "00.04b"}, + {.last = ball_row + 1, .ids = "00.04b"}, + {.last = parcel_row, .ids = "00.04b,00.05"}, + }; + for (const Case& item : cases){ + const std::vector rows = rows_after_starter_rng(checkpoints, ball_row, item.last); + std::string ids; + for (const StoryCheckpoint& row : rows){ + ids += (ids.empty() ? "" : ",") + row.id; + } + const std::string first_step = rows.front().steps.empty() ? "" : rows.front().steps.front().name; + if (ids != item.ids || first_step != "above_rival_trigger"){ + return std::format( + "Expected rows {} starting at above_rival_trigger; got {} starting at {}", item.ids, ids, first_step + ); + } + } + return true; +} + +} + + +void add_tests_AutoStoryRngLoop(UnitTestDatabase& database){ + for (const LoopRow& row : LOOP_ROWS){ + database.add(row.name, [row]{ return run_loop_row(row); }); + } + database.add("attempt deadlines", test_deadlines); + database.add("rows after a shiny", test_rows_after_shiny); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp index 66b7c02642..875ca72073 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp @@ -112,10 +112,19 @@ void StarterRngPlanOptions::check(Logger& logger) const{ filters(logger); } +std::vector StarterRngPlanOptions::helper_candidates(uint16_t tid) const{ + return sid_helper_candidates(tid, SID_HELPER_ADVANCES, SID_HELPER_CANDIDATES); +} + +std::vector StarterRngPlanOptions::plan_candidates(Logger& logger, uint16_t tid) const{ + const std::optional known = sid(logger); + return known ? std::vector{{*known, 1}} : helper_candidates(tid); +} + std::vector StarterRngPlanOptions::plan(Logger& logger, Language language, uint16_t tid) const{ // SID Helper's candidates are logged even with the SID known, to place // it among them (rng_log_confirmed()). - const std::vector helper = sid_helper_candidates(tid, SID_HELPER_ADVANCES, SID_HELPER_CANDIDATES); + const std::vector helper = helper_candidates(tid); logger.log(rng_log_sid_helper(tid, SID_HELPER_ADVANCES, helper)); const std::optional known = sid(logger); if (known){ @@ -128,7 +137,7 @@ std::vector StarterRngPlanOptions::plan(Logger& logger, Language lan .language = language, .sound = SOUND, .tid = tid, - .candidates = known ? std::vector{{*known, 1}} : helper, + .candidates = plan_candidates(logger, tid), .filters = filters(logger), .max_attempts = MAX_ATTEMPTS, }); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h index 38f4cc0366..2c13ef4977 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h @@ -42,6 +42,10 @@ class StarterRngPlanOptions : public GroupOption{ // in "language", logged as "RngPlan:" lines. Throws UserSetupError // when no target passes. std::vector plan(Logger& logger, Language language, uint16_t tid) const; + // SID Helper's candidates for "tid", from the two SID Helper options. + std::vector helper_candidates(uint16_t tid) const; + // The SIDs plan() plans for: the SID if set, else helper_candidates(). + std::vector plan_candidates(Logger& logger, uint16_t tid) const; // The sound setting as Starter RNG's dropdown shows it. std::string sound_name() const; diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index b88076520a..12e3f60848 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1840,14 +1840,17 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryEvents.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryItems_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngPlan.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngPlan.h Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngPlan_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h - Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySimulation_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory_Tests.cpp Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_EliteFourFarmer.cpp Source/VideoGames/PokemonFRLG/Programs/Farming/PokemonFRLG_EliteFourFarmer.h From e160dc26ca9378ea35dd0e7be7b7acb12d1aa475 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 16:37:24 -0800 Subject: [PATCH 02/10] FRLG AutoStory: log the Starter RNG loop's state The loop now logs, and shows on the overlay log, an "RngPlan: state" line at the start of every try of an attempt and after every reset: attempt and try counts, resets, seed, advances, the attempt's SIDs, the SIDs ruled out, the try's and the loop's time against their caps, and the calibration. StarterRngAttempts reports each reset through a new on_reset hook in its settings (StarterRng passes none), so RngManipulation still doesn't depend on AutoStory. "RngPlan: result" gains the try, Starter RNG's own outcome, the nature, IVs and PID when known, and what the loop does next; its outcomes are lower case. The RngPlan header lists every line in the order a run logs them, and the new lines' formats are unit-tested. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../AutoStory/PokemonFRLG_AutoStory.cpp | 17 +- .../PokemonFRLG_AutoStoryRngLoop.cpp | 158 ++++++++++++++++-- .../AutoStory/PokemonFRLG_AutoStoryRngLoop.h | 82 +++++++-- .../PokemonFRLG_AutoStoryRngLoop_Tests.cpp | 92 +++++++--- .../PokemonFRLG_AutoStoryRngPlan.cpp | 61 ++++++- .../AutoStory/PokemonFRLG_AutoStoryRngPlan.h | 40 ++++- .../PokemonFRLG_AutoStoryRngPlan_Tests.cpp | 18 +- .../PokemonFRLG_StarterRng.cpp | 7 +- .../PokemonFRLG_StarterRngAttempts.cpp | 3 + .../PokemonFRLG_StarterRngAttempts.h | 9 + 10 files changed, 420 insertions(+), 67 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index 7f84cb57d5..547543e5fc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -388,13 +388,13 @@ static void set_sid_in_program( namespace{ -// Run Starter RNG in AutoStory: an attempt's misses before the run stops, -// Starter RNG's default Max Resets per attempt, and the time caps. -const size_t STARTER_RNG_MAX_RETRIES = 2; -const uint64_t STARTER_RNG_MAX_RESETS = 50; +// Run Starter RNG in AutoStory: the time caps, Starter RNG's default Max +// Resets per try, and an attempt's misses before the run stops. const StarterRngLoopLimits STARTER_RNG_LIMITS{ .attempt_time = std::chrono::hours(3), .total_time = std::chrono::hours(12), + .max_resets = 50, + .max_retries = 2, }; } @@ -408,15 +408,14 @@ static bool run_starter_rng_in_program( const StarterRngNotifications& notifications, EventNotificationOption& finished ){ RngPlanTracker tracker( - planned.attempts, options.plan_candidates(env.console, planned.tid), options.SHINY_REQUIRED, STARTER_RNG_MAX_RETRIES + planned.attempts, options.plan_candidates(env.console, planned.tid), options.SHINY_REQUIRED, STARTER_RNG_LIMITS.max_retries ); ConsoleStarterRngSteps steps( - env, context, - StarterRngConsoleSettings{.language = language, .sound = options.SOUND, .max_resets = STARTER_RNG_MAX_RESETS}, - notifications + env, context, StarterRngConsoleSettings{.language = language, .sound = options.SOUND}, notifications ); + RngPlanLogger logger(env.console); const StarterRngLoopResult result = run_starter_rng_plan( - env.console, tracker, steps, STARTER_RNG_LIMITS, planned.tid, options.helper_candidates(planned.tid) + logger, tracker, steps, STARTER_RNG_LIMITS, planned.tid, options.helper_candidates(planned.tid) ); const std::string message = starter_rng_loop_message(result); if (result.end != StarterRngLoopEnd::SHINY){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp index 49338aa207..df3b211ac3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp @@ -7,6 +7,7 @@ #include #include #include "Common/Cpp/Exceptions.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" #include "PokemonFRLG_AutoStoryRngLoop.h" namespace PokemonAutomation{ @@ -28,17 +29,63 @@ RngAttemptOutcome plan_outcome(StarterRngOutcome outcome){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Starter RNG outcome."); } +std::string starter_rng_outcome_name(StarterRngOutcome outcome){ + switch (outcome){ + case StarterRngOutcome::shiny: + return "shiny"; + case StarterRngOutcome::target_hit: + return "target_hit"; + case StarterRngOutcome::wild_shiny: + return "wild_shiny"; + case StarterRngOutcome::out_of_resets: + return "out_of_resets"; + case StarterRngOutcome::no_matches: + return "no_matches"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Starter RNG outcome."); +} + namespace{ +// "-" for none. std::string join_sids(const std::vector& sids){ std::string text; for (uint16_t sid : sids){ text += (text.empty() ? "" : ",") + std::to_string(sid); } - return text; + return text.empty() ? "-" : text; } +std::string clock_text(Milliseconds time){ + const int64_t seconds = std::chrono::duration_cast(time).count(); + return std::format("{:02}:{:02}:{:02}", seconds / 3600, seconds / 60 % 60, seconds % 60); +} + +std::string calibration_text(const std::optional& calibration){ + if (!calibration){ + return "-"; + } + return std::format("{:.2f}/{:.2f}/{:.2f}", calibration->seed_offset, calibration->csf_offset, calibration->ingame_offset); +} + +} + +std::string rng_log_state(const RngLoopState& state){ + return std::format( + "RngPlan: state attempt={}/{} try={}/{} reset={}/{} seed={:04X} advances={} sids={} ruled_out={} " + "attempt_time={}/{} total_time={}/{} calibration={}", + state.attempt, state.attempts, state.try_number, state.tries, state.resets, state.max_resets, + state.seed, state.advances, join_sids(state.sids), join_sids(state.ruled_out), + clock_text(state.attempt_time), clock_text(state.attempt_cap), + clock_text(state.total_time), clock_text(state.total_cap), + calibration_text(state.calibration) + ); +} + + +namespace{ + std::optional loop_end(RngPlanStep step){ switch (step){ case RngPlanStep::RUN_ATTEMPT: @@ -55,6 +102,78 @@ std::optional loop_end(RngPlanStep step){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RNG plan step."); } +// The loop's state lines and tries, across the attempts. +class LoopLog{ +public: + LoopLog(Logger& logger, const RngPlanTracker& tracker, const StarterRngLoopLimits& limits, WallClock start) + : m_logger(logger) + , m_tracker(tracker) + , m_limits(limits) + , m_start(start) + , m_start_sids(tracker.remaining_sids()) + {} + + // A new try of the tracker's current attempt, starting at `now`. + void begin_try(WallClock now){ + const size_t index = m_tracker.attempt_index(); + m_try = (m_tries_of && *m_tries_of == index) ? m_try + 1 : 1; + m_tries_of = index; + m_try_start = now; + } + size_t try_number() const{ + return m_try; + } + + void log_state(WallClock now, uint64_t resets, const std::optional& calibration){ + const RngAttempt& attempt = m_tracker.current_attempt(); + std::vector ruled_out; + for (uint16_t sid : m_start_sids){ + const std::vector& left = m_tracker.remaining_sids(); + if (std::find(left.begin(), left.end(), sid) == left.end()){ + ruled_out.push_back(sid); + } + } + m_logger.log(rng_log_state(RngLoopState{ + .attempt = m_tracker.attempt_index() + 1, .attempts = m_tracker.attempt_count(), + .try_number = m_try, .tries = m_limits.max_retries + 1, + .resets = resets, .max_resets = m_limits.max_resets, + .seed = attempt.target.seed.seed, .advances = attempt.target.advances, + .sids = attempt.sids, .ruled_out = std::move(ruled_out), + .attempt_time = std::chrono::duration_cast(now - m_try_start), .attempt_cap = m_limits.attempt_time, + .total_time = std::chrono::duration_cast(now - m_start), .total_cap = m_limits.total_time, + .calibration = calibration, + })); + } + +private: + Logger& m_logger; + const RngPlanTracker& m_tracker; + const StarterRngLoopLimits& m_limits; + const WallClock m_start; + const std::vector m_start_sids; + std::optional m_tries_of; + size_t m_try = 0; + WallClock m_try_start; +}; + +// Runs one try of the tracker's current attempt, logging its state lines. +StarterRngResult run_try( + LoopLog& log, const RngPlanTracker& tracker, StarterRngLoopSteps& steps, + const StarterRngLoopLimits& limits, WallClock start, WallClock total_deadline +){ + log.begin_try(start); + log.log_state(start, 0, std::nullopt); + StarterRngAttemptCall call{ + .index = tracker.attempt_index(), + .deadline = std::min(start + limits.attempt_time, total_deadline), + .max_resets = limits.max_resets, + .on_reset = [&](const StarterRngProgress& progress){ + log.log_state(steps.now(), progress.resets, progress.calibrations); + }, + }; + return steps.run_attempt(tracker.current_attempt(), call); +} + } @@ -63,7 +182,9 @@ StarterRngLoopResult run_starter_rng_plan( const StarterRngLoopLimits& limits, uint16_t tid, const std::vector& sid_helper_candidates ){ StarterRngLoopResult result; - const WallClock total_deadline = steps.now() + limits.total_time; + const WallClock loop_start = steps.now(); + const WallClock total_deadline = loop_start + limits.total_time; + LoopLog log(logger, tracker, limits, loop_start); while (true){ std::optional end = loop_end(tracker.step()); if (end){ @@ -77,11 +198,15 @@ StarterRngLoopResult run_starter_rng_plan( break; } const size_t index = tracker.attempt_index(); - const WallClock deadline = std::min(start + limits.attempt_time, total_deadline); - const RngAttemptOutcome outcome = plan_outcome(steps.run_attempt(index, tracker.current_attempt(), deadline)); + const StarterRngResult attempt = run_try(log, tracker, steps, limits, start, total_deadline); + const RngAttemptOutcome outcome = plan_outcome(attempt.outcome); result.attempts_run++; - logger.log(rng_log_result(index, outcome)); - tracker.record(outcome); + const RngPlanStep step = tracker.record(outcome); + logger.log(rng_log_result(RngResultLog{ + .index = index, .try_number = log.try_number(), .outcome = outcome, + .detail = starter_rng_outcome_name(attempt.outcome), .pokemon = attempt.pokemon, + .next = rng_plan_next(step, index, tracker.attempt_index()), + })); } result.remaining_sids = tracker.remaining_sids(); result.sid = tracker.confirmed_sid(); @@ -144,6 +269,18 @@ std::vector rows_after_starter_rng( } +RngPlanLogger::RngPlanLogger(ConsoleHandle& console) + : m_console(console) +{} + +void RngPlanLogger::log(const std::string& msg, Color color){ + m_console.log(msg, color); + if (msg.starts_with("RngPlan: state") || msg.starts_with("RngPlan: result")){ + m_console.overlay().add_log(msg); + } +} + + ConsoleStarterRngSteps::ConsoleStarterRngSteps( SingleSwitchProgramEnvironment& env, ProControllerContext& context, const StarterRngConsoleSettings& settings, const StarterRngNotifications& notifications @@ -160,16 +297,14 @@ WallClock ConsoleStarterRngSteps::now(){ return current_time(); } -StarterRngOutcome ConsoleStarterRngSteps::run_attempt(size_t index, const RngAttempt& attempt, WallClock deadline){ +StarterRngResult ConsoleStarterRngSteps::run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call){ // Starter RNG's default Nearby Seed Radius. const int SEED_RADIUS = 5; const SeedMatch seed_match = m_seeds.find_seed(attempt.target.seed.seed, m_settings.sound, SEED_RADIUS); if (!seed_match.found){ throw InternalProgramError(&m_env.logger(), PA_CURRENT_FUNCTION, "The plan's seed isn't in the seed list it came from."); } - m_env.log(std::format("Starter RNG attempt {}: seed {:04X}, advances {}.", index + 1, attempt.target.seed.seed, attempt.target.advances)); - const uint64_t max_resets = m_settings.max_resets; StarterRngStats stats; StarterRngAttempts attempts( StarterRngTarget{ @@ -183,9 +318,10 @@ StarterRngOutcome ConsoleStarterRngSteps::run_attempt(size_t index, const RngAtt .profile = 0, .ignore_wild_shinies = true, .take_video = false, - .max_resets = [deadline, max_resets]{ + .max_resets = [deadline = call.deadline, max_resets = call.max_resets]{ return current_time() >= deadline ? uint64_t(0) : max_resets; }, + .on_reset = call.on_reset, }, StarterRngDisplays{ .target = m_target_display, @@ -195,7 +331,7 @@ StarterRngOutcome ConsoleStarterRngSteps::run_attempt(size_t index, const RngAtt m_notifications, stats ); - return attempts.run(m_env, m_context).outcome; + return attempts.run(m_env, m_context); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h index 576e2cedc6..ad39addebd 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h @@ -6,6 +6,8 @@ * attempts (PokemonFRLG_AutoStoryRngPlan.h), each run with Starter RNG's * attempt loop (StarterRngAttempts) from the save under Squirtle's ball, * until one comes out shiny or the plan, its retries or the time run out. + * Its "RngPlan: state" and "RngPlan: result" lines are listed with the + * plan's in PokemonFRLG_AutoStoryRngPlan.h. * */ @@ -13,16 +15,20 @@ #define PokemonAutomation_PokemonFRLG_AutoStoryRngLoop_H #include +#include #include #include #include +#include "Common/Cpp/Color.h" #include "Common/Cpp/Logging/AbstractLogger.h" #include "Common/Cpp/Time.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "CommonFramework/Language.h" #include "CommonFramework/Notifications/EventNotificationOption.h" #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngCalibration.h" #include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngDisplays.h" #include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h" #include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h" @@ -43,6 +49,33 @@ struct StarterRngPlanned{ // Starter RNG's outcome as the RNG plan counts it. Out of resets, no // matches and a wild shiny are misses, which the plan runs again. RngAttemptOutcome plan_outcome(StarterRngOutcome outcome); +// As the result line names it: "shiny", "target_hit", "out_of_resets"... +std::string starter_rng_outcome_name(StarterRngOutcome outcome); + + +// Where the loop is, for an "RngPlan: state" line. +struct RngLoopState{ + // From 1, of `attempts`. + size_t attempt = 1; + size_t attempts = 0; + // From 1, of `tries`. + size_t try_number = 1; + size_t tries = 0; + uint64_t resets = 0; + uint64_t max_resets = 0; + uint16_t seed = 0; + uint64_t advances = 0; + // The SIDs the attempt is shiny for, and those ruled out so far. + std::vector sids; + std::vector ruled_out; + Milliseconds attempt_time = Milliseconds(0); + Milliseconds attempt_cap = Milliseconds(0); + Milliseconds total_time = Milliseconds(0); + Milliseconds total_cap = Milliseconds(0); + // The calibration of the last reset, in frames; none before the first. + std::optional calibration; +}; +std::string rng_log_state(const RngLoopState& state); struct StarterRngLoopLimits{ @@ -50,6 +83,21 @@ struct StarterRngLoopLimits{ Milliseconds attempt_time = Milliseconds(0); // No attempt starts after this long. Milliseconds total_time = Milliseconds(0); + // Resets per try of an attempt. + uint64_t max_resets = 0; + // The tracker's retries of a missed attempt, for the state lines. + size_t max_retries = 0; +}; + +// One try of an attempt, as the loop asks the steps for it. +struct StarterRngAttemptCall{ + // From 0. + size_t index = 0; + // No reset after this. + WallClock deadline; + uint64_t max_resets = 0; + // To call after each reset. + std::function on_reset; }; // The game steps of the loop, injected so that its decisions run in tests @@ -58,9 +106,9 @@ class StarterRngLoopSteps{ public: virtual ~StarterRngLoopSteps() = default; virtual WallClock now() = 0; - // Runs Starter RNG's attempts at attempt `index` (from 0) from the save - // under the ball, making no reset after `deadline`. - virtual StarterRngOutcome run_attempt(size_t index, const RngAttempt& attempt, WallClock deadline) = 0; + // Runs Starter RNG's attempts at `attempt`'s target from the save under + // the ball, as `call` says. + virtual StarterRngResult run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call) = 0; }; enum class StarterRngLoopEnd{ @@ -88,9 +136,10 @@ struct StarterRngLoopResult{ }; // Runs `tracker`'s attempts through `steps` until the plan ends or -// `limits.total_time` has passed. Logs an "RngPlan: result" line per -// attempt and, when a shiny leaves one SID, an "RngPlan: confirmed" line -// placing it among SID Helper's candidates for `tid`. +// `limits.total_time` has passed. Logs an "RngPlan: state" line at the +// start of each try and after each reset, an "RngPlan: result" line after +// it and, when a shiny leaves one SID, an "RngPlan: confirmed" line placing +// it among SID Helper's candidates for `tid`. StarterRngLoopResult run_starter_rng_plan( Logger& logger, RngPlanTracker& tracker, StarterRngLoopSteps& steps, const StarterRngLoopLimits& limits, uint16_t tid, const std::vector& sid_helper_candidates @@ -99,6 +148,7 @@ StarterRngLoopResult run_starter_rng_plan( // What the run says when the loop ends with `result`. std::string starter_rng_loop_message(const StarterRngLoopResult& result); + // The rows a run takes after a shiny from the loop, which leaves the player // under Squirtle's ball with the rival's ball taken: the row after // `ball_row` (00.04b) from its step after "rival_takes_bulbasaur", then @@ -109,15 +159,27 @@ std::vector rows_after_starter_rng( ); +// The console's log, with the loop's state and result lines also on the +// stream's overlay log. +class RngPlanLogger : public Logger{ +public: + explicit RngPlanLogger(ConsoleHandle& console); + virtual void log(const std::string& msg, Color color = Color()) override; + +private: + ConsoleHandle& m_console; +}; + + struct StarterRngConsoleSettings{ Language language = Language::English; SoundSetting sound = SoundSetting::Mono; - uint64_t max_resets = 0; }; // The loop's steps on the console, with Starter RNG's displays, stats and -// calibration kept here (AutoStory doesn't show them). Squirtle, FireRed, -// the Switch's default profile. +// calibration kept here (AutoStory doesn't show them). Each try starts +// from the calibration the last one ended with. Squirtle, FireRed, the +// Switch's default profile. class ConsoleStarterRngSteps : public StarterRngLoopSteps{ public: ConsoleStarterRngSteps( @@ -126,7 +188,7 @@ class ConsoleStarterRngSteps : public StarterRngLoopSteps{ ); virtual WallClock now() override; - virtual StarterRngOutcome run_attempt(size_t index, const RngAttempt& attempt, WallClock deadline) override; + virtual StarterRngResult run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call) override; private: SingleSwitchProgramEnvironment& m_env; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp index 9f12d992e2..8e71666582 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp @@ -2,8 +2,8 @@ * * From: https://github.com/PokemonAutomation/ * - * The Starter RNG loop's decisions on scripted attempt outcomes and a fake - * clock, and the rows a run takes after a shiny. + * The Starter RNG loop's decisions and log lines on scripted attempt + * outcomes and a fake clock, and the rows a run takes after a shiny. * */ @@ -56,8 +56,9 @@ class LineLogger : public Logger{ std::vector lines; }; -// Each attempt takes `minutes_per_attempt` on the clock and comes out as -// the next of `outcomes`. +// Each try takes `minutes_per_attempt` on the clock, makes one reset at +// its end with calibration 1.5/-2/0.25 frames, and comes out as the next +// of `outcomes`. class ScriptedSteps : public StarterRngLoopSteps{ public: ScriptedSteps(std::vector outcomes, int minutes_per_attempt) @@ -68,14 +69,15 @@ class ScriptedSteps : public StarterRngLoopSteps{ virtual WallClock now() override{ return m_now; } - virtual StarterRngOutcome run_attempt(size_t index, const RngAttempt&, WallClock deadline) override{ + virtual StarterRngResult run_attempt(const RngAttempt&, const StarterRngAttemptCall& call) override{ if (m_next >= m_outcomes.size()){ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "More attempts than scripted."); } - indices.push_back(index); - deadlines_min.push_back(int(std::chrono::duration_cast(deadline - START).count())); + indices.push_back(call.index); + deadlines_min.push_back(int(std::chrono::duration_cast(call.deadline - START).count())); m_now += std::chrono::minutes(m_minutes); - return m_outcomes[m_next++]; + call.on_reset(StarterRngProgress{.resets = 1, .calibrations = {1.5, -2, 0.25}}); + return StarterRngResult{.outcome = m_outcomes[m_next++], .pokemon = std::nullopt}; } std::vector indices; @@ -96,16 +98,22 @@ const std::vector CANDIDATES = {{100, 1}, {200, 2}, {300, 1}}; std::vector attempts(){ RngAttempt first{}; + first.target.seed.seed = 0xceff; + first.target.advances = 983; first.sids = {100, 200}; RngAttempt second{}; + second.target.seed.seed = 0x2ef6; + second.target.advances = 29364; second.sids = {300}; return {first, second}; } -// 60-minute attempts, 12 hours in all. +// 60-minute tries, 12 hours in all, 50 resets a try, 2 retries. const StarterRngLoopLimits LIMITS{ .attempt_time = std::chrono::minutes(60), .total_time = std::chrono::hours(12), + .max_resets = 50, + .max_retries = 2, }; std::string end_name(StarterRngLoopEnd end){ @@ -143,8 +151,8 @@ struct LoopRow{ std::string attempts_run; // The SID confirmed, or 0 for none. uint16_t sid; - // A log line the loop must write; empty for none. - std::string line; + // Log lines the loop must write. + std::vector lines; }; const std::vector LOOP_ROWS = { @@ -153,49 +161,67 @@ const std::vector LOOP_ROWS = { .outcomes = {StarterRngOutcome::target_hit, StarterRngOutcome::shiny}, .minutes_per_attempt = 30, .shiny_required = true, .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,2", .sid = 300, - .line = "RngPlan: confirmed tid=12345 sid=300 candidate=3 of=3", + .lines = { + "RngPlan: state attempt=1/2 try=1/3 reset=0/50 seed=CEFF advances=983 sids=100,200 ruled_out=- " + "attempt_time=00:00:00/01:00:00 total_time=00:00:00/12:00:00 calibration=-", + "RngPlan: state attempt=1/2 try=1/3 reset=1/50 seed=CEFF advances=983 sids=100,200 ruled_out=- " + "attempt_time=00:30:00/01:00:00 total_time=00:30:00/12:00:00 calibration=1.50/-2.00/0.25", + "RngPlan: result attempt=1 try=1 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=next_attempt", + "RngPlan: state attempt=2/2 try=1/3 reset=0/50 seed=2EF6 advances=29364 sids=300 ruled_out=100,200 " + "attempt_time=00:00:00/01:00:00 total_time=00:30:00/12:00:00 calibration=-", + "RngPlan: result attempt=2 try=1 outcome=shiny starter_rng=shiny nature=- ivs=- pid=- next=confirm", + "RngPlan: confirmed tid=12345 sid=300 candidate=3 of=3", + }, }, { .name = "shiny for two SIDs confirms none", .outcomes = {StarterRngOutcome::shiny}, .minutes_per_attempt = 30, .shiny_required = true, .end = StarterRngLoopEnd::SHINY, .attempts_run = "1", .sid = 0, - .line = "RngPlan: result attempt=1 outcome=SHINY", + .lines = {"RngPlan: result attempt=1 try=1 outcome=shiny starter_rng=shiny nature=- ivs=- pid=- next=confirm"}, }, { .name = "misses retry the same attempt", .outcomes = {StarterRngOutcome::out_of_resets, StarterRngOutcome::no_matches, StarterRngOutcome::shiny}, .minutes_per_attempt = 30, .shiny_required = true, .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,1", .sid = 0, - .line = "RngPlan: result attempt=1 outcome=MISSED", + .lines = { + "RngPlan: result attempt=1 try=1 outcome=missed starter_rng=out_of_resets nature=- ivs=- pid=- next=retry", + "RngPlan: result attempt=1 try=2 outcome=missed starter_rng=no_matches nature=- ivs=- pid=- next=retry", + "RngPlan: result attempt=1 try=3 outcome=shiny starter_rng=shiny nature=- ivs=- pid=- next=confirm", + }, }, { .name = "too many misses stop", .outcomes = {StarterRngOutcome::out_of_resets, StarterRngOutcome::out_of_resets, StarterRngOutcome::wild_shiny}, .minutes_per_attempt = 30, .shiny_required = true, .end = StarterRngLoopEnd::OUT_OF_RETRIES, .attempts_run = "1,1,1", .sid = 0, - .line = "", + .lines = {"RngPlan: result attempt=1 try=3 outcome=missed starter_rng=wild_shiny nature=- ivs=- pid=- next=stop"}, }, { .name = "every attempt hit, none shiny", .outcomes = {StarterRngOutcome::target_hit, StarterRngOutcome::target_hit}, .minutes_per_attempt = 30, .shiny_required = true, .end = StarterRngLoopEnd::OUT_OF_ATTEMPTS, .attempts_run = "1,2", .sid = 0, - .line = "RngPlan: result attempt=2 outcome=HIT_NOT_SHINY", + .lines = {"RngPlan: result attempt=2 try=1 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=stop"}, }, { .name = "a hit ends the plan with shiny not required", .outcomes = {StarterRngOutcome::target_hit}, .minutes_per_attempt = 30, .shiny_required = false, .end = StarterRngLoopEnd::TARGET, .attempts_run = "1", .sid = 0, - .line = "", + .lines = {}, }, { .name = "no attempt starts after the total time", .outcomes = {StarterRngOutcome::out_of_resets, StarterRngOutcome::out_of_resets}, .minutes_per_attempt = 400, .shiny_required = true, .end = StarterRngLoopEnd::OUT_OF_TIME, .attempts_run = "1,1", .sid = 0, - .line = "RngPlan: out of time before attempt 1", + .lines = { + "RngPlan: state attempt=1/2 try=2/3 reset=1/50 seed=CEFF advances=983 sids=100,200 ruled_out=- " + "attempt_time=06:40:00/01:00:00 total_time=13:20:00/12:00:00 calibration=1.50/-2.00/0.25", + "RngPlan: out of time before attempt 1", + }, }, }; @@ -212,8 +238,10 @@ UnitTestResult run_loop_row(const LoopRow& row){ if (expected != got){ return "Expected " + expected + "; got " + got; } - if (!row.line.empty() && !logger.has(row.line)){ - return "Expected the log line \"" + row.line + "\""; + for (const std::string& line : row.lines){ + if (!logger.has(line)){ + return "Expected the log line \"" + line + "\""; + } } if (result.attempts_run != steps.indices.size()){ return std::format("Expected attempts_run {}; got {}", steps.indices.size(), result.attempts_run); @@ -229,7 +257,9 @@ UnitTestResult test_deadlines(){ RngPlanTracker tracker(attempts(), CANDIDATES, true, 5); ScriptedSteps steps({StarterRngOutcome::out_of_resets, StarterRngOutcome::out_of_resets}, 400); LineLogger logger; - const StarterRngLoopLimits limits{.attempt_time = std::chrono::minutes(60), .total_time = std::chrono::minutes(430)}; + const StarterRngLoopLimits limits{ + .attempt_time = std::chrono::minutes(60), .total_time = std::chrono::minutes(430), .max_resets = 50, .max_retries = 5, + }; run_starter_rng_plan(logger, tracker, steps, limits, 12345, CANDIDATES); std::string got; for (int deadline : steps.deadlines_min){ @@ -242,6 +272,25 @@ UnitTestResult test_deadlines(){ } +// The state line on its own: hours, empty lists and a negative offset. +UnitTestResult test_state_line(){ + const std::string got = rng_log_state(RngLoopState{ + .attempt = 3, .attempts = 5, .try_number = 2, .tries = 3, .resets = 41, .max_resets = 50, + .seed = 0x70fe, .advances = 1200, .sids = {}, .ruled_out = {7, 8}, + .attempt_time = std::chrono::seconds(3 * 3600 + 61), .attempt_cap = std::chrono::hours(3), + .total_time = std::chrono::minutes(605), .total_cap = std::chrono::hours(12), + .calibration = RngCalibrations{-0.5, 12, -3.125}, + }); + const std::string expected = + "RngPlan: state attempt=3/5 try=2/3 reset=41/50 seed=70FE advances=1200 sids=- ruled_out=7,8 " + "attempt_time=03:01:01/03:00:00 total_time=10:05:00/12:00:00 calibration=-0.50/12.00/-3.12"; + if (got != expected){ + return "Expected \"" + expected + "\", got \"" + got + "\"."; + } + return true; +} + + // After a shiny, 00.04b picks up at the rival's trigger and runs on. UnitTestResult test_rows_after_shiny(){ const std::vector& checkpoints = story_checkpoints(); @@ -288,6 +337,7 @@ void add_tests_AutoStoryRngLoop(UnitTestDatabase& database){ database.add(row.name, [row]{ return run_loop_row(row); }); } database.add("attempt deadlines", test_deadlines); + database.add("state line", test_state_line); database.add("rows after a shiny", test_rows_after_shiny); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngPlan.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngPlan.cpp index 615299ec59..6b1f6fc51f 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngPlan.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngPlan.cpp @@ -349,14 +349,61 @@ std::string rng_log_attempt(size_t index, const RngAttempt& attempt){ ); } -std::string rng_log_result(size_t index, RngAttemptOutcome outcome){ - const char* name = "MISSED"; - if (outcome == RngAttemptOutcome::SHINY){ - name = "SHINY"; - }else if (outcome == RngAttemptOutcome::HIT_NOT_SHINY){ - name = "HIT_NOT_SHINY"; +RngPlanNext rng_plan_next(RngPlanStep step, size_t index, size_t next_index){ + switch (step){ + case RngPlanStep::RUN_ATTEMPT: + return next_index == index ? RngPlanNext::RETRY : RngPlanNext::NEXT_ATTEMPT; + case RngPlanStep::GOT_SHINY: + return RngPlanNext::CONFIRM; + case RngPlanStep::GOT_TARGET: + case RngPlanStep::OUT_OF_ATTEMPTS: + case RngPlanStep::OUT_OF_RETRIES: + return RngPlanNext::STOP; } - return std::format("RngPlan: result attempt={} outcome={}", index + 1, name); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RngPlanStep."); +} + +namespace{ + +const char* outcome_name(RngAttemptOutcome outcome){ + switch (outcome){ + case RngAttemptOutcome::SHINY: + return "shiny"; + case RngAttemptOutcome::HIT_NOT_SHINY: + return "hit_not_shiny"; + case RngAttemptOutcome::MISSED: + return "missed"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RngAttemptOutcome."); +} + +const char* next_name(RngPlanNext next){ + switch (next){ + case RngPlanNext::RETRY: + return "retry"; + case RngPlanNext::NEXT_ATTEMPT: + return "next_attempt"; + case RngPlanNext::CONFIRM: + return "confirm"; + case RngPlanNext::STOP: + return "stop"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RngPlanNext."); +} + +} + +std::string rng_log_result(const RngResultLog& result){ + const std::optional& pokemon = result.pokemon; + return std::format( + "RngPlan: result attempt={} try={} outcome={} starter_rng={} nature={} ivs={} pid={} next={}", + result.index + 1, result.try_number, outcome_name(result.outcome), + result.detail.empty() ? "-" : result.detail, + pokemon ? nature_to_string(pokemon->nature) : "-", + pokemon ? ivs_to_string(pokemon->ivs) : "-", + pokemon ? std::format("{:08X}", pokemon->pid) : "-", + next_name(result.next) + ); } std::string rng_log_confirmed(uint16_t tid, uint16_t sid, const std::vector& sid_helper_candidates){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngPlan.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngPlan.h index bb338e0d4b..7487320295 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngPlan.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngPlan.h @@ -116,6 +116,7 @@ class RngPlanTracker{ RngPlanStep step() const{ return m_step; } size_t attempt_index() const{ return m_attempt; } + size_t attempt_count() const{ return m_attempts.size(); } const RngAttempt& current_attempt() const{ return m_attempts[m_attempt]; } // The SID candidates not ruled out, in the order given. const std::vector& remaining_sids() const{ return m_remaining; } @@ -164,12 +165,22 @@ std::vector rng_attempt_lines(const std::vector& attemp // The data to rebuild how likely SID Helper's k-th candidate of N is (the // 1-2-3-2-1 weights of sid_helper_candidates() are a guess), from the logs -// alone. Every line starts with "RngPlan:"; grep for it: +// alone, and to follow AutoStory's Starter RNG loop. Every line starts with +// "RngPlan:"; grep for it. In the order a run logs them: // RngPlan: tid= source= // RngPlan: sid_helper tid= target_advances= candidates=,... // RngPlan: attempt= seed= advances= sids=,... -// RngPlan: result attempt= outcome= +// then, with Run Starter RNG in AutoStory, for each try of an attempt +// (rng_log_state() in PokemonFRLG_AutoStoryRngLoop.h): +// RngPlan: state attempt=/ try=/ reset=/ seed= +// advances= sids=,... ruled_out=,... attempt_time=/ +// total_time=/ calibration=// +// (once at the try's start, then after every reset) +// RngPlan: result attempt= try= outcome= +// starter_rng= nature= ivs= +// pid= next= // RngPlan: confirmed tid= sid= candidate= of= +// Lists that are empty print "-". // "candidates" are in SID Helper's order; "candidate=k" counts from 1 in // it, 0 when the SID wasn't among them. Count each TID's "confirmed" once: // every later run with the SID set logs it again. While the user runs @@ -178,7 +189,30 @@ std::vector rng_attempt_lines(const std::vector& attemp std::string rng_log_tid(uint16_t tid, bool from_card); std::string rng_log_sid_helper(uint16_t tid, uint32_t target_advances, const std::vector& candidates); std::string rng_log_attempt(size_t index, const RngAttempt& attempt); -std::string rng_log_result(size_t index, RngAttemptOutcome outcome); +// What the loop does after an attempt's result. +enum class RngPlanNext{ + RETRY, + NEXT_ATTEMPT, + // Shiny: go on with the story. + CONFIRM, + STOP, +}; +// The step after `index` came out as the tracker's `step` and its attempt +// is now `next_index`. +RngPlanNext rng_plan_next(RngPlanStep step, size_t index, size_t next_index); + +struct RngResultLog{ + size_t index = 0; + // From 1. + size_t try_number = 1; + RngAttemptOutcome outcome = RngAttemptOutcome::MISSED; + // How the RNG program put it ("out_of_resets"); empty for none. + std::string detail; + // The Pokemon hit, when known. + std::optional pokemon; + RngPlanNext next = RngPlanNext::STOP; +}; +std::string rng_log_result(const RngResultLog& result); std::string rng_log_confirmed(uint16_t tid, uint16_t sid, const std::vector& sid_helper_candidates); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngPlan_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngPlan_Tests.cpp index 3b83e60d78..ad1870f95c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngPlan_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngPlan_Tests.cpp @@ -404,7 +404,23 @@ UnitTestResult test_log_lines(Logger&){ {.got = rng_log_tid(43771, false), .expected = "RngPlan: tid=43771 source=option"}, {.got = rng_log_sid_helper(43771, 3001, CANDIDATES), .expected = "RngPlan: sid_helper tid=43771 target_advances=3001 candidates=100,200,300"}, {.got = rng_log_attempt(0, attempt), .expected = "RngPlan: attempt=1 seed=2EF6 advances=29364 sids=100,200"}, - {.got = rng_log_result(1, RngAttemptOutcome::HIT_NOT_SHINY), .expected = "RngPlan: result attempt=2 outcome=HIT_NOT_SHINY"}, + { + .got = rng_log_result(RngResultLog{ + .index = 1, .try_number = 2, .outcome = RngAttemptOutcome::HIT_NOT_SHINY, .detail = "target_hit", + .pokemon = attempt.target.pokemon, .next = RngPlanNext::NEXT_ATTEMPT, + }), + .expected = std::format( + "RngPlan: result attempt=2 try=2 outcome=hit_not_shiny starter_rng=target_hit nature={} ivs={} pid={:08X} next=next_attempt", + nature_to_string(attempt.target.pokemon.nature), ivs_to_string(attempt.target.pokemon.ivs), attempt.target.pokemon.pid + ), + }, + { + .got = rng_log_result(RngResultLog{ + .index = 0, .try_number = 1, .outcome = RngAttemptOutcome::MISSED, .detail = "out_of_resets", + .pokemon = std::nullopt, .next = RngPlanNext::RETRY, + }), + .expected = "RngPlan: result attempt=1 try=1 outcome=missed starter_rng=out_of_resets nature=- ivs=- pid=- next=retry", + }, {.got = rng_log_confirmed(43771, 300, CANDIDATES), .expected = "RngPlan: confirmed tid=43771 sid=300 candidate=3 of=3"}, {.got = rng_log_confirmed(43771, 7, CANDIDATES), .expected = "RngPlan: confirmed tid=43771 sid=7 candidate=0 of=3"}, }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp index de660ef6f0..66930704ad 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.cpp @@ -221,12 +221,9 @@ void StarterRng::program(SingleSwitchProgramEnvironment& env, ProControllerConte .ignore_wild_shinies = IGNORE_WILD_SHINIES, .take_video = TAKE_VIDEO, .max_resets = [this]{ return uint64_t(MAX_RESETS); }, + .on_reset = nullptr, }, - StarterRngDisplays{ - .target = RNG_TARGET, - .filters = RNG_FILTERS, - .calibration = RNG_CALIBRATION, - }, + StarterRngDisplays{.target = RNG_TARGET, .filters = RNG_FILTERS, .calibration = RNG_CALIBRATION}, StarterRngNotifications{ .shiny = NOTIFICATION_SHINY, .status_update = NOTIFICATION_STATUS_UPDATE, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp index 1db4d785fc..188cbfe787 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp @@ -214,6 +214,9 @@ void StarterRngAttempts::reset_game(SingleSwitchProgramEnvironment& env, ProCont m_launch_delay, false, m_settings.profile ); m_stats.resets++; + if (m_settings.on_reset){ + m_settings.on_reset(StarterRngProgress{.resets = m_stats.resets.load(), .calibrations = m_calibrations}); + } m_displays.filters.reset(); m_displays.calibration.set_calibrations(m_calibrations); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h index 5d8430867e..82ab0431bf 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h @@ -66,6 +66,13 @@ struct StarterRngTarget{ SeedMatch seed_match; }; +// Where an attempt is after a reset: the resets so far, and the +// calibration that reset was timed with. +struct StarterRngProgress{ + uint64_t resets = 0; + RngCalibrations calibrations{}; +}; + struct StarterRngSettings{ Language language = Language::None; // The Switch profile's position on the user selection screen; 0 for @@ -77,6 +84,8 @@ struct StarterRngSettings{ // Read before each reset, since Starter RNG lets the user change it // while running. std::function max_resets; + // Called after each reset, if set, for a caller that logs the attempts. + std::function on_reset; }; // Where the attempts show the target, the filters read so far and the From 3b2e851d8f7d76073f8e0398412ed75cbdc06e0e Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 16:58:09 -0800 Subject: [PATCH 03/10] FRLG AutoStory: a shiny off the target doesn't confirm a SID; misses move on Starter RNG's attempts now tell whether a shiny was the target (identify_shiny, #183). Only a shiny on the target narrows the SIDs; one off it, or not known to be on it, ends the loop as SHINY_OFF_TARGET with no SID confirmed and no "RngPlan: confirmed" line. Its result line says outcome=shiny_off_target next=stop. Either shiny goes on with the story. The result line names a try that ran past its deadline attempt_deadline, apart from out_of_resets, no_matches and wild_shiny; all still count as a miss. An attempt missed more often than the retries allow moves on to the next one still shiny for a SID left (#182), and the run stops only when none is left (MISSED_EVERY_ATTEMPT_LEFT). A shiny for none of the SIDs left no longer says "one of" an empty list. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../AutoStory/PokemonFRLG_AutoStory.cpp | 6 +- .../PokemonFRLG_AutoStoryRngLoop.cpp | 45 +++++-- .../AutoStory/PokemonFRLG_AutoStoryRngLoop.h | 20 ++- .../PokemonFRLG_AutoStoryRngLoop_Tests.cpp | 122 +++++++++++++++--- 4 files changed, 155 insertions(+), 38 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index 547543e5fc..c41395e0d0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -400,8 +400,8 @@ const StarterRngLoopLimits STARTER_RNG_LIMITS{ } // Starter RNG's attempts in the program, from the save south of the table. -// Returns true for a shiny Squirtle, the game on its summary; otherwise the -// run has stopped with what to do next. +// Returns true for a shiny Squirtle, on the target or not, the game on its +// summary; otherwise the run has stopped with what to do next. static bool run_starter_rng_in_program( SingleSwitchProgramEnvironment& env, ProControllerContext& context, const StarterRngPlanned& planned, const StarterRngPlanOptions& options, Language language, @@ -418,7 +418,7 @@ static bool run_starter_rng_in_program( logger, tracker, steps, STARTER_RNG_LIMITS, planned.tid, options.helper_candidates(planned.tid) ); const std::string message = starter_rng_loop_message(result); - if (result.end != StarterRngLoopEnd::SHINY){ + if (result.end != StarterRngLoopEnd::SHINY && result.end != StarterRngLoopEnd::SHINY_OFF_TARGET){ stop_for_handoff(env, finished, message); return false; } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp index df3b211ac3..8925c1fca3 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp @@ -17,8 +17,11 @@ namespace PokemonFRLG{ RngAttemptOutcome plan_outcome(StarterRngOutcome outcome){ switch (outcome){ - case StarterRngOutcome::shiny: + case StarterRngOutcome::shiny_on_target: return RngAttemptOutcome::SHINY; + case StarterRngOutcome::shiny: + case StarterRngOutcome::shiny_off_target: + return RngAttemptOutcome::SHINY_OFF_TARGET; case StarterRngOutcome::target_hit: return RngAttemptOutcome::HIT_NOT_SHINY; case StarterRngOutcome::wild_shiny: @@ -33,6 +36,10 @@ std::string starter_rng_outcome_name(StarterRngOutcome outcome){ switch (outcome){ case StarterRngOutcome::shiny: return "shiny"; + case StarterRngOutcome::shiny_on_target: + return "shiny_on_target"; + case StarterRngOutcome::shiny_off_target: + return "shiny_off_target"; case StarterRngOutcome::target_hit: return "target_hit"; case StarterRngOutcome::wild_shiny: @@ -92,12 +99,14 @@ std::optional loop_end(RngPlanStep step){ return std::nullopt; case RngPlanStep::GOT_SHINY: return StarterRngLoopEnd::SHINY; + case RngPlanStep::GOT_SHINY_OFF_TARGET: + return StarterRngLoopEnd::SHINY_OFF_TARGET; case RngPlanStep::GOT_TARGET: return StarterRngLoopEnd::TARGET; case RngPlanStep::OUT_OF_ATTEMPTS: return StarterRngLoopEnd::OUT_OF_ATTEMPTS; - case RngPlanStep::OUT_OF_RETRIES: - return StarterRngLoopEnd::OUT_OF_RETRIES; + case RngPlanStep::MISSED_EVERY_ATTEMPT_LEFT: + return StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT; } throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RNG plan step."); } @@ -159,13 +168,13 @@ class LoopLog{ // Runs one try of the tracker's current attempt, logging its state lines. StarterRngResult run_try( LoopLog& log, const RngPlanTracker& tracker, StarterRngLoopSteps& steps, - const StarterRngLoopLimits& limits, WallClock start, WallClock total_deadline + const StarterRngLoopLimits& limits, WallClock start, WallClock deadline ){ log.begin_try(start); log.log_state(start, 0, std::nullopt); StarterRngAttemptCall call{ .index = tracker.attempt_index(), - .deadline = std::min(start + limits.attempt_time, total_deadline), + .deadline = deadline, .max_resets = limits.max_resets, .on_reset = [&](const StarterRngProgress& progress){ log.log_state(steps.now(), progress.resets, progress.calibrations); @@ -198,13 +207,16 @@ StarterRngLoopResult run_starter_rng_plan( break; } const size_t index = tracker.attempt_index(); - const StarterRngResult attempt = run_try(log, tracker, steps, limits, start, total_deadline); + const WallClock deadline = std::min(start + limits.attempt_time, total_deadline); + const StarterRngResult attempt = run_try(log, tracker, steps, limits, start, deadline); + // The deadline ends a try as out of resets. + const bool past_deadline = attempt.outcome == StarterRngOutcome::out_of_resets && steps.now() >= deadline; const RngAttemptOutcome outcome = plan_outcome(attempt.outcome); result.attempts_run++; const RngPlanStep step = tracker.record(outcome); logger.log(rng_log_result(RngResultLog{ .index = index, .try_number = log.try_number(), .outcome = outcome, - .detail = starter_rng_outcome_name(attempt.outcome), .pokemon = attempt.pokemon, + .detail = past_deadline ? "attempt_deadline" : starter_rng_outcome_name(attempt.outcome), .pokemon = attempt.pokemon, .next = rng_plan_next(step, index, tracker.attempt_index()), })); } @@ -220,9 +232,17 @@ std::string starter_rng_loop_message(const StarterRngLoopResult& result){ const std::string sids = join_sids(result.remaining_sids); switch (result.end){ case StarterRngLoopEnd::SHINY: - return result.sid - ? std::format("Starter RNG: shiny Squirtle. The SID is {}: enter it as the RNG plan's SID.", *result.sid) - : std::format("Starter RNG: shiny Squirtle. The SID is one of {}.", sids); + if (result.sid){ + return std::format("Starter RNG: shiny Squirtle. The SID is {}: enter it as the RNG plan's SID.", *result.sid); + } + if (result.remaining_sids.empty()){ + return "Starter RNG: shiny Squirtle, for none of the SID candidates left: the SID isn't one of SID Helper's candidates."; + } + return std::format("Starter RNG: shiny Squirtle. The SID is one of {}.", sids); + case StarterRngLoopEnd::SHINY_OFF_TARGET: + return std::format( + "Starter RNG: shiny Squirtle, but not the planned target, so it doesn't tell the SID. SIDs left: {}.", sids + ); case StarterRngLoopEnd::TARGET: return "Starter RNG hit the target (shiny not required). Nothing was saved after it: the game is where " "Starter RNG's calibration left it. Play to the rival's battle and save by hand, then start AutoStory at 00.05."; @@ -231,8 +251,8 @@ std::string starter_rng_loop_message(const StarterRngLoopResult& result){ "Starter RNG: every planned attempt hit its target and none was shiny. SIDs left: {}. " "The save is still south of the table: raise the RNG plan's max attempts and start AutoStory at 00.04 again.", sids ); - case StarterRngLoopEnd::OUT_OF_RETRIES: - return "Starter RNG: one attempt missed its target more often than the retries allow. " + case StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT: + return "Starter RNG: every attempt left missed its target more often than the retries allow. " "The save is still south of the table: check the RNG plan's sound setting and start AutoStory at 00.04 again."; case StarterRngLoopEnd::OUT_OF_TIME: return std::format( @@ -318,6 +338,7 @@ StarterRngResult ConsoleStarterRngSteps::run_attempt(const RngAttempt& attempt, .profile = 0, .ignore_wild_shinies = true, .take_video = false, + .identify_shiny = true, .max_resets = [deadline = call.deadline, max_resets = call.max_resets]{ return current_time() >= deadline ? uint64_t(0) : max_resets; }, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h index ad39addebd..598ad9122c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h @@ -46,10 +46,14 @@ struct StarterRngPlanned{ std::vector attempts; }; -// Starter RNG's outcome as the RNG plan counts it. Out of resets, no -// matches and a wild shiny are misses, which the plan runs again. +// Starter RNG's outcome as the RNG plan counts it. Only a shiny on the +// target is SHINY; one off it, or not known to be on it, is +// SHINY_OFF_TARGET. Out of resets, no matches and a wild shiny are misses, +// which the plan runs again. RngAttemptOutcome plan_outcome(StarterRngOutcome outcome); -// As the result line names it: "shiny", "target_hit", "out_of_resets"... +// As the result line names it: "shiny_on_target", "target_hit", +// "out_of_resets"... (The loop says "attempt_deadline" instead of +// "out_of_resets" once the try's deadline has passed.) std::string starter_rng_outcome_name(StarterRngOutcome outcome); @@ -112,15 +116,19 @@ class StarterRngLoopSteps{ }; enum class StarterRngLoopEnd{ - // The starter is shiny; the game is on its summary, not saved. + // The starter is shiny and the target; the game is on its summary, not saved. SHINY, + // The starter is shiny but not the target (or not known to be), so it + // doesn't tell the SID; the game is on its summary, not saved. + SHINY_OFF_TARGET, // Shiny not required, and the target was hit. The game is where // Starter RNG's calibration left it, not saved. TARGET, // Every attempt was hit and none was shiny. OUT_OF_ATTEMPTS, - // One attempt missed more often than the retries allow. - OUT_OF_RETRIES, + // The last attempt still shiny for a SID left missed more often than + // the retries allow. + MISSED_EVERY_ATTEMPT_LEFT, // The total time ran out with attempts left. OUT_OF_TIME, }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp index 8e71666582..ef6b693001 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp @@ -120,12 +120,14 @@ std::string end_name(StarterRngLoopEnd end){ switch (end){ case StarterRngLoopEnd::SHINY: return "SHINY"; + case StarterRngLoopEnd::SHINY_OFF_TARGET: + return "SHINY_OFF_TARGET"; case StarterRngLoopEnd::TARGET: return "TARGET"; case StarterRngLoopEnd::OUT_OF_ATTEMPTS: return "OUT_OF_ATTEMPTS"; - case StarterRngLoopEnd::OUT_OF_RETRIES: - return "OUT_OF_RETRIES"; + case StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT: + return "MISSED_EVERY_ATTEMPT_LEFT"; case StarterRngLoopEnd::OUT_OF_TIME: return "OUT_OF_TIME"; } @@ -149,16 +151,18 @@ struct LoopRow{ StarterRngLoopEnd end; // The attempts run, from 1, as "1,1,2". std::string attempts_run; - // The SID confirmed, or 0 for none. + // The SID confirmed, or 0 for none; with it, an "RngPlan: confirmed" line. uint16_t sid; // Log lines the loop must write. std::vector lines; }; +using enum StarterRngOutcome; + const std::vector LOOP_ROWS = { { .name = "hit, then shiny confirms the SID", - .outcomes = {StarterRngOutcome::target_hit, StarterRngOutcome::shiny}, + .outcomes = {target_hit, shiny_on_target}, .minutes_per_attempt = 30, .shiny_required = true, .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,2", .sid = 300, .lines = { @@ -169,52 +173,94 @@ const std::vector LOOP_ROWS = { "RngPlan: result attempt=1 try=1 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=next_attempt", "RngPlan: state attempt=2/2 try=1/3 reset=0/50 seed=2EF6 advances=29364 sids=300 ruled_out=100,200 " "attempt_time=00:00:00/01:00:00 total_time=00:30:00/12:00:00 calibration=-", - "RngPlan: result attempt=2 try=1 outcome=shiny starter_rng=shiny nature=- ivs=- pid=- next=confirm", + "RngPlan: result attempt=2 try=1 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", "RngPlan: confirmed tid=12345 sid=300 candidate=3 of=3", }, }, { - .name = "shiny for two SIDs confirms none", - .outcomes = {StarterRngOutcome::shiny}, + .name = "shiny on the target for two SIDs confirms none", + .outcomes = {shiny_on_target}, .minutes_per_attempt = 30, .shiny_required = true, .end = StarterRngLoopEnd::SHINY, .attempts_run = "1", .sid = 0, - .lines = {"RngPlan: result attempt=1 try=1 outcome=shiny starter_rng=shiny nature=- ivs=- pid=- next=confirm"}, + .lines = {"RngPlan: result attempt=1 try=1 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm"}, + }, + { + .name = "shiny off the target confirms nothing", + .outcomes = {target_hit, shiny_off_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY_OFF_TARGET, .attempts_run = "1,2", .sid = 0, + .lines = {"RngPlan: result attempt=2 try=1 outcome=shiny_off_target starter_rng=shiny_off_target nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "a shiny not known to be the target confirms nothing", + .outcomes = {shiny}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY_OFF_TARGET, .attempts_run = "1", .sid = 0, + .lines = {"RngPlan: result attempt=1 try=1 outcome=shiny_off_target starter_rng=shiny nature=- ivs=- pid=- next=stop"}, }, { .name = "misses retry the same attempt", - .outcomes = {StarterRngOutcome::out_of_resets, StarterRngOutcome::no_matches, StarterRngOutcome::shiny}, + .outcomes = {out_of_resets, no_matches, shiny_on_target}, .minutes_per_attempt = 30, .shiny_required = true, .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,1", .sid = 0, .lines = { "RngPlan: result attempt=1 try=1 outcome=missed starter_rng=out_of_resets nature=- ivs=- pid=- next=retry", "RngPlan: result attempt=1 try=2 outcome=missed starter_rng=no_matches nature=- ivs=- pid=- next=retry", - "RngPlan: result attempt=1 try=3 outcome=shiny starter_rng=shiny nature=- ivs=- pid=- next=confirm", + "RngPlan: result attempt=1 try=3 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", }, }, { - .name = "too many misses stop", - .outcomes = {StarterRngOutcome::out_of_resets, StarterRngOutcome::out_of_resets, StarterRngOutcome::wild_shiny}, + .name = "an attempt past its deadline", + .outcomes = {out_of_resets, shiny_on_target}, + .minutes_per_attempt = 90, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1", .sid = 0, + .lines = {"RngPlan: result attempt=1 try=1 outcome=missed starter_rng=attempt_deadline nature=- ivs=- pid=- next=retry"}, + }, + { + .name = "retries used up, then the next attempt", + .outcomes = {out_of_resets, no_matches, wild_shiny, shiny_on_target}, .minutes_per_attempt = 30, .shiny_required = true, - .end = StarterRngLoopEnd::OUT_OF_RETRIES, .attempts_run = "1,1,1", .sid = 0, - .lines = {"RngPlan: result attempt=1 try=3 outcome=missed starter_rng=wild_shiny nature=- ivs=- pid=- next=stop"}, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,1,2", .sid = 300, + .lines = { + "RngPlan: result attempt=1 try=3 outcome=missed starter_rng=wild_shiny nature=- ivs=- pid=- next=next_attempt", + "RngPlan: result attempt=2 try=1 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", + "RngPlan: confirmed tid=12345 sid=300 candidate=3 of=3", + }, + }, + { + .name = "every attempt left missed too often", + .outcomes = {out_of_resets, out_of_resets, out_of_resets, no_matches, no_matches, no_matches}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT, .attempts_run = "1,1,1,2,2,2", .sid = 0, + .lines = {"RngPlan: result attempt=2 try=3 outcome=missed starter_rng=no_matches nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "miss, hit, miss, then shiny", + .outcomes = {out_of_resets, target_hit, no_matches, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,2,2", .sid = 300, + .lines = { + "RngPlan: result attempt=1 try=2 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=next_attempt", + "RngPlan: result attempt=2 try=2 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", + }, }, { .name = "every attempt hit, none shiny", - .outcomes = {StarterRngOutcome::target_hit, StarterRngOutcome::target_hit}, + .outcomes = {target_hit, target_hit}, .minutes_per_attempt = 30, .shiny_required = true, .end = StarterRngLoopEnd::OUT_OF_ATTEMPTS, .attempts_run = "1,2", .sid = 0, .lines = {"RngPlan: result attempt=2 try=1 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=stop"}, }, { .name = "a hit ends the plan with shiny not required", - .outcomes = {StarterRngOutcome::target_hit}, + .outcomes = {target_hit}, .minutes_per_attempt = 30, .shiny_required = false, .end = StarterRngLoopEnd::TARGET, .attempts_run = "1", .sid = 0, .lines = {}, }, { .name = "no attempt starts after the total time", - .outcomes = {StarterRngOutcome::out_of_resets, StarterRngOutcome::out_of_resets}, + .outcomes = {out_of_resets, out_of_resets}, .minutes_per_attempt = 400, .shiny_required = true, .end = StarterRngLoopEnd::OUT_OF_TIME, .attempts_run = "1,1", .sid = 0, .lines = { @@ -243,6 +289,12 @@ UnitTestResult run_loop_row(const LoopRow& row){ return "Expected the log line \"" + line + "\""; } } + const bool confirmed = std::any_of(logger.lines.begin(), logger.lines.end(), [](const std::string& line){ + return line.starts_with("RngPlan: confirmed"); + }); + if (confirmed != (row.sid != 0)){ + return std::format("Expected {} \"RngPlan: confirmed\" line", row.sid != 0 ? "a" : "no"); + } if (result.attempts_run != steps.indices.size()){ return std::format("Expected attempts_run {}; got {}", steps.indices.size(), result.attempts_run); } @@ -272,6 +324,41 @@ UnitTestResult test_deadlines(){ } +// What the run says after a shiny, by what it tells of the SID. +UnitTestResult test_shiny_messages(){ + struct Case{ + StarterRngLoopResult result; + std::string expected; + }; + const std::vector cases = { + { + .result = {.end = StarterRngLoopEnd::SHINY, .attempts_run = 2, .remaining_sids = {300}, .sid = uint16_t(300)}, + .expected = "Starter RNG: shiny Squirtle. The SID is 300: enter it as the RNG plan's SID.", + }, + { + .result = {.end = StarterRngLoopEnd::SHINY, .attempts_run = 1, .remaining_sids = {100, 200}, .sid = std::nullopt}, + .expected = "Starter RNG: shiny Squirtle. The SID is one of 100,200.", + }, + { + .result = {.end = StarterRngLoopEnd::SHINY, .attempts_run = 1, .remaining_sids = {}, .sid = std::nullopt}, + .expected = "Starter RNG: shiny Squirtle, for none of the SID candidates left: the SID isn't one of SID Helper's candidates.", + }, + { + .result = {.end = StarterRngLoopEnd::SHINY_OFF_TARGET, .attempts_run = 1, .remaining_sids = {100, 200}, .sid = std::nullopt}, + .expected = "Starter RNG: shiny Squirtle, but not the planned target, so it doesn't tell the SID. " + "SIDs left: 100,200.", + }, + }; + for (const Case& item : cases){ + const std::string got = starter_rng_loop_message(item.result); + if (got != item.expected){ + return "Expected \"" + item.expected + "\", got \"" + got + "\"."; + } + } + return true; +} + + // The state line on its own: hours, empty lists and a negative offset. UnitTestResult test_state_line(){ const std::string got = rng_log_state(RngLoopState{ @@ -338,6 +425,7 @@ void add_tests_AutoStoryRngLoop(UnitTestDatabase& database){ } database.add("attempt deadlines", test_deadlines); database.add("state line", test_state_line); + database.add("shiny messages", test_shiny_messages); database.add("rows after a shiny", test_rows_after_shiny); } From 5bbd9832aacfdd794cfcc45f4f4a531c83492ce1 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 17:14:43 -0800 Subject: [PATCH 04/10] FRLG AutoStory: skip an RNG attempt whose timings Starter RNG refuses Starter RNG refuses timings it can't press (a title screen or in-game wait too short, a negative delay) with a UserSetupError, or a failure that sends no error report (check_timings()). That ended the whole run; on console B it did for seed 11A3, whose title screen wait was under 30 s. The console steps now turn such a refusal into a UserSetupError, and the loop logs it ("RngPlan: attempt can't run: ...") and records the attempt as unusable (#182): the result line says outcome=unusable starter_rng=setup_error, and the next attempt still shiny for a SID left runs. A game failure (one that sends an error report) still ends the run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonFRLG_AutoStoryRngLoop.cpp | 56 +++++++++++++++---- .../AutoStory/PokemonFRLG_AutoStoryRngLoop.h | 5 +- .../PokemonFRLG_AutoStoryRngLoop_Tests.cpp | 35 ++++++++++-- 3 files changed, 79 insertions(+), 17 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp index 8925c1fca3..46209bd40e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp @@ -7,6 +7,7 @@ #include #include #include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" #include "CommonFramework/VideoPipeline/VideoOverlay.h" #include "PokemonFRLG_AutoStoryRngLoop.h" @@ -165,6 +166,13 @@ class LoopLog{ WallClock m_try_start; }; +// What one try came to, for the tracker and the result line. +struct TryOutcome{ + RngAttemptOutcome outcome = RngAttemptOutcome::MISSED; + std::string detail; + std::optional pokemon; +}; + // Runs one try of the tracker's current attempt, logging its state lines. StarterRngResult run_try( LoopLog& log, const RngPlanTracker& tracker, StarterRngLoopSteps& steps, @@ -183,6 +191,27 @@ StarterRngResult run_try( return steps.run_attempt(tracker.current_attempt(), call); } +// run_try(), with a setup error (Starter RNG refusing the attempt's +// timings) as an attempt that can't run. +TryOutcome run_try_outcome( + Logger& logger, LoopLog& log, const RngPlanTracker& tracker, StarterRngLoopSteps& steps, + const StarterRngLoopLimits& limits, WallClock start, WallClock deadline +){ + try{ + const StarterRngResult attempt = run_try(log, tracker, steps, limits, start, deadline); + // The deadline ends a try as out of resets. + const bool past_deadline = attempt.outcome == StarterRngOutcome::out_of_resets && steps.now() >= deadline; + return TryOutcome{ + .outcome = plan_outcome(attempt.outcome), + .detail = past_deadline ? "attempt_deadline" : starter_rng_outcome_name(attempt.outcome), + .pokemon = attempt.pokemon, + }; + }catch (UserSetupError& e){ + logger.log(std::format("RngPlan: attempt {} can't run: {}", tracker.attempt_index() + 1, e.message()), COLOR_RED); + return TryOutcome{.outcome = RngAttemptOutcome::UNUSABLE, .detail = "setup_error", .pokemon = std::nullopt}; + } +} + } @@ -208,15 +237,12 @@ StarterRngLoopResult run_starter_rng_plan( } const size_t index = tracker.attempt_index(); const WallClock deadline = std::min(start + limits.attempt_time, total_deadline); - const StarterRngResult attempt = run_try(log, tracker, steps, limits, start, deadline); - // The deadline ends a try as out of resets. - const bool past_deadline = attempt.outcome == StarterRngOutcome::out_of_resets && steps.now() >= deadline; - const RngAttemptOutcome outcome = plan_outcome(attempt.outcome); + const TryOutcome attempt = run_try_outcome(logger, log, tracker, steps, limits, start, deadline); result.attempts_run++; - const RngPlanStep step = tracker.record(outcome); + const RngPlanStep step = tracker.record(attempt.outcome); logger.log(rng_log_result(RngResultLog{ - .index = index, .try_number = log.try_number(), .outcome = outcome, - .detail = past_deadline ? "attempt_deadline" : starter_rng_outcome_name(attempt.outcome), .pokemon = attempt.pokemon, + .index = index, .try_number = log.try_number(), .outcome = attempt.outcome, + .detail = attempt.detail, .pokemon = attempt.pokemon, .next = rng_plan_next(step, index, tracker.attempt_index()), })); } @@ -252,8 +278,9 @@ std::string starter_rng_loop_message(const StarterRngLoopResult& result){ "The save is still south of the table: raise the RNG plan's max attempts and start AutoStory at 00.04 again.", sids ); case StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT: - return "Starter RNG: every attempt left missed its target more often than the retries allow. " - "The save is still south of the table: check the RNG plan's sound setting and start AutoStory at 00.04 again."; + return "Starter RNG: every attempt left missed its target more often than the retries allow, or Starter RNG " + "refused its timings (see the log). The save is still south of the table: check the RNG plan's sound setting " + "and start AutoStory at 00.04 again."; case StarterRngLoopEnd::OUT_OF_TIME: return std::format( "Starter RNG: out of time after {} attempts. The save is still south of the table: start AutoStory at 00.04 again.", @@ -352,7 +379,16 @@ StarterRngResult ConsoleStarterRngSteps::run_attempt(const RngAttempt& attempt, m_notifications, stats ); - return attempts.run(m_env, m_context); + try{ + return attempts.run(m_env, m_context); + }catch (OperationFailedException& e){ + // Starter RNG refuses timings it can't press (check_timings()) this + // way; a failure in the game sends an error report. + if (e.error_report_mode() != ErrorReportMode::NO_ERROR_REPORT){ + throw; + } + throw UserSetupError(m_env.logger(), e.message()); + } } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h index 598ad9122c..696e061a6d 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h @@ -111,7 +111,8 @@ class StarterRngLoopSteps{ virtual ~StarterRngLoopSteps() = default; virtual WallClock now() = 0; // Runs Starter RNG's attempts at `attempt`'s target from the save under - // the ball, as `call` says. + // the ball, as `call` says. Throws UserSetupError when Starter RNG + // refuses the attempt's timings; the loop logs it and moves on. virtual StarterRngResult run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call) = 0; }; @@ -127,7 +128,7 @@ enum class StarterRngLoopEnd{ // Every attempt was hit and none was shiny. OUT_OF_ATTEMPTS, // The last attempt still shiny for a SID left missed more often than - // the retries allow. + // the retries allow, or couldn't run. MISSED_EVERY_ATTEMPT_LEFT, // The total time ran out with attempts left. OUT_OF_TIME, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp index ef6b693001..2c8d771b2e 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp @@ -58,10 +58,11 @@ class LineLogger : public Logger{ // Each try takes `minutes_per_attempt` on the clock, makes one reset at // its end with calibration 1.5/-2/0.25 frames, and comes out as the next -// of `outcomes`. +// of `outcomes`. An empty one is Starter RNG refusing the timings: a +// UserSetupError at once. class ScriptedSteps : public StarterRngLoopSteps{ public: - ScriptedSteps(std::vector outcomes, int minutes_per_attempt) + ScriptedSteps(std::vector> outcomes, int minutes_per_attempt) : m_outcomes(std::move(outcomes)) , m_minutes(minutes_per_attempt) {} @@ -75,9 +76,13 @@ class ScriptedSteps : public StarterRngLoopSteps{ } indices.push_back(call.index); deadlines_min.push_back(int(std::chrono::duration_cast(call.deadline - START).count())); + const std::optional outcome = m_outcomes[m_next++]; + if (!outcome){ + throw UserSetupError(m_logger, "Refused timings."); + } m_now += std::chrono::minutes(m_minutes); call.on_reset(StarterRngProgress{.resets = 1, .calibrations = {1.5, -2, 0.25}}); - return StarterRngResult{.outcome = m_outcomes[m_next++], .pokemon = std::nullopt}; + return StarterRngResult{.outcome = *outcome, .pokemon = std::nullopt}; } std::vector indices; @@ -86,8 +91,9 @@ class ScriptedSteps : public StarterRngLoopSteps{ private: static inline const WallClock START = WallClock{} + std::chrono::hours(1000); - std::vector m_outcomes; + std::vector> m_outcomes; int m_minutes; + LineLogger m_logger; WallClock m_now = START; size_t m_next = 0; }; @@ -145,7 +151,8 @@ std::string join(const std::vector& values){ struct LoopRow{ std::string name; - std::vector outcomes; + // Empty: Starter RNG refuses the attempt's timings. + std::vector> outcomes; int minutes_per_attempt; bool shiny_required; StarterRngLoopEnd end; @@ -158,6 +165,7 @@ struct LoopRow{ }; using enum StarterRngOutcome; +const std::optional REFUSED = std::nullopt; const std::vector LOOP_ROWS = { { @@ -244,6 +252,23 @@ const std::vector LOOP_ROWS = { "RngPlan: result attempt=2 try=2 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", }, }, + { + .name = "an attempt whose timings Starter RNG refuses is skipped", + .outcomes = {REFUSED, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,2", .sid = 300, + .lines = { + "RngPlan: attempt 1 can't run: Refused timings.", + "RngPlan: result attempt=1 try=1 outcome=unusable starter_rng=setup_error nature=- ivs=- pid=- next=next_attempt", + }, + }, + { + .name = "no attempt Starter RNG will run", + .outcomes = {REFUSED, REFUSED}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT, .attempts_run = "1,2", .sid = 0, + .lines = {"RngPlan: result attempt=2 try=1 outcome=unusable starter_rng=setup_error nature=- ivs=- pid=- next=stop"}, + }, { .name = "every attempt hit, none shiny", .outcomes = {target_hit, target_hit}, From cde5f574e8183560d607ce4e640ba4fc90bdd924 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 18:03:33 -0800 Subject: [PATCH 05/10] FRLG AutoStory: stop the RNG loop on a setup error other than refused timings The loop marked an attempt unusable and moved on for any UserSetupError, so "No sound detected." (no audio input on the panel) burned every attempt. Starter RNG's refused timings now come through as StarterRngTimingsRefused, the only error the loop skips an attempt for; any other error, a UserSetupError included, ends the program. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonFRLG_AutoStoryRngLoop.cpp | 9 ++-- .../AutoStory/PokemonFRLG_AutoStoryRngLoop.h | 18 ++++++- .../PokemonFRLG_AutoStoryRngLoop_Tests.cpp | 51 ++++++++++++++++++- 3 files changed, 70 insertions(+), 8 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp index 46209bd40e..d4f7feb3a6 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp @@ -191,8 +191,9 @@ StarterRngResult run_try( return steps.run_attempt(tracker.current_attempt(), call); } -// run_try(), with a setup error (Starter RNG refusing the attempt's -// timings) as an attempt that can't run. +// run_try(), with Starter RNG refusing the attempt's timings as an attempt +// that can't run. Other errors, a setup error such as no sound included, +// would fail every attempt the same way, so they end the loop. TryOutcome run_try_outcome( Logger& logger, LoopLog& log, const RngPlanTracker& tracker, StarterRngLoopSteps& steps, const StarterRngLoopLimits& limits, WallClock start, WallClock deadline @@ -206,7 +207,7 @@ TryOutcome run_try_outcome( .detail = past_deadline ? "attempt_deadline" : starter_rng_outcome_name(attempt.outcome), .pokemon = attempt.pokemon, }; - }catch (UserSetupError& e){ + }catch (StarterRngTimingsRefused& e){ logger.log(std::format("RngPlan: attempt {} can't run: {}", tracker.attempt_index() + 1, e.message()), COLOR_RED); return TryOutcome{.outcome = RngAttemptOutcome::UNUSABLE, .detail = "setup_error", .pokemon = std::nullopt}; } @@ -387,7 +388,7 @@ StarterRngResult ConsoleStarterRngSteps::run_attempt(const RngAttempt& attempt, if (e.error_report_mode() != ErrorReportMode::NO_ERROR_REPORT){ throw; } - throw UserSetupError(m_env.logger(), e.message()); + throw StarterRngTimingsRefused(e.message()); } } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h index 696e061a6d..30798d14bb 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h @@ -20,6 +20,7 @@ #include #include #include "Common/Cpp/Color.h" +#include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Logging/AbstractLogger.h" #include "Common/Cpp/Time.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" @@ -93,6 +94,19 @@ struct StarterRngLoopLimits{ size_t max_retries = 0; }; +// Starter RNG refused an attempt's timings (check_timings()). The loop +// records the attempt as unusable and moves on; any other error, a +// UserSetupError included, stops the loop. +class StarterRngTimingsRefused : public Exception{ +public: + explicit StarterRngTimingsRefused(std::string message) : m_message(std::move(message)) {} + virtual const char* name() const override{ return "StarterRngTimingsRefused"; } + virtual std::string message() const override{ return m_message; } + +private: + std::string m_message; +}; + // One try of an attempt, as the loop asks the steps for it. struct StarterRngAttemptCall{ // From 0. @@ -111,8 +125,8 @@ class StarterRngLoopSteps{ virtual ~StarterRngLoopSteps() = default; virtual WallClock now() = 0; // Runs Starter RNG's attempts at `attempt`'s target from the save under - // the ball, as `call` says. Throws UserSetupError when Starter RNG - // refuses the attempt's timings; the loop logs it and moves on. + // the ball, as `call` says. Throws StarterRngTimingsRefused when + // Starter RNG refuses the attempt's timings; the loop logs it and moves on. virtual StarterRngResult run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call) = 0; }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp index 2c8d771b2e..1284632091 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp @@ -59,7 +59,7 @@ class LineLogger : public Logger{ // Each try takes `minutes_per_attempt` on the clock, makes one reset at // its end with calibration 1.5/-2/0.25 frames, and comes out as the next // of `outcomes`. An empty one is Starter RNG refusing the timings: a -// UserSetupError at once. +// StarterRngTimingsRefused at once. class ScriptedSteps : public StarterRngLoopSteps{ public: ScriptedSteps(std::vector> outcomes, int minutes_per_attempt) @@ -78,7 +78,7 @@ class ScriptedSteps : public StarterRngLoopSteps{ deadlines_min.push_back(int(std::chrono::duration_cast(call.deadline - START).count())); const std::optional outcome = m_outcomes[m_next++]; if (!outcome){ - throw UserSetupError(m_logger, "Refused timings."); + throw StarterRngTimingsRefused("Refused timings."); } m_now += std::chrono::minutes(m_minutes); call.on_reset(StarterRngProgress{.resets = 1, .calibrations = {1.5, -2, 0.25}}); @@ -98,6 +98,24 @@ class ScriptedSteps : public StarterRngLoopSteps{ size_t m_next = 0; }; +// A setup problem Starter RNG hits on every attempt alike, such as no +// audio input. +class SetupErrorSteps : public StarterRngLoopSteps{ +public: + virtual WallClock now() override{ + return WallClock{} + std::chrono::hours(1000); + } + virtual StarterRngResult run_attempt(const RngAttempt&, const StarterRngAttemptCall&) override{ + calls++; + throw UserSetupError(m_logger, "No sound detected."); + } + + size_t calls = 0; + +private: + LineLogger m_logger; +}; + // SID Helper's candidates 100, 200, 300; attempt 1 is shiny for 100 and // 200, attempt 2 for 300. const std::vector CANDIDATES = {{100, 1}, {200, 2}, {300, 1}}; @@ -349,6 +367,34 @@ UnitTestResult test_deadlines(){ } +// A setup error other than refused timings stops the loop at once: it +// reaches the program, and the attempt is neither recorded nor skipped. +UnitTestResult test_setup_error_stops(){ + RngPlanTracker tracker(attempts(), CANDIDATES, true, 2); + SetupErrorSteps steps; + LineLogger logger; + const size_t sids = tracker.remaining_sids().size(); + bool thrown = false; + try{ + run_starter_rng_plan(logger, tracker, steps, LIMITS, 12345, CANDIDATES); + }catch (UserSetupError&){ + thrown = true; + } + const bool result_line = std::any_of(logger.lines.begin(), logger.lines.end(), [](const std::string& line){ + return line.starts_with("RngPlan: result") || line.starts_with("RngPlan: attempt"); + }); + const std::string expected = std::format("thrown 1, calls 1, attempt 1, sids {}, result line 0", sids); + const std::string got = std::format( + "thrown {}, calls {}, attempt {}, sids {}, result line {}", + int(thrown), steps.calls, tracker.attempt_index() + 1, tracker.remaining_sids().size(), int(result_line) + ); + if (got != expected){ + return "Expected " + expected + "; got " + got; + } + return true; +} + + // What the run says after a shiny, by what it tells of the SID. UnitTestResult test_shiny_messages(){ struct Case{ @@ -449,6 +495,7 @@ void add_tests_AutoStoryRngLoop(UnitTestDatabase& database){ database.add(row.name, [row]{ return run_loop_row(row); }); } database.add("attempt deadlines", test_deadlines); + database.add("a setup error stops the loop", test_setup_error_stops); database.add("state line", test_state_line); database.add("shiny messages", test_shiny_messages); database.add("rows after a shiny", test_rows_after_shiny); From 9f014021d8fa17d3956cec7367d28e014fa4135c Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 18:13:08 -0800 Subject: [PATCH 06/10] FRLG: move the Starter RNG loop into RngManipulation The loop doesn't know about the story, so it moves out of AutoStory: StarterRngLoop (the steps interface, limits, run_starter_rng_plan and its state line, with its tests) and StarterRngConsoleSteps (the console steps and RngPlanLogger). AutoStoryRngLoop keeps the story glue: StarterRngPlanned, the loop's end message, which names AutoStory's checkpoints, and rows_after_starter_rng. Code is moved unchanged; the message keeps its own copy of the short SID-list helper. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonFRLG/PokemonFRLG_Tests.cpp | 2 + .../AutoStory/PokemonFRLG_AutoStory.cpp | 3 + .../PokemonFRLG_AutoStoryRngLoop.cpp | 305 ------------- .../AutoStory/PokemonFRLG_AutoStoryRngLoop.h | 191 +------- .../PokemonFRLG_AutoStoryRngLoop_Tests.cpp | 378 +-------------- .../PokemonFRLG_StarterRngConsoleSteps.cpp | 95 ++++ .../PokemonFRLG_StarterRngConsoleSteps.h | 80 ++++ .../PokemonFRLG_StarterRngLoop.cpp | 261 +++++++++++ .../PokemonFRLG_StarterRngLoop.h | 161 +++++++ .../PokemonFRLG_StarterRngLoop_Tests.cpp | 432 ++++++++++++++++++ .../PokemonFRLG_StarterRngLoop_Tests.h | 23 + SerialPrograms/cmake/SourceFiles.cmake | 6 + 12 files changed, 1069 insertions(+), 868 deletions(-) create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp create mode 100644 SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp index dfbcb7f0b8..03b37dfeed 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp @@ -48,6 +48,7 @@ #include "Programs/RngManipulation/PokemonFRLG_RngPlan_Tests.h" #include "Programs/RngManipulation/PokemonFRLG_RngSteps_Tests.h" #include "Programs/RngManipulation/PokemonFRLG_RngTargetSearch_Tests.h" +#include "Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h" #include "Tests/TestUtils.h" #include "PokemonFRLG_Tests.h" @@ -719,6 +720,7 @@ void add_tests(UnitTestDatabase& database){ add_tests_RngPlanTracker(database); add_tests_RngPlanLog(database); add_tests_RngSteps(database); + add_tests_StarterRngLoop(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index 3786de6ba3..36856fdd14 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -19,7 +19,10 @@ #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" #include "VideoGames/PokemonFRLG/Programs/PokemonFRLG_TrainerCard.h" #include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h" #include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SidSteps.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h" #include "PokemonFRLG_AutoStoryEvents.h" #include "PokemonFRLG_AutoStoryRngLoop.h" #include "PokemonFRLG_AutoStoryTable.h" diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp index ef61f6b3d4..740caf3def 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp @@ -7,9 +7,6 @@ #include #include #include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h" #include "PokemonFRLG_AutoStoryRngLoop.h" namespace PokemonAutomation{ @@ -17,44 +14,6 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ -RngAttemptOutcome plan_outcome(StarterRngOutcome outcome){ - switch (outcome){ - case StarterRngOutcome::shiny_on_target: - return RngAttemptOutcome::SHINY; - case StarterRngOutcome::shiny: - case StarterRngOutcome::shiny_off_target: - return RngAttemptOutcome::SHINY_OFF_TARGET; - case StarterRngOutcome::target_hit: - return RngAttemptOutcome::HIT_NOT_SHINY; - case StarterRngOutcome::wild_shiny: - case StarterRngOutcome::out_of_resets: - case StarterRngOutcome::no_matches: - return RngAttemptOutcome::MISSED; - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Starter RNG outcome."); -} - -std::string starter_rng_outcome_name(StarterRngOutcome outcome){ - switch (outcome){ - case StarterRngOutcome::shiny: - return "shiny"; - case StarterRngOutcome::shiny_on_target: - return "shiny_on_target"; - case StarterRngOutcome::shiny_off_target: - return "shiny_off_target"; - case StarterRngOutcome::target_hit: - return "target_hit"; - case StarterRngOutcome::wild_shiny: - return "wild_shiny"; - case StarterRngOutcome::out_of_resets: - return "out_of_resets"; - case StarterRngOutcome::no_matches: - return "no_matches"; - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Starter RNG outcome."); -} - - namespace{ // "-" for none. @@ -66,194 +25,6 @@ std::string join_sids(const std::vector& sids){ return text.empty() ? "-" : text; } -std::string clock_text(Milliseconds time){ - const int64_t seconds = std::chrono::duration_cast(time).count(); - return std::format("{:02}:{:02}:{:02}", seconds / 3600, seconds / 60 % 60, seconds % 60); -} - -std::string calibration_text(const std::optional& calibration){ - if (!calibration){ - return "-"; - } - return std::format("{:.2f}/{:.2f}/{:.2f}", calibration->seed_offset, calibration->csf_offset, calibration->ingame_offset); -} - -} - -std::string rng_log_state(const RngLoopState& state){ - return std::format( - "RngPlan: state attempt={}/{} try={}/{} reset={}/{} seed={:04X} advances={} sids={} ruled_out={} " - "attempt_time={}/{} total_time={}/{} calibration={}", - state.attempt, state.attempts, state.try_number, state.tries, state.resets, state.max_resets, - state.seed, state.advances, join_sids(state.sids), join_sids(state.ruled_out), - clock_text(state.attempt_time), clock_text(state.attempt_cap), - clock_text(state.total_time), clock_text(state.total_cap), - calibration_text(state.calibration) - ); -} - - -namespace{ - -std::optional loop_end(RngPlanStep step){ - switch (step){ - case RngPlanStep::RUN_ATTEMPT: - return std::nullopt; - case RngPlanStep::GOT_SHINY: - return StarterRngLoopEnd::SHINY; - case RngPlanStep::GOT_SHINY_OFF_TARGET: - return StarterRngLoopEnd::SHINY_OFF_TARGET; - case RngPlanStep::GOT_TARGET: - return StarterRngLoopEnd::TARGET; - case RngPlanStep::OUT_OF_ATTEMPTS: - return StarterRngLoopEnd::OUT_OF_ATTEMPTS; - case RngPlanStep::MISSED_EVERY_ATTEMPT_LEFT: - return StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT; - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RNG plan step."); -} - -// The loop's state lines and tries, across the attempts. -class LoopLog{ -public: - LoopLog(Logger& logger, const RngPlanTracker& tracker, const StarterRngLoopLimits& limits, WallClock start) - : m_logger(logger) - , m_tracker(tracker) - , m_limits(limits) - , m_start(start) - , m_start_sids(tracker.remaining_sids()) - {} - - // A new try of the tracker's current attempt, starting at `now`. - void begin_try(WallClock now){ - const size_t index = m_tracker.attempt_index(); - m_try = (m_tries_of && *m_tries_of == index) ? m_try + 1 : 1; - m_tries_of = index; - m_try_start = now; - } - size_t try_number() const{ - return m_try; - } - - void log_state(WallClock now, uint64_t resets, const std::optional& calibration){ - const RngAttempt& attempt = m_tracker.current_attempt(); - std::vector ruled_out; - for (uint16_t sid : m_start_sids){ - const std::vector& left = m_tracker.remaining_sids(); - if (std::find(left.begin(), left.end(), sid) == left.end()){ - ruled_out.push_back(sid); - } - } - m_logger.log(rng_log_state(RngLoopState{ - .attempt = m_tracker.attempt_index() + 1, .attempts = m_tracker.attempt_count(), - .try_number = m_try, .tries = m_limits.max_retries + 1, - .resets = resets, .max_resets = m_limits.max_resets, - .seed = attempt.target.seed.seed, .advances = attempt.target.advances, - .sids = attempt.sids, .ruled_out = std::move(ruled_out), - .attempt_time = std::chrono::duration_cast(now - m_try_start), .attempt_cap = m_limits.attempt_time, - .total_time = std::chrono::duration_cast(now - m_start), .total_cap = m_limits.total_time, - .calibration = calibration, - })); - } - -private: - Logger& m_logger; - const RngPlanTracker& m_tracker; - const StarterRngLoopLimits& m_limits; - const WallClock m_start; - const std::vector m_start_sids; - std::optional m_tries_of; - size_t m_try = 0; - WallClock m_try_start; -}; - -// What one try came to, for the tracker and the result line. -struct TryOutcome{ - RngAttemptOutcome outcome = RngAttemptOutcome::MISSED; - std::string detail; - std::optional pokemon; -}; - -// Runs one try of the tracker's current attempt, logging its state lines. -StarterRngResult run_try( - LoopLog& log, const RngPlanTracker& tracker, StarterRngLoopSteps& steps, - const StarterRngLoopLimits& limits, WallClock start, WallClock deadline -){ - log.begin_try(start); - log.log_state(start, 0, std::nullopt); - StarterRngAttemptCall call{ - .index = tracker.attempt_index(), - .deadline = deadline, - .max_resets = limits.max_resets, - .on_reset = [&](const StarterRngProgress& progress){ - log.log_state(steps.now(), progress.resets, progress.calibrations); - }, - }; - return steps.run_attempt(tracker.current_attempt(), call); -} - -// run_try(), with Starter RNG refusing the attempt's timings as an attempt -// that can't run. Other errors, a setup error such as no sound included, -// would fail every attempt the same way, so they end the loop. -TryOutcome run_try_outcome( - Logger& logger, LoopLog& log, const RngPlanTracker& tracker, StarterRngLoopSteps& steps, - const StarterRngLoopLimits& limits, WallClock start, WallClock deadline -){ - try{ - const StarterRngResult attempt = run_try(log, tracker, steps, limits, start, deadline); - // The deadline ends a try as out of resets. - const bool past_deadline = attempt.outcome == StarterRngOutcome::out_of_resets && steps.now() >= deadline; - return TryOutcome{ - .outcome = plan_outcome(attempt.outcome), - .detail = past_deadline ? "attempt_deadline" : starter_rng_outcome_name(attempt.outcome), - .pokemon = attempt.pokemon, - }; - }catch (StarterRngTimingsRefused& e){ - logger.log(std::format("RngPlan: attempt {} can't run: {}", tracker.attempt_index() + 1, e.message()), COLOR_RED); - return TryOutcome{.outcome = RngAttemptOutcome::UNUSABLE, .detail = "setup_error", .pokemon = std::nullopt}; - } -} - -} - - -StarterRngLoopResult run_starter_rng_plan( - Logger& logger, RngPlanTracker& tracker, StarterRngLoopSteps& steps, - const StarterRngLoopLimits& limits, uint16_t tid, const std::vector& sid_helper_candidates -){ - StarterRngLoopResult result; - const WallClock loop_start = steps.now(); - const WallClock total_deadline = loop_start + limits.total_time; - LoopLog log(logger, tracker, limits, loop_start); - while (true){ - std::optional end = loop_end(tracker.step()); - if (end){ - result.end = *end; - break; - } - const WallClock start = steps.now(); - if (start >= total_deadline){ - logger.log("RngPlan: out of time before attempt " + std::to_string(tracker.attempt_index() + 1)); - result.end = StarterRngLoopEnd::OUT_OF_TIME; - break; - } - const size_t index = tracker.attempt_index(); - const WallClock deadline = std::min(start + limits.attempt_time, total_deadline); - const TryOutcome attempt = run_try_outcome(logger, log, tracker, steps, limits, start, deadline); - result.attempts_run++; - const RngPlanStep step = tracker.record(attempt.outcome); - logger.log(rng_log_result(RngResultLog{ - .index = index, .try_number = log.try_number(), .outcome = attempt.outcome, - .detail = attempt.detail, .pokemon = attempt.pokemon, - .next = rng_plan_next(step, index, tracker.attempt_index()), - })); - } - result.remaining_sids = tracker.remaining_sids(); - result.sid = tracker.confirmed_sid(); - if (result.end == StarterRngLoopEnd::SHINY && result.sid){ - logger.log(rng_log_confirmed(tid, *result.sid, sid_helper_candidates)); - } - return result; } std::string starter_rng_loop_message(const StarterRngLoopResult& result){ @@ -318,82 +89,6 @@ std::vector rows_after_starter_rng( } -RngPlanLogger::RngPlanLogger(ConsoleHandle& console) - : m_console(console) -{} - -void RngPlanLogger::log(const std::string& msg, Color color){ - m_console.log(msg, color); - if (msg.starts_with("RngPlan: state") || msg.starts_with("RngPlan: result")){ - m_console.overlay().add_log(msg); - } -} - - -ConsoleStarterRngSteps::ConsoleStarterRngSteps( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const StarterRngConsoleSettings& settings, const StarterRngNotifications& notifications -) - : m_env(env) - , m_context(context) - , m_settings(settings) - , m_notifications(notifications) - // TODO: LeafGreen, once AutoStory plays it. - , m_seeds(seeds_json_path(true, settings.language)) -{} - -WallClock ConsoleStarterRngSteps::now(){ - return current_time(); -} - -StarterRngResult ConsoleStarterRngSteps::run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call){ - // Starter RNG's default Nearby Seed Radius. - const int SEED_RADIUS = 5; - const SeedMatch seed_match = m_seeds.find_seed(attempt.target.seed.seed, m_settings.sound, SEED_RADIUS); - if (!seed_match.found){ - throw InternalProgramError(&m_env.logger(), PA_CURRENT_FUNCTION, "The plan's seed isn't in the seed list it came from."); - } - - StarterRngStats stats; - StarterRngAttempts attempts( - StarterRngTarget{ - .starter = StarterSpecies::squirtle, - .seed = attempt.target.seed.seed, - .advances = attempt.target.advances, - .seed_match = seed_match, - }, - StarterRngSettings{ - .language = m_settings.language, - .profile = 0, - .ignore_wild_shinies = true, - .take_video = false, - .identify_shiny = true, - .max_resets = [deadline = call.deadline, max_resets = call.max_resets]{ - return current_time() >= deadline ? uint64_t(0) : max_resets; - }, - .on_reset = call.on_reset, - }, - StarterRngDisplays{ - .target = m_target_display, - .filters = m_filter_display, - .calibration = m_calibration_display, - }, - m_notifications, - stats - ); - try{ - return attempts.run(m_env, m_context); - }catch (OperationFailedException& e){ - // Starter RNG refuses timings it can't press (check_timings()) this - // way; a failure in the game sends an error report. - if (e.error_report_mode() != ErrorReportMode::NO_ERROR_REPORT){ - throw; - } - throw StarterRngTimingsRefused(e.message()); - } -} - - } } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h index c25f16f718..266204c6c4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h @@ -2,12 +2,10 @@ * * From: https://github.com/PokemonAutomation/ * - * AutoStory's Starter RNG stop, run in the program: the RNG plan's - * attempts (RngManipulation/PokemonFRLG_RngPlan.h), each run with Starter RNG's - * attempt loop (StarterRngAttempts) from the save under Squirtle's ball, - * until one comes out shiny or the plan, its retries or the time run out. - * Its "RngPlan: state" and "RngPlan: result" lines are listed with the - * plan's in RngManipulation/PokemonFRLG_RngPlanLog.h. + * AutoStory's Starter RNG stop, run in the program with the Starter RNG + * loop (RngManipulation/PokemonFRLG_StarterRngLoop.h) from the save under + * Squirtle's ball: the plan it runs, what the run says when the loop + * ends, and the rows it takes after a shiny. * */ @@ -15,26 +13,11 @@ #define PokemonAutomation_PokemonFRLG_AutoStoryRngLoop_H #include -#include -#include #include #include -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Logging/AbstractLogger.h" -#include "Common/Cpp/Time.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" -#include "CommonFramework/Language.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngCalibration.h" -#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngDisplays.h" #include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h" -#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h" -#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h" -#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h" #include "PokemonFRLG_AutoStoryEvents.h" namespace PokemonAutomation{ @@ -48,127 +31,6 @@ struct StarterRngPlanned{ std::vector attempts; }; -// Starter RNG's outcome as the RNG plan counts it. Only a shiny on the -// target is SHINY; one off it, or not known to be on it, is -// SHINY_OFF_TARGET. Out of resets, no matches and a wild shiny are misses, -// which the plan runs again. -RngAttemptOutcome plan_outcome(StarterRngOutcome outcome); -// As the result line names it: "shiny_on_target", "target_hit", -// "out_of_resets"... (The loop says "attempt_deadline" instead of -// "out_of_resets" once the try's deadline has passed.) -std::string starter_rng_outcome_name(StarterRngOutcome outcome); - - -// Where the loop is, for an "RngPlan: state" line. -struct RngLoopState{ - // From 1, of `attempts`. - size_t attempt = 1; - size_t attempts = 0; - // From 1, of `tries`. - size_t try_number = 1; - size_t tries = 0; - uint64_t resets = 0; - uint64_t max_resets = 0; - uint16_t seed = 0; - uint64_t advances = 0; - // The SIDs the attempt is shiny for, and those ruled out so far. - std::vector sids; - std::vector ruled_out; - Milliseconds attempt_time = Milliseconds(0); - Milliseconds attempt_cap = Milliseconds(0); - Milliseconds total_time = Milliseconds(0); - Milliseconds total_cap = Milliseconds(0); - // The calibration of the last reset, in frames; none before the first. - std::optional calibration; -}; -std::string rng_log_state(const RngLoopState& state); - - -struct StarterRngLoopLimits{ - // An attempt makes no more resets after this long, and counts as missed. - Milliseconds attempt_time = Milliseconds(0); - // No attempt starts after this long. - Milliseconds total_time = Milliseconds(0); - // Resets per try of an attempt. - uint64_t max_resets = 0; - // The tracker's retries of a missed attempt, for the state lines. - size_t max_retries = 0; -}; - -// Starter RNG refused an attempt's timings (check_timings()). The loop -// records the attempt as unusable and moves on; any other error, a -// UserSetupError included, stops the loop. -class StarterRngTimingsRefused : public Exception{ -public: - explicit StarterRngTimingsRefused(std::string message) : m_message(std::move(message)) {} - virtual const char* name() const override{ return "StarterRngTimingsRefused"; } - virtual std::string message() const override{ return m_message; } - -private: - std::string m_message; -}; - -// One try of an attempt, as the loop asks the steps for it. -struct StarterRngAttemptCall{ - // From 0. - size_t index = 0; - // No reset after this. - WallClock deadline; - uint64_t max_resets = 0; - // To call after each reset. - std::function on_reset; -}; - -// The game steps of the loop, injected so that its decisions run in tests -// without a Switch. -class StarterRngLoopSteps{ -public: - virtual ~StarterRngLoopSteps() = default; - virtual WallClock now() = 0; - // Runs Starter RNG's attempts at `attempt`'s target from the save under - // the ball, as `call` says. Throws StarterRngTimingsRefused when - // Starter RNG refuses the attempt's timings; the loop logs it and moves on. - virtual StarterRngResult run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call) = 0; -}; - -enum class StarterRngLoopEnd{ - // The starter is shiny and the target; the game is on its summary, not saved. - SHINY, - // The starter is shiny but not the target (or not known to be), so it - // doesn't tell the SID; the game is on its summary, not saved. - SHINY_OFF_TARGET, - // Shiny not required, and the target was hit. The game is where - // Starter RNG's calibration left it, not saved. - TARGET, - // Every attempt was hit and none was shiny. - OUT_OF_ATTEMPTS, - // The last attempt still shiny for a SID left missed more often than - // the retries allow, or couldn't run. - MISSED_EVERY_ATTEMPT_LEFT, - // The total time ran out with attempts left. - OUT_OF_TIME, -}; - -struct StarterRngLoopResult{ - StarterRngLoopEnd end = StarterRngLoopEnd::OUT_OF_TIME; - // Attempts run, retries included. - size_t attempts_run = 0; - // The SID candidates not ruled out. - std::vector remaining_sids; - // The SID, once a shiny leaves one candidate. - std::optional sid; -}; - -// Runs `tracker`'s attempts through `steps` until the plan ends or -// `limits.total_time` has passed. Logs an "RngPlan: state" line at the -// start of each try and after each reset, an "RngPlan: result" line after -// it and, when a shiny leaves one SID, an "RngPlan: confirmed" line placing -// it among SID Helper's candidates for `tid`. -StarterRngLoopResult run_starter_rng_plan( - Logger& logger, RngPlanTracker& tracker, StarterRngLoopSteps& steps, - const StarterRngLoopLimits& limits, uint16_t tid, const std::vector& sid_helper_candidates -); - // What the run says when the loop ends with `result`. std::string starter_rng_loop_message(const StarterRngLoopResult& result); @@ -183,49 +45,6 @@ std::vector rows_after_starter_rng( ); -// The console's log, with the loop's state and result lines also on the -// stream's overlay log. -class RngPlanLogger : public Logger{ -public: - explicit RngPlanLogger(ConsoleHandle& console); - virtual void log(const std::string& msg, Color color = Color()) override; - -private: - ConsoleHandle& m_console; -}; - - -struct StarterRngConsoleSettings{ - Language language = Language::English; - SoundSetting sound = SoundSetting::Mono; -}; - -// The loop's steps on the console, with Starter RNG's displays, stats and -// calibration kept here (AutoStory doesn't show them). Each try starts -// from the calibration the last one ended with. Squirtle, FireRed, the -// Switch's default profile. -class ConsoleStarterRngSteps : public StarterRngLoopSteps{ -public: - ConsoleStarterRngSteps( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const StarterRngConsoleSettings& settings, const StarterRngNotifications& notifications - ); - - virtual WallClock now() override; - virtual StarterRngResult run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call) override; - -private: - SingleSwitchProgramEnvironment& m_env; - ProControllerContext& m_context; - StarterRngConsoleSettings m_settings; - StarterRngNotifications m_notifications; - SeedsDatabase m_seeds; - RngTargetDisplay m_target_display; - RngFilterDisplay m_filter_display; - RngCalibrationDisplay m_calibration_display; -}; - - void add_tests_AutoStoryRngLoop(UnitTestDatabase& database); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp index 1284632091..4e9a1a4846 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp @@ -2,8 +2,7 @@ * * From: https://github.com/PokemonAutomation/ * - * The Starter RNG loop's decisions and log lines on scripted attempt - * outcomes and a fake clock, and the rows a run takes after a shiny. + * What the run says after a shiny, and the rows it takes then. * */ @@ -44,356 +43,6 @@ class Test_AutoStoryRngLoop : public UnitTest{ }; -class LineLogger : public Logger{ -public: - virtual void log(const std::string& msg, Color) override{ - lines.push_back(msg); - } - bool has(const std::string& line) const{ - return std::find(lines.begin(), lines.end(), line) != lines.end(); - } - - std::vector lines; -}; - -// Each try takes `minutes_per_attempt` on the clock, makes one reset at -// its end with calibration 1.5/-2/0.25 frames, and comes out as the next -// of `outcomes`. An empty one is Starter RNG refusing the timings: a -// StarterRngTimingsRefused at once. -class ScriptedSteps : public StarterRngLoopSteps{ -public: - ScriptedSteps(std::vector> outcomes, int minutes_per_attempt) - : m_outcomes(std::move(outcomes)) - , m_minutes(minutes_per_attempt) - {} - - virtual WallClock now() override{ - return m_now; - } - virtual StarterRngResult run_attempt(const RngAttempt&, const StarterRngAttemptCall& call) override{ - if (m_next >= m_outcomes.size()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "More attempts than scripted."); - } - indices.push_back(call.index); - deadlines_min.push_back(int(std::chrono::duration_cast(call.deadline - START).count())); - const std::optional outcome = m_outcomes[m_next++]; - if (!outcome){ - throw StarterRngTimingsRefused("Refused timings."); - } - m_now += std::chrono::minutes(m_minutes); - call.on_reset(StarterRngProgress{.resets = 1, .calibrations = {1.5, -2, 0.25}}); - return StarterRngResult{.outcome = *outcome, .pokemon = std::nullopt}; - } - - std::vector indices; - // Each attempt's deadline, in minutes from the start. - std::vector deadlines_min; - -private: - static inline const WallClock START = WallClock{} + std::chrono::hours(1000); - std::vector> m_outcomes; - int m_minutes; - LineLogger m_logger; - WallClock m_now = START; - size_t m_next = 0; -}; - -// A setup problem Starter RNG hits on every attempt alike, such as no -// audio input. -class SetupErrorSteps : public StarterRngLoopSteps{ -public: - virtual WallClock now() override{ - return WallClock{} + std::chrono::hours(1000); - } - virtual StarterRngResult run_attempt(const RngAttempt&, const StarterRngAttemptCall&) override{ - calls++; - throw UserSetupError(m_logger, "No sound detected."); - } - - size_t calls = 0; - -private: - LineLogger m_logger; -}; - -// SID Helper's candidates 100, 200, 300; attempt 1 is shiny for 100 and -// 200, attempt 2 for 300. -const std::vector CANDIDATES = {{100, 1}, {200, 2}, {300, 1}}; - -std::vector attempts(){ - RngAttempt first{}; - first.target.seed.seed = 0xceff; - first.target.advances = 983; - first.sids = {100, 200}; - RngAttempt second{}; - second.target.seed.seed = 0x2ef6; - second.target.advances = 29364; - second.sids = {300}; - return {first, second}; -} - -// 60-minute tries, 12 hours in all, 50 resets a try, 2 retries. -const StarterRngLoopLimits LIMITS{ - .attempt_time = std::chrono::minutes(60), - .total_time = std::chrono::hours(12), - .max_resets = 50, - .max_retries = 2, -}; - -std::string end_name(StarterRngLoopEnd end){ - switch (end){ - case StarterRngLoopEnd::SHINY: - return "SHINY"; - case StarterRngLoopEnd::SHINY_OFF_TARGET: - return "SHINY_OFF_TARGET"; - case StarterRngLoopEnd::TARGET: - return "TARGET"; - case StarterRngLoopEnd::OUT_OF_ATTEMPTS: - return "OUT_OF_ATTEMPTS"; - case StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT: - return "MISSED_EVERY_ATTEMPT_LEFT"; - case StarterRngLoopEnd::OUT_OF_TIME: - return "OUT_OF_TIME"; - } - return "?"; -} - -std::string join(const std::vector& values){ - std::string text; - for (size_t value : values){ - text += (text.empty() ? "" : ",") + std::to_string(value + 1); - } - return text; -} - - -struct LoopRow{ - std::string name; - // Empty: Starter RNG refuses the attempt's timings. - std::vector> outcomes; - int minutes_per_attempt; - bool shiny_required; - StarterRngLoopEnd end; - // The attempts run, from 1, as "1,1,2". - std::string attempts_run; - // The SID confirmed, or 0 for none; with it, an "RngPlan: confirmed" line. - uint16_t sid; - // Log lines the loop must write. - std::vector lines; -}; - -using enum StarterRngOutcome; -const std::optional REFUSED = std::nullopt; - -const std::vector LOOP_ROWS = { - { - .name = "hit, then shiny confirms the SID", - .outcomes = {target_hit, shiny_on_target}, - .minutes_per_attempt = 30, .shiny_required = true, - .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,2", .sid = 300, - .lines = { - "RngPlan: state attempt=1/2 try=1/3 reset=0/50 seed=CEFF advances=983 sids=100,200 ruled_out=- " - "attempt_time=00:00:00/01:00:00 total_time=00:00:00/12:00:00 calibration=-", - "RngPlan: state attempt=1/2 try=1/3 reset=1/50 seed=CEFF advances=983 sids=100,200 ruled_out=- " - "attempt_time=00:30:00/01:00:00 total_time=00:30:00/12:00:00 calibration=1.50/-2.00/0.25", - "RngPlan: result attempt=1 try=1 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=next_attempt", - "RngPlan: state attempt=2/2 try=1/3 reset=0/50 seed=2EF6 advances=29364 sids=300 ruled_out=100,200 " - "attempt_time=00:00:00/01:00:00 total_time=00:30:00/12:00:00 calibration=-", - "RngPlan: result attempt=2 try=1 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", - "RngPlan: confirmed tid=12345 sid=300 candidate=3 of=3", - }, - }, - { - .name = "shiny on the target for two SIDs confirms none", - .outcomes = {shiny_on_target}, - .minutes_per_attempt = 30, .shiny_required = true, - .end = StarterRngLoopEnd::SHINY, .attempts_run = "1", .sid = 0, - .lines = {"RngPlan: result attempt=1 try=1 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm"}, - }, - { - .name = "shiny off the target confirms nothing", - .outcomes = {target_hit, shiny_off_target}, - .minutes_per_attempt = 30, .shiny_required = true, - .end = StarterRngLoopEnd::SHINY_OFF_TARGET, .attempts_run = "1,2", .sid = 0, - .lines = {"RngPlan: result attempt=2 try=1 outcome=shiny_off_target starter_rng=shiny_off_target nature=- ivs=- pid=- next=stop"}, - }, - { - .name = "a shiny not known to be the target confirms nothing", - .outcomes = {shiny}, - .minutes_per_attempt = 30, .shiny_required = true, - .end = StarterRngLoopEnd::SHINY_OFF_TARGET, .attempts_run = "1", .sid = 0, - .lines = {"RngPlan: result attempt=1 try=1 outcome=shiny_off_target starter_rng=shiny nature=- ivs=- pid=- next=stop"}, - }, - { - .name = "misses retry the same attempt", - .outcomes = {out_of_resets, no_matches, shiny_on_target}, - .minutes_per_attempt = 30, .shiny_required = true, - .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,1", .sid = 0, - .lines = { - "RngPlan: result attempt=1 try=1 outcome=missed starter_rng=out_of_resets nature=- ivs=- pid=- next=retry", - "RngPlan: result attempt=1 try=2 outcome=missed starter_rng=no_matches nature=- ivs=- pid=- next=retry", - "RngPlan: result attempt=1 try=3 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", - }, - }, - { - .name = "an attempt past its deadline", - .outcomes = {out_of_resets, shiny_on_target}, - .minutes_per_attempt = 90, .shiny_required = true, - .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1", .sid = 0, - .lines = {"RngPlan: result attempt=1 try=1 outcome=missed starter_rng=attempt_deadline nature=- ivs=- pid=- next=retry"}, - }, - { - .name = "retries used up, then the next attempt", - .outcomes = {out_of_resets, no_matches, wild_shiny, shiny_on_target}, - .minutes_per_attempt = 30, .shiny_required = true, - .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,1,2", .sid = 300, - .lines = { - "RngPlan: result attempt=1 try=3 outcome=missed starter_rng=wild_shiny nature=- ivs=- pid=- next=next_attempt", - "RngPlan: result attempt=2 try=1 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", - "RngPlan: confirmed tid=12345 sid=300 candidate=3 of=3", - }, - }, - { - .name = "every attempt left missed too often", - .outcomes = {out_of_resets, out_of_resets, out_of_resets, no_matches, no_matches, no_matches}, - .minutes_per_attempt = 30, .shiny_required = true, - .end = StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT, .attempts_run = "1,1,1,2,2,2", .sid = 0, - .lines = {"RngPlan: result attempt=2 try=3 outcome=missed starter_rng=no_matches nature=- ivs=- pid=- next=stop"}, - }, - { - .name = "miss, hit, miss, then shiny", - .outcomes = {out_of_resets, target_hit, no_matches, shiny_on_target}, - .minutes_per_attempt = 30, .shiny_required = true, - .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,2,2", .sid = 300, - .lines = { - "RngPlan: result attempt=1 try=2 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=next_attempt", - "RngPlan: result attempt=2 try=2 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", - }, - }, - { - .name = "an attempt whose timings Starter RNG refuses is skipped", - .outcomes = {REFUSED, shiny_on_target}, - .minutes_per_attempt = 30, .shiny_required = true, - .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,2", .sid = 300, - .lines = { - "RngPlan: attempt 1 can't run: Refused timings.", - "RngPlan: result attempt=1 try=1 outcome=unusable starter_rng=setup_error nature=- ivs=- pid=- next=next_attempt", - }, - }, - { - .name = "no attempt Starter RNG will run", - .outcomes = {REFUSED, REFUSED}, - .minutes_per_attempt = 30, .shiny_required = true, - .end = StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT, .attempts_run = "1,2", .sid = 0, - .lines = {"RngPlan: result attempt=2 try=1 outcome=unusable starter_rng=setup_error nature=- ivs=- pid=- next=stop"}, - }, - { - .name = "every attempt hit, none shiny", - .outcomes = {target_hit, target_hit}, - .minutes_per_attempt = 30, .shiny_required = true, - .end = StarterRngLoopEnd::OUT_OF_ATTEMPTS, .attempts_run = "1,2", .sid = 0, - .lines = {"RngPlan: result attempt=2 try=1 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=stop"}, - }, - { - .name = "a hit ends the plan with shiny not required", - .outcomes = {target_hit}, - .minutes_per_attempt = 30, .shiny_required = false, - .end = StarterRngLoopEnd::TARGET, .attempts_run = "1", .sid = 0, - .lines = {}, - }, - { - .name = "no attempt starts after the total time", - .outcomes = {out_of_resets, out_of_resets}, - .minutes_per_attempt = 400, .shiny_required = true, - .end = StarterRngLoopEnd::OUT_OF_TIME, .attempts_run = "1,1", .sid = 0, - .lines = { - "RngPlan: state attempt=1/2 try=2/3 reset=1/50 seed=CEFF advances=983 sids=100,200 ruled_out=- " - "attempt_time=06:40:00/01:00:00 total_time=13:20:00/12:00:00 calibration=1.50/-2.00/0.25", - "RngPlan: out of time before attempt 1", - }, - }, -}; - -UnitTestResult run_loop_row(const LoopRow& row){ - RngPlanTracker tracker(attempts(), CANDIDATES, row.shiny_required, 2); - ScriptedSteps steps(row.outcomes, row.minutes_per_attempt); - LineLogger logger; - StarterRngLoopResult result = run_starter_rng_plan(logger, tracker, steps, LIMITS, 12345, CANDIDATES); - - const std::string expected = std::format("end {}, attempts {}, sid {}", end_name(row.end), row.attempts_run, row.sid); - const std::string got = std::format( - "end {}, attempts {}, sid {}", end_name(result.end), join(steps.indices), result.sid.value_or(0) - ); - if (expected != got){ - return "Expected " + expected + "; got " + got; - } - for (const std::string& line : row.lines){ - if (!logger.has(line)){ - return "Expected the log line \"" + line + "\""; - } - } - const bool confirmed = std::any_of(logger.lines.begin(), logger.lines.end(), [](const std::string& line){ - return line.starts_with("RngPlan: confirmed"); - }); - if (confirmed != (row.sid != 0)){ - return std::format("Expected {} \"RngPlan: confirmed\" line", row.sid != 0 ? "a" : "no"); - } - if (result.attempts_run != steps.indices.size()){ - return std::format("Expected attempts_run {}; got {}", steps.indices.size(), result.attempts_run); - } - return true; -} - - -// An attempt's deadline is an hour after it starts, or the end of the -// total time if sooner: attempts of 400 minutes start at 0 and 400, and -// none at 800, past the total of 430. -UnitTestResult test_deadlines(){ - RngPlanTracker tracker(attempts(), CANDIDATES, true, 5); - ScriptedSteps steps({StarterRngOutcome::out_of_resets, StarterRngOutcome::out_of_resets}, 400); - LineLogger logger; - const StarterRngLoopLimits limits{ - .attempt_time = std::chrono::minutes(60), .total_time = std::chrono::minutes(430), .max_resets = 50, .max_retries = 5, - }; - run_starter_rng_plan(logger, tracker, steps, limits, 12345, CANDIDATES); - std::string got; - for (int deadline : steps.deadlines_min){ - got += (got.empty() ? "" : ",") + std::to_string(deadline); - } - if (got != "60,430"){ - return "Expected deadlines 60,430 minutes; got " + got; - } - return true; -} - - -// A setup error other than refused timings stops the loop at once: it -// reaches the program, and the attempt is neither recorded nor skipped. -UnitTestResult test_setup_error_stops(){ - RngPlanTracker tracker(attempts(), CANDIDATES, true, 2); - SetupErrorSteps steps; - LineLogger logger; - const size_t sids = tracker.remaining_sids().size(); - bool thrown = false; - try{ - run_starter_rng_plan(logger, tracker, steps, LIMITS, 12345, CANDIDATES); - }catch (UserSetupError&){ - thrown = true; - } - const bool result_line = std::any_of(logger.lines.begin(), logger.lines.end(), [](const std::string& line){ - return line.starts_with("RngPlan: result") || line.starts_with("RngPlan: attempt"); - }); - const std::string expected = std::format("thrown 1, calls 1, attempt 1, sids {}, result line 0", sids); - const std::string got = std::format( - "thrown {}, calls {}, attempt {}, sids {}, result line {}", - int(thrown), steps.calls, tracker.attempt_index() + 1, tracker.remaining_sids().size(), int(result_line) - ); - if (got != expected){ - return "Expected " + expected + "; got " + got; - } - return true; -} - // What the run says after a shiny, by what it tells of the SID. UnitTestResult test_shiny_messages(){ @@ -430,25 +79,6 @@ UnitTestResult test_shiny_messages(){ } -// The state line on its own: hours, empty lists and a negative offset. -UnitTestResult test_state_line(){ - const std::string got = rng_log_state(RngLoopState{ - .attempt = 3, .attempts = 5, .try_number = 2, .tries = 3, .resets = 41, .max_resets = 50, - .seed = 0x70fe, .advances = 1200, .sids = {}, .ruled_out = {7, 8}, - .attempt_time = std::chrono::seconds(3 * 3600 + 61), .attempt_cap = std::chrono::hours(3), - .total_time = std::chrono::minutes(605), .total_cap = std::chrono::hours(12), - .calibration = RngCalibrations{-0.5, 12, -3.125}, - }); - const std::string expected = - "RngPlan: state attempt=3/5 try=2/3 reset=41/50 seed=70FE advances=1200 sids=- ruled_out=7,8 " - "attempt_time=03:01:01/03:00:00 total_time=10:05:00/12:00:00 calibration=-0.50/12.00/-3.12"; - if (got != expected){ - return "Expected \"" + expected + "\", got \"" + got + "\"."; - } - return true; -} - - // After a shiny, 00.04b picks up at the rival's trigger and runs on. UnitTestResult test_rows_after_shiny(){ const std::vector& checkpoints = story_checkpoints(); @@ -491,12 +121,6 @@ UnitTestResult test_rows_after_shiny(){ void add_tests_AutoStoryRngLoop(UnitTestDatabase& database){ - for (const LoopRow& row : LOOP_ROWS){ - database.add(row.name, [row]{ return run_loop_row(row); }); - } - database.add("attempt deadlines", test_deadlines); - database.add("a setup error stops the loop", test_setup_error_stops); - database.add("state line", test_state_line); database.add("shiny messages", test_shiny_messages); database.add("rows after a shiny", test_rows_after_shiny); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp new file mode 100644 index 0000000000..cabc1322d9 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp @@ -0,0 +1,95 @@ +/* Starter RNG Console Steps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonFRLG_StarterRngConsoleSteps.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +RngPlanLogger::RngPlanLogger(ConsoleHandle& console) + : m_console(console) +{} + +void RngPlanLogger::log(const std::string& msg, Color color){ + m_console.log(msg, color); + if (msg.starts_with("RngPlan: state") || msg.starts_with("RngPlan: result")){ + m_console.overlay().add_log(msg); + } +} + + +ConsoleStarterRngSteps::ConsoleStarterRngSteps( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StarterRngConsoleSettings& settings, const StarterRngNotifications& notifications +) + : m_env(env) + , m_context(context) + , m_settings(settings) + , m_notifications(notifications) + // TODO: LeafGreen, once AutoStory plays it. + , m_seeds(seeds_json_path(true, settings.language)) +{} + +WallClock ConsoleStarterRngSteps::now(){ + return current_time(); +} + +StarterRngResult ConsoleStarterRngSteps::run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call){ + // Starter RNG's default Nearby Seed Radius. + const int SEED_RADIUS = 5; + const SeedMatch seed_match = m_seeds.find_seed(attempt.target.seed.seed, m_settings.sound, SEED_RADIUS); + if (!seed_match.found){ + throw InternalProgramError(&m_env.logger(), PA_CURRENT_FUNCTION, "The plan's seed isn't in the seed list it came from."); + } + + StarterRngStats stats; + StarterRngAttempts attempts( + StarterRngTarget{ + .starter = StarterSpecies::squirtle, + .seed = attempt.target.seed.seed, + .advances = attempt.target.advances, + .seed_match = seed_match, + }, + StarterRngSettings{ + .language = m_settings.language, + .profile = 0, + .ignore_wild_shinies = true, + .take_video = false, + .identify_shiny = true, + .max_resets = [deadline = call.deadline, max_resets = call.max_resets]{ + return current_time() >= deadline ? uint64_t(0) : max_resets; + }, + .on_reset = call.on_reset, + }, + StarterRngDisplays{ + .target = m_target_display, + .filters = m_filter_display, + .calibration = m_calibration_display, + }, + m_notifications, + stats + ); + try{ + return attempts.run(m_env, m_context); + }catch (OperationFailedException& e){ + // Starter RNG refuses timings it can't press (check_timings()) this + // way; a failure in the game sends an error report. + if (e.error_report_mode() != ErrorReportMode::NO_ERROR_REPORT){ + throw; + } + throw StarterRngTimingsRefused(e.message()); + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h new file mode 100644 index 0000000000..4b3f3b132e --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h @@ -0,0 +1,80 @@ +/* Starter RNG Console Steps + * + * From: https://github.com/PokemonAutomation/ + * + * The Starter RNG loop's steps (PokemonFRLG_StarterRngLoop.h) on the + * console, and the log it writes to. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngConsoleSteps_H +#define PokemonAutomation_PokemonFRLG_StarterRngConsoleSteps_H + +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/Time.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngDisplays.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_SeedsDatabase.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// The console's log, with the loop's state and result lines also on the +// stream's overlay log. +class RngPlanLogger : public Logger{ +public: + explicit RngPlanLogger(ConsoleHandle& console); + virtual void log(const std::string& msg, Color color = Color()) override; + +private: + ConsoleHandle& m_console; +}; + + +struct StarterRngConsoleSettings{ + Language language = Language::English; + SoundSetting sound = SoundSetting::Mono; +}; + +// The loop's steps on the console, with Starter RNG's displays, stats and +// calibration kept here (AutoStory doesn't show them). Each try starts +// from the calibration the last one ended with. Squirtle, FireRed, the +// Switch's default profile. +class ConsoleStarterRngSteps : public StarterRngLoopSteps{ +public: + ConsoleStarterRngSteps( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const StarterRngConsoleSettings& settings, const StarterRngNotifications& notifications + ); + + virtual WallClock now() override; + virtual StarterRngResult run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call) override; + +private: + SingleSwitchProgramEnvironment& m_env; + ProControllerContext& m_context; + StarterRngConsoleSettings m_settings; + StarterRngNotifications m_notifications; + SeedsDatabase m_seeds; + RngTargetDisplay m_target_display; + RngFilterDisplay m_filter_display; + RngCalibrationDisplay m_calibration_display; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp new file mode 100644 index 0000000000..bff10d04b2 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp @@ -0,0 +1,261 @@ +/* Starter RNG Loop + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h" +#include "PokemonFRLG_StarterRngLoop.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +RngAttemptOutcome plan_outcome(StarterRngOutcome outcome){ + switch (outcome){ + case StarterRngOutcome::shiny_on_target: + return RngAttemptOutcome::SHINY; + case StarterRngOutcome::shiny: + case StarterRngOutcome::shiny_off_target: + return RngAttemptOutcome::SHINY_OFF_TARGET; + case StarterRngOutcome::target_hit: + return RngAttemptOutcome::HIT_NOT_SHINY; + case StarterRngOutcome::wild_shiny: + case StarterRngOutcome::out_of_resets: + case StarterRngOutcome::no_matches: + return RngAttemptOutcome::MISSED; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Starter RNG outcome."); +} + +std::string starter_rng_outcome_name(StarterRngOutcome outcome){ + switch (outcome){ + case StarterRngOutcome::shiny: + return "shiny"; + case StarterRngOutcome::shiny_on_target: + return "shiny_on_target"; + case StarterRngOutcome::shiny_off_target: + return "shiny_off_target"; + case StarterRngOutcome::target_hit: + return "target_hit"; + case StarterRngOutcome::wild_shiny: + return "wild_shiny"; + case StarterRngOutcome::out_of_resets: + return "out_of_resets"; + case StarterRngOutcome::no_matches: + return "no_matches"; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Starter RNG outcome."); +} + + +namespace{ + +// "-" for none. +std::string join_sids(const std::vector& sids){ + std::string text; + for (uint16_t sid : sids){ + text += (text.empty() ? "" : ",") + std::to_string(sid); + } + return text.empty() ? "-" : text; +} + +std::string clock_text(Milliseconds time){ + const int64_t seconds = std::chrono::duration_cast(time).count(); + return std::format("{:02}:{:02}:{:02}", seconds / 3600, seconds / 60 % 60, seconds % 60); +} + +std::string calibration_text(const std::optional& calibration){ + if (!calibration){ + return "-"; + } + return std::format("{:.2f}/{:.2f}/{:.2f}", calibration->seed_offset, calibration->csf_offset, calibration->ingame_offset); +} + +} + +std::string rng_log_state(const RngLoopState& state){ + return std::format( + "RngPlan: state attempt={}/{} try={}/{} reset={}/{} seed={:04X} advances={} sids={} ruled_out={} " + "attempt_time={}/{} total_time={}/{} calibration={}", + state.attempt, state.attempts, state.try_number, state.tries, state.resets, state.max_resets, + state.seed, state.advances, join_sids(state.sids), join_sids(state.ruled_out), + clock_text(state.attempt_time), clock_text(state.attempt_cap), + clock_text(state.total_time), clock_text(state.total_cap), + calibration_text(state.calibration) + ); +} + + +namespace{ + +std::optional loop_end(RngPlanStep step){ + switch (step){ + case RngPlanStep::RUN_ATTEMPT: + return std::nullopt; + case RngPlanStep::GOT_SHINY: + return StarterRngLoopEnd::SHINY; + case RngPlanStep::GOT_SHINY_OFF_TARGET: + return StarterRngLoopEnd::SHINY_OFF_TARGET; + case RngPlanStep::GOT_TARGET: + return StarterRngLoopEnd::TARGET; + case RngPlanStep::OUT_OF_ATTEMPTS: + return StarterRngLoopEnd::OUT_OF_ATTEMPTS; + case RngPlanStep::MISSED_EVERY_ATTEMPT_LEFT: + return StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown RNG plan step."); +} + +// The loop's state lines and tries, across the attempts. +class LoopLog{ +public: + LoopLog(Logger& logger, const RngPlanTracker& tracker, const StarterRngLoopLimits& limits, WallClock start) + : m_logger(logger) + , m_tracker(tracker) + , m_limits(limits) + , m_start(start) + , m_start_sids(tracker.remaining_sids()) + {} + + // A new try of the tracker's current attempt, starting at `now`. + void begin_try(WallClock now){ + const size_t index = m_tracker.attempt_index(); + m_try = (m_tries_of && *m_tries_of == index) ? m_try + 1 : 1; + m_tries_of = index; + m_try_start = now; + } + size_t try_number() const{ + return m_try; + } + + void log_state(WallClock now, uint64_t resets, const std::optional& calibration){ + const RngAttempt& attempt = m_tracker.current_attempt(); + std::vector ruled_out; + for (uint16_t sid : m_start_sids){ + const std::vector& left = m_tracker.remaining_sids(); + if (std::find(left.begin(), left.end(), sid) == left.end()){ + ruled_out.push_back(sid); + } + } + m_logger.log(rng_log_state(RngLoopState{ + .attempt = m_tracker.attempt_index() + 1, .attempts = m_tracker.attempt_count(), + .try_number = m_try, .tries = m_limits.max_retries + 1, + .resets = resets, .max_resets = m_limits.max_resets, + .seed = attempt.target.seed.seed, .advances = attempt.target.advances, + .sids = attempt.sids, .ruled_out = std::move(ruled_out), + .attempt_time = std::chrono::duration_cast(now - m_try_start), .attempt_cap = m_limits.attempt_time, + .total_time = std::chrono::duration_cast(now - m_start), .total_cap = m_limits.total_time, + .calibration = calibration, + })); + } + +private: + Logger& m_logger; + const RngPlanTracker& m_tracker; + const StarterRngLoopLimits& m_limits; + const WallClock m_start; + const std::vector m_start_sids; + std::optional m_tries_of; + size_t m_try = 0; + WallClock m_try_start; +}; + +// What one try came to, for the tracker and the result line. +struct TryOutcome{ + RngAttemptOutcome outcome = RngAttemptOutcome::MISSED; + std::string detail; + std::optional pokemon; +}; + +// Runs one try of the tracker's current attempt, logging its state lines. +StarterRngResult run_try( + LoopLog& log, const RngPlanTracker& tracker, StarterRngLoopSteps& steps, + const StarterRngLoopLimits& limits, WallClock start, WallClock deadline +){ + log.begin_try(start); + log.log_state(start, 0, std::nullopt); + StarterRngAttemptCall call{ + .index = tracker.attempt_index(), + .deadline = deadline, + .max_resets = limits.max_resets, + .on_reset = [&](const StarterRngProgress& progress){ + log.log_state(steps.now(), progress.resets, progress.calibrations); + }, + }; + return steps.run_attempt(tracker.current_attempt(), call); +} + +// run_try(), with Starter RNG refusing the attempt's timings as an attempt +// that can't run. Other errors, a setup error such as no sound included, +// would fail every attempt the same way, so they end the loop. +TryOutcome run_try_outcome( + Logger& logger, LoopLog& log, const RngPlanTracker& tracker, StarterRngLoopSteps& steps, + const StarterRngLoopLimits& limits, WallClock start, WallClock deadline +){ + try{ + const StarterRngResult attempt = run_try(log, tracker, steps, limits, start, deadline); + // The deadline ends a try as out of resets. + const bool past_deadline = attempt.outcome == StarterRngOutcome::out_of_resets && steps.now() >= deadline; + return TryOutcome{ + .outcome = plan_outcome(attempt.outcome), + .detail = past_deadline ? "attempt_deadline" : starter_rng_outcome_name(attempt.outcome), + .pokemon = attempt.pokemon, + }; + }catch (StarterRngTimingsRefused& e){ + logger.log(std::format("RngPlan: attempt {} can't run: {}", tracker.attempt_index() + 1, e.message()), COLOR_RED); + return TryOutcome{.outcome = RngAttemptOutcome::UNUSABLE, .detail = "setup_error", .pokemon = std::nullopt}; + } +} + +} + + +StarterRngLoopResult run_starter_rng_plan( + Logger& logger, RngPlanTracker& tracker, StarterRngLoopSteps& steps, + const StarterRngLoopLimits& limits, uint16_t tid, const std::vector& sid_helper_candidates +){ + StarterRngLoopResult result; + const WallClock loop_start = steps.now(); + const WallClock total_deadline = loop_start + limits.total_time; + LoopLog log(logger, tracker, limits, loop_start); + while (true){ + std::optional end = loop_end(tracker.step()); + if (end){ + result.end = *end; + break; + } + const WallClock start = steps.now(); + if (start >= total_deadline){ + logger.log("RngPlan: out of time before attempt " + std::to_string(tracker.attempt_index() + 1)); + result.end = StarterRngLoopEnd::OUT_OF_TIME; + break; + } + const size_t index = tracker.attempt_index(); + const WallClock deadline = std::min(start + limits.attempt_time, total_deadline); + const TryOutcome attempt = run_try_outcome(logger, log, tracker, steps, limits, start, deadline); + result.attempts_run++; + const RngPlanStep step = tracker.record(attempt.outcome); + logger.log(rng_log_result(RngResultLog{ + .index = index, .try_number = log.try_number(), .outcome = attempt.outcome, + .detail = attempt.detail, .pokemon = attempt.pokemon, + .next = rng_plan_next(step, index, tracker.attempt_index()), + })); + } + result.remaining_sids = tracker.remaining_sids(); + result.sid = tracker.confirmed_sid(); + if (result.end == StarterRngLoopEnd::SHINY && result.sid){ + logger.log(rng_log_confirmed(tid, *result.sid, sid_helper_candidates)); + } + return result; +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h new file mode 100644 index 0000000000..1307ebb47d --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h @@ -0,0 +1,161 @@ +/* Starter RNG Loop + * + * From: https://github.com/PokemonAutomation/ + * + * An RNG plan's attempts (PokemonFRLG_RngPlan.h), each run with Starter + * RNG's attempt loop (StarterRngAttempts), until one comes out shiny or + * the plan, its retries or the time run out. Its "RngPlan: state" and + * "RngPlan: result" lines are listed with the plan's in + * PokemonFRLG_RngPlanLog.h. + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngLoop_H +#define PokemonAutomation_PokemonFRLG_StarterRngLoop_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/Time.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngCalibration.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanTracker.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngTargetSearch.h" +#include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +// Starter RNG's outcome as the RNG plan counts it. Only a shiny on the +// target is SHINY; one off it, or not known to be on it, is +// SHINY_OFF_TARGET. Out of resets, no matches and a wild shiny are misses, +// which the plan runs again. +RngAttemptOutcome plan_outcome(StarterRngOutcome outcome); +// As the result line names it: "shiny_on_target", "target_hit", +// "out_of_resets"... (The loop says "attempt_deadline" instead of +// "out_of_resets" once the try's deadline has passed.) +std::string starter_rng_outcome_name(StarterRngOutcome outcome); + + +// Where the loop is, for an "RngPlan: state" line. +struct RngLoopState{ + // From 1, of `attempts`. + size_t attempt = 1; + size_t attempts = 0; + // From 1, of `tries`. + size_t try_number = 1; + size_t tries = 0; + uint64_t resets = 0; + uint64_t max_resets = 0; + uint16_t seed = 0; + uint64_t advances = 0; + // The SIDs the attempt is shiny for, and those ruled out so far. + std::vector sids; + std::vector ruled_out; + Milliseconds attempt_time = Milliseconds(0); + Milliseconds attempt_cap = Milliseconds(0); + Milliseconds total_time = Milliseconds(0); + Milliseconds total_cap = Milliseconds(0); + // The calibration of the last reset, in frames; none before the first. + std::optional calibration; +}; +std::string rng_log_state(const RngLoopState& state); + + +struct StarterRngLoopLimits{ + // An attempt makes no more resets after this long, and counts as missed. + Milliseconds attempt_time = Milliseconds(0); + // No attempt starts after this long. + Milliseconds total_time = Milliseconds(0); + // Resets per try of an attempt. + uint64_t max_resets = 0; + // The tracker's retries of a missed attempt, for the state lines. + size_t max_retries = 0; +}; + +// Starter RNG refused an attempt's timings (check_timings()). The loop +// records the attempt as unusable and moves on; any other error, a +// UserSetupError included, stops the loop. +class StarterRngTimingsRefused : public Exception{ +public: + explicit StarterRngTimingsRefused(std::string message) : m_message(std::move(message)) {} + virtual const char* name() const override{ return "StarterRngTimingsRefused"; } + virtual std::string message() const override{ return m_message; } + +private: + std::string m_message; +}; + +// One try of an attempt, as the loop asks the steps for it. +struct StarterRngAttemptCall{ + // From 0. + size_t index = 0; + // No reset after this. + WallClock deadline; + uint64_t max_resets = 0; + // To call after each reset. + std::function on_reset; +}; + +// The game steps of the loop, injected so that its decisions run in tests +// without a Switch. +class StarterRngLoopSteps{ +public: + virtual ~StarterRngLoopSteps() = default; + virtual WallClock now() = 0; + // Runs Starter RNG's attempts at `attempt`'s target from the save under + // the ball, as `call` says. Throws StarterRngTimingsRefused when + // Starter RNG refuses the attempt's timings; the loop logs it and moves on. + virtual StarterRngResult run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call) = 0; +}; + +enum class StarterRngLoopEnd{ + // The starter is shiny and the target; the game is on its summary, not saved. + SHINY, + // The starter is shiny but not the target (or not known to be), so it + // doesn't tell the SID; the game is on its summary, not saved. + SHINY_OFF_TARGET, + // Shiny not required, and the target was hit. The game is where + // Starter RNG's calibration left it, not saved. + TARGET, + // Every attempt was hit and none was shiny. + OUT_OF_ATTEMPTS, + // The last attempt still shiny for a SID left missed more often than + // the retries allow, or couldn't run. + MISSED_EVERY_ATTEMPT_LEFT, + // The total time ran out with attempts left. + OUT_OF_TIME, +}; + +struct StarterRngLoopResult{ + StarterRngLoopEnd end = StarterRngLoopEnd::OUT_OF_TIME; + // Attempts run, retries included. + size_t attempts_run = 0; + // The SID candidates not ruled out. + std::vector remaining_sids; + // The SID, once a shiny leaves one candidate. + std::optional sid; +}; + +// Runs `tracker`'s attempts through `steps` until the plan ends or +// `limits.total_time` has passed. Logs an "RngPlan: state" line at the +// start of each try and after each reset, an "RngPlan: result" line after +// it and, when a shiny leaves one SID, an "RngPlan: confirmed" line placing +// it among SID Helper's candidates for `tid`. +StarterRngLoopResult run_starter_rng_plan( + Logger& logger, RngPlanTracker& tracker, StarterRngLoopSteps& steps, + const StarterRngLoopLimits& limits, uint16_t tid, const std::vector& sid_helper_candidates +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp new file mode 100644 index 0000000000..547b6b3dcc --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp @@ -0,0 +1,432 @@ +/* Starter RNG Loop Tests + * + * From: https://github.com/PokemonAutomation/ + * + * The Starter RNG loop's decisions and log lines on scripted attempt + * outcomes and a fake clock. + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "Common/Cpp/TestRunners/UnitTest.h" +#include "PokemonFRLG_StarterRngLoop.h" +#include "PokemonFRLG_StarterRngLoop_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +namespace{ + +class Test_StarterRngLoop : public UnitTest{ +public: + Test_StarterRngLoop(std::string name, std::function body) + : UnitTest("PokemonFRLG::StarterRngLoop - " + std::move(name)) + , m_body(std::move(body)) + {} + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + try{ + return m_body(); + }catch (Exception& e){ + return std::string(e.name()) + ": " + e.message(); + } + } + +private: + std::function m_body; +}; + + +class LineLogger : public Logger{ +public: + virtual void log(const std::string& msg, Color) override{ + lines.push_back(msg); + } + bool has(const std::string& line) const{ + return std::find(lines.begin(), lines.end(), line) != lines.end(); + } + + std::vector lines; +}; + +// Each try takes `minutes_per_attempt` on the clock, makes one reset at +// its end with calibration 1.5/-2/0.25 frames, and comes out as the next +// of `outcomes`. An empty one is Starter RNG refusing the timings: a +// StarterRngTimingsRefused at once. +class ScriptedSteps : public StarterRngLoopSteps{ +public: + ScriptedSteps(std::vector> outcomes, int minutes_per_attempt) + : m_outcomes(std::move(outcomes)) + , m_minutes(minutes_per_attempt) + {} + + virtual WallClock now() override{ + return m_now; + } + virtual StarterRngResult run_attempt(const RngAttempt&, const StarterRngAttemptCall& call) override{ + if (m_next >= m_outcomes.size()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "More attempts than scripted."); + } + indices.push_back(call.index); + deadlines_min.push_back(int(std::chrono::duration_cast(call.deadline - START).count())); + const std::optional outcome = m_outcomes[m_next++]; + if (!outcome){ + throw StarterRngTimingsRefused("Refused timings."); + } + m_now += std::chrono::minutes(m_minutes); + call.on_reset(StarterRngProgress{.resets = 1, .calibrations = {1.5, -2, 0.25}}); + return StarterRngResult{.outcome = *outcome, .pokemon = std::nullopt}; + } + + std::vector indices; + // Each attempt's deadline, in minutes from the start. + std::vector deadlines_min; + +private: + static inline const WallClock START = WallClock{} + std::chrono::hours(1000); + std::vector> m_outcomes; + int m_minutes; + LineLogger m_logger; + WallClock m_now = START; + size_t m_next = 0; +}; + +// A setup problem Starter RNG hits on every attempt alike, such as no +// audio input. +class SetupErrorSteps : public StarterRngLoopSteps{ +public: + virtual WallClock now() override{ + return WallClock{} + std::chrono::hours(1000); + } + virtual StarterRngResult run_attempt(const RngAttempt&, const StarterRngAttemptCall&) override{ + calls++; + throw UserSetupError(m_logger, "No sound detected."); + } + + size_t calls = 0; + +private: + LineLogger m_logger; +}; + +// SID Helper's candidates 100, 200, 300; attempt 1 is shiny for 100 and +// 200, attempt 2 for 300. +const std::vector CANDIDATES = {{100, 1}, {200, 2}, {300, 1}}; + +std::vector attempts(){ + RngAttempt first{}; + first.target.seed.seed = 0xceff; + first.target.advances = 983; + first.sids = {100, 200}; + RngAttempt second{}; + second.target.seed.seed = 0x2ef6; + second.target.advances = 29364; + second.sids = {300}; + return {first, second}; +} + +// 60-minute tries, 12 hours in all, 50 resets a try, 2 retries. +const StarterRngLoopLimits LIMITS{ + .attempt_time = std::chrono::minutes(60), + .total_time = std::chrono::hours(12), + .max_resets = 50, + .max_retries = 2, +}; + +std::string end_name(StarterRngLoopEnd end){ + switch (end){ + case StarterRngLoopEnd::SHINY: + return "SHINY"; + case StarterRngLoopEnd::SHINY_OFF_TARGET: + return "SHINY_OFF_TARGET"; + case StarterRngLoopEnd::TARGET: + return "TARGET"; + case StarterRngLoopEnd::OUT_OF_ATTEMPTS: + return "OUT_OF_ATTEMPTS"; + case StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT: + return "MISSED_EVERY_ATTEMPT_LEFT"; + case StarterRngLoopEnd::OUT_OF_TIME: + return "OUT_OF_TIME"; + } + return "?"; +} + +std::string join(const std::vector& values){ + std::string text; + for (size_t value : values){ + text += (text.empty() ? "" : ",") + std::to_string(value + 1); + } + return text; +} + + +struct LoopRow{ + std::string name; + // Empty: Starter RNG refuses the attempt's timings. + std::vector> outcomes; + int minutes_per_attempt; + bool shiny_required; + StarterRngLoopEnd end; + // The attempts run, from 1, as "1,1,2". + std::string attempts_run; + // The SID confirmed, or 0 for none; with it, an "RngPlan: confirmed" line. + uint16_t sid; + // Log lines the loop must write. + std::vector lines; +}; + +using enum StarterRngOutcome; +const std::optional REFUSED = std::nullopt; + +const std::vector LOOP_ROWS = { + { + .name = "hit, then shiny confirms the SID", + .outcomes = {target_hit, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,2", .sid = 300, + .lines = { + "RngPlan: state attempt=1/2 try=1/3 reset=0/50 seed=CEFF advances=983 sids=100,200 ruled_out=- " + "attempt_time=00:00:00/01:00:00 total_time=00:00:00/12:00:00 calibration=-", + "RngPlan: state attempt=1/2 try=1/3 reset=1/50 seed=CEFF advances=983 sids=100,200 ruled_out=- " + "attempt_time=00:30:00/01:00:00 total_time=00:30:00/12:00:00 calibration=1.50/-2.00/0.25", + "RngPlan: result attempt=1 try=1 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=next_attempt", + "RngPlan: state attempt=2/2 try=1/3 reset=0/50 seed=2EF6 advances=29364 sids=300 ruled_out=100,200 " + "attempt_time=00:00:00/01:00:00 total_time=00:30:00/12:00:00 calibration=-", + "RngPlan: result attempt=2 try=1 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", + "RngPlan: confirmed tid=12345 sid=300 candidate=3 of=3", + }, + }, + { + .name = "shiny on the target for two SIDs confirms none", + .outcomes = {shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1", .sid = 0, + .lines = {"RngPlan: result attempt=1 try=1 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm"}, + }, + { + .name = "shiny off the target confirms nothing", + .outcomes = {target_hit, shiny_off_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY_OFF_TARGET, .attempts_run = "1,2", .sid = 0, + .lines = {"RngPlan: result attempt=2 try=1 outcome=shiny_off_target starter_rng=shiny_off_target nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "a shiny not known to be the target confirms nothing", + .outcomes = {shiny}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY_OFF_TARGET, .attempts_run = "1", .sid = 0, + .lines = {"RngPlan: result attempt=1 try=1 outcome=shiny_off_target starter_rng=shiny nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "misses retry the same attempt", + .outcomes = {out_of_resets, no_matches, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,1", .sid = 0, + .lines = { + "RngPlan: result attempt=1 try=1 outcome=missed starter_rng=out_of_resets nature=- ivs=- pid=- next=retry", + "RngPlan: result attempt=1 try=2 outcome=missed starter_rng=no_matches nature=- ivs=- pid=- next=retry", + "RngPlan: result attempt=1 try=3 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", + }, + }, + { + .name = "an attempt past its deadline", + .outcomes = {out_of_resets, shiny_on_target}, + .minutes_per_attempt = 90, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1", .sid = 0, + .lines = {"RngPlan: result attempt=1 try=1 outcome=missed starter_rng=attempt_deadline nature=- ivs=- pid=- next=retry"}, + }, + { + .name = "retries used up, then the next attempt", + .outcomes = {out_of_resets, no_matches, wild_shiny, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,1,2", .sid = 300, + .lines = { + "RngPlan: result attempt=1 try=3 outcome=missed starter_rng=wild_shiny nature=- ivs=- pid=- next=next_attempt", + "RngPlan: result attempt=2 try=1 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", + "RngPlan: confirmed tid=12345 sid=300 candidate=3 of=3", + }, + }, + { + .name = "every attempt left missed too often", + .outcomes = {out_of_resets, out_of_resets, out_of_resets, no_matches, no_matches, no_matches}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT, .attempts_run = "1,1,1,2,2,2", .sid = 0, + .lines = {"RngPlan: result attempt=2 try=3 outcome=missed starter_rng=no_matches nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "miss, hit, miss, then shiny", + .outcomes = {out_of_resets, target_hit, no_matches, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,1,2,2", .sid = 300, + .lines = { + "RngPlan: result attempt=1 try=2 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=next_attempt", + "RngPlan: result attempt=2 try=2 outcome=shiny starter_rng=shiny_on_target nature=- ivs=- pid=- next=confirm", + }, + }, + { + .name = "an attempt whose timings Starter RNG refuses is skipped", + .outcomes = {REFUSED, shiny_on_target}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::SHINY, .attempts_run = "1,2", .sid = 300, + .lines = { + "RngPlan: attempt 1 can't run: Refused timings.", + "RngPlan: result attempt=1 try=1 outcome=unusable starter_rng=setup_error nature=- ivs=- pid=- next=next_attempt", + }, + }, + { + .name = "no attempt Starter RNG will run", + .outcomes = {REFUSED, REFUSED}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::MISSED_EVERY_ATTEMPT_LEFT, .attempts_run = "1,2", .sid = 0, + .lines = {"RngPlan: result attempt=2 try=1 outcome=unusable starter_rng=setup_error nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "every attempt hit, none shiny", + .outcomes = {target_hit, target_hit}, + .minutes_per_attempt = 30, .shiny_required = true, + .end = StarterRngLoopEnd::OUT_OF_ATTEMPTS, .attempts_run = "1,2", .sid = 0, + .lines = {"RngPlan: result attempt=2 try=1 outcome=hit_not_shiny starter_rng=target_hit nature=- ivs=- pid=- next=stop"}, + }, + { + .name = "a hit ends the plan with shiny not required", + .outcomes = {target_hit}, + .minutes_per_attempt = 30, .shiny_required = false, + .end = StarterRngLoopEnd::TARGET, .attempts_run = "1", .sid = 0, + .lines = {}, + }, + { + .name = "no attempt starts after the total time", + .outcomes = {out_of_resets, out_of_resets}, + .minutes_per_attempt = 400, .shiny_required = true, + .end = StarterRngLoopEnd::OUT_OF_TIME, .attempts_run = "1,1", .sid = 0, + .lines = { + "RngPlan: state attempt=1/2 try=2/3 reset=1/50 seed=CEFF advances=983 sids=100,200 ruled_out=- " + "attempt_time=06:40:00/01:00:00 total_time=13:20:00/12:00:00 calibration=1.50/-2.00/0.25", + "RngPlan: out of time before attempt 1", + }, + }, +}; + +UnitTestResult run_loop_row(const LoopRow& row){ + RngPlanTracker tracker(attempts(), CANDIDATES, row.shiny_required, 2); + ScriptedSteps steps(row.outcomes, row.minutes_per_attempt); + LineLogger logger; + StarterRngLoopResult result = run_starter_rng_plan(logger, tracker, steps, LIMITS, 12345, CANDIDATES); + + const std::string expected = std::format("end {}, attempts {}, sid {}", end_name(row.end), row.attempts_run, row.sid); + const std::string got = std::format( + "end {}, attempts {}, sid {}", end_name(result.end), join(steps.indices), result.sid.value_or(0) + ); + if (expected != got){ + return "Expected " + expected + "; got " + got; + } + for (const std::string& line : row.lines){ + if (!logger.has(line)){ + return "Expected the log line \"" + line + "\""; + } + } + const bool confirmed = std::any_of(logger.lines.begin(), logger.lines.end(), [](const std::string& line){ + return line.starts_with("RngPlan: confirmed"); + }); + if (confirmed != (row.sid != 0)){ + return std::format("Expected {} \"RngPlan: confirmed\" line", row.sid != 0 ? "a" : "no"); + } + if (result.attempts_run != steps.indices.size()){ + return std::format("Expected attempts_run {}; got {}", steps.indices.size(), result.attempts_run); + } + return true; +} + + +// An attempt's deadline is an hour after it starts, or the end of the +// total time if sooner: attempts of 400 minutes start at 0 and 400, and +// none at 800, past the total of 430. +UnitTestResult test_deadlines(){ + RngPlanTracker tracker(attempts(), CANDIDATES, true, 5); + ScriptedSteps steps({StarterRngOutcome::out_of_resets, StarterRngOutcome::out_of_resets}, 400); + LineLogger logger; + const StarterRngLoopLimits limits{ + .attempt_time = std::chrono::minutes(60), .total_time = std::chrono::minutes(430), .max_resets = 50, .max_retries = 5, + }; + run_starter_rng_plan(logger, tracker, steps, limits, 12345, CANDIDATES); + std::string got; + for (int deadline : steps.deadlines_min){ + got += (got.empty() ? "" : ",") + std::to_string(deadline); + } + if (got != "60,430"){ + return "Expected deadlines 60,430 minutes; got " + got; + } + return true; +} + + +// A setup error other than refused timings stops the loop at once: it +// reaches the program, and the attempt is neither recorded nor skipped. +UnitTestResult test_setup_error_stops(){ + RngPlanTracker tracker(attempts(), CANDIDATES, true, 2); + SetupErrorSteps steps; + LineLogger logger; + const size_t sids = tracker.remaining_sids().size(); + bool thrown = false; + try{ + run_starter_rng_plan(logger, tracker, steps, LIMITS, 12345, CANDIDATES); + }catch (UserSetupError&){ + thrown = true; + } + const bool result_line = std::any_of(logger.lines.begin(), logger.lines.end(), [](const std::string& line){ + return line.starts_with("RngPlan: result") || line.starts_with("RngPlan: attempt"); + }); + const std::string expected = std::format("thrown 1, calls 1, attempt 1, sids {}, result line 0", sids); + const std::string got = std::format( + "thrown {}, calls {}, attempt {}, sids {}, result line {}", + int(thrown), steps.calls, tracker.attempt_index() + 1, tracker.remaining_sids().size(), int(result_line) + ); + if (got != expected){ + return "Expected " + expected + "; got " + got; + } + return true; +} + + +// The state line on its own: hours, empty lists and a negative offset. +UnitTestResult test_state_line(){ + const std::string got = rng_log_state(RngLoopState{ + .attempt = 3, .attempts = 5, .try_number = 2, .tries = 3, .resets = 41, .max_resets = 50, + .seed = 0x70fe, .advances = 1200, .sids = {}, .ruled_out = {7, 8}, + .attempt_time = std::chrono::seconds(3 * 3600 + 61), .attempt_cap = std::chrono::hours(3), + .total_time = std::chrono::minutes(605), .total_cap = std::chrono::hours(12), + .calibration = RngCalibrations{-0.5, 12, -3.125}, + }); + const std::string expected = + "RngPlan: state attempt=3/5 try=2/3 reset=41/50 seed=70FE advances=1200 sids=- ruled_out=7,8 " + "attempt_time=03:01:01/03:00:00 total_time=10:05:00/12:00:00 calibration=-0.50/12.00/-3.12"; + if (got != expected){ + return "Expected \"" + expected + "\", got \"" + got + "\"."; + } + return true; +} + +} + + +void add_tests_StarterRngLoop(UnitTestDatabase& database){ + for (const LoopRow& row : LOOP_ROWS){ + database.add(row.name, [row]{ return run_loop_row(row); }); + } + database.add("attempt deadlines", test_deadlines); + database.add("a setup error stops the loop", test_setup_error_stops); + database.add("state line", test_state_line); +} + + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h new file mode 100644 index 0000000000..8c98b0a8cb --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h @@ -0,0 +1,23 @@ +/* Starter RNG Loop Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonFRLG_StarterRngLoop_Tests_H +#define PokemonAutomation_PokemonFRLG_StarterRngLoop_Tests_H + +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonFRLG{ + + +void add_tests_StarterRngLoop(UnitTestDatabase& database); + + +} +} +} +#endif diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 1dd5884e21..f7685d0cdd 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -1933,6 +1933,12 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRng.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngAttempts.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp + Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.cpp Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StaticRng.h Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_WildRng.cpp From 5cf2e1b2703d54e6c0e432272169b1e2cf6b9970 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 18:56:21 -0800 Subject: [PATCH 07/10] FRLG AutoStory: save the SID Starter RNG confirms in the RNG plan When the in-program Starter RNG loop ends on a shiny that leaves one SID, write it into RNG_PLAN.SID, so it is kept with the program's settings and the next run skips SID Helper's steps. Log it, say so in the loop's message and the finish message, and mention it in the SID option's text. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../AutoStory/PokemonFRLG_AutoStory.cpp | 35 ++++++++++++++++--- .../PokemonFRLG_AutoStoryRngLoop.cpp | 2 +- .../PokemonFRLG_AutoStoryRngLoop_Tests.cpp | 2 +- .../PokemonFRLG_AutoStoryRngOptions.cpp | 3 +- 4 files changed, 35 insertions(+), 7 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index 36856fdd14..b308ab0bd4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -405,10 +405,11 @@ const StarterRngLoopLimits STARTER_RNG_LIMITS{ // Starter RNG's attempts in the program, from the save south of the table. // Returns true for a shiny Squirtle, on the target or not, the game on its -// summary; otherwise the run has stopped with what to do next. +// summary; otherwise the run has stopped with what to do next. A shiny that +// confirms the SID writes it into the RNG plan's SID option. static bool run_starter_rng_in_program( SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const StarterRngPlanned& planned, const StarterRngPlanOptions& options, Language language, + const StarterRngPlanned& planned, StarterRngPlanOptions& options, Language language, const StarterRngNotifications& notifications, EventNotificationOption& finished ){ RngPlanTracker tracker( @@ -421,6 +422,18 @@ static bool run_starter_rng_in_program( const StarterRngLoopResult result = run_starter_rng_plan( logger, tracker, steps, STARTER_RNG_LIMITS, planned.tid, options.helper_candidates(planned.tid) ); + const std::string confirmed_sid = result.sid ? std::to_string(*result.sid) : ""; + if (result.end == StarterRngLoopEnd::SHINY && result.sid && static_cast(options.SID) != confirmed_sid){ + // Kept in AutoStory's settings, so the next run plans for it and skips SID + // Helper's steps. Deferred: a per-save record keyed by TID (e.g. UserSettings/ + // FRLG-Saves.json: TID -> SID, version, language) that any FRLG RNG program + // could read, once a second program needs the SID. + options.SID.set(confirmed_sid); + env.console.log( + "AutoStory: set the RNG plan's SID to " + confirmed_sid + ". The settings file gets it " + "when the program's panel is closed or the app quits.", COLOR_BLUE + ); + } const std::string message = starter_rng_loop_message(result); if (result.end != StarterRngLoopEnd::SHINY && result.end != StarterRngLoopEnd::SHINY_OFF_TARGET){ stop_for_handoff(env, finished, message); @@ -450,6 +463,20 @@ static std::string run_after_shiny_starter( return rows.back().id; } +// The run is done through `done_through`. The finish message also gives +// the SID when Starter RNG set it, from `sid_before` to `sid_after`. +static void send_story_finished( + SingleSwitchProgramEnvironment& env, EventNotificationOption& finished, + const std::string& done_through, const std::string& sid_before, const std::string& sid_after +){ + std::string message = "AutoStory: done through " + done_through + "."; + if (sid_after != sid_before){ + message += " Starter RNG confirmed the SID, " + sid_after + ", and saved it as the RNG plan's SID."; + } + env.console.log(message); + send_program_finished_notification(env, finished, message); +} + StoryHandoffs AutoStory::story_handoffs() const{ // Running Starter RNG here splits 00.04 at the ball as its stop does, // and sets the SID at 00.01 when it isn't known. @@ -466,6 +493,7 @@ void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContex const std::string player_name = PLAYER_NAME; check_setup(env.console, checkpoints, first, last, NEW_GAME_FROM_TITLE, player_name); const StoryHandoffs handoffs = story_handoffs(); + const std::string sid_before = RNG_PLAN.SID; StoryRunPlan plan = plan_story_run(checkpoints, first, last, handoffs); if (plan.stop == StoryHandoff::SID_HELPER && !RUN_STARTER_RNG){ stop_for_sid_helper(env, context, NOTIFICATION_PROGRAM_FINISH, player_name); @@ -504,8 +532,7 @@ void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContex } done_through = *done; } - env.console.log("AutoStory: done through " + done_through + "."); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + send_story_finished(env, NOTIFICATION_PROGRAM_FINISH, done_through, sid_before, RNG_PLAN.SID); } std::optional AutoStory::after_starter_ball( diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp index 740caf3def..b30418f240 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp @@ -32,7 +32,7 @@ std::string starter_rng_loop_message(const StarterRngLoopResult& result){ switch (result.end){ case StarterRngLoopEnd::SHINY: if (result.sid){ - return std::format("Starter RNG: shiny Squirtle. The SID is {}: enter it as the RNG plan's SID.", *result.sid); + return std::format("Starter RNG: shiny Squirtle. The SID is {}: saved as the RNG plan's SID, so AutoStory skips SID Helper's steps next time.", *result.sid); } if (result.remaining_sids.empty()){ return "Starter RNG: shiny Squirtle, for none of the SID candidates left: the SID isn't one of SID Helper's candidates."; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp index 4e9a1a4846..3dc8e25675 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp @@ -53,7 +53,7 @@ UnitTestResult test_shiny_messages(){ const std::vector cases = { { .result = {.end = StarterRngLoopEnd::SHINY, .attempts_run = 2, .remaining_sids = {300}, .sid = uint16_t(300)}, - .expected = "Starter RNG: shiny Squirtle. The SID is 300: enter it as the RNG plan's SID.", + .expected = "Starter RNG: shiny Squirtle. The SID is 300: saved as the RNG plan's SID, so AutoStory skips SID Helper's steps next time.", }, { .result = {.end = StarterRngLoopEnd::SHINY, .attempts_run = 1, .remaining_sids = {100, 200}, .sid = std::nullopt}, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp index ffba355d14..17a5018541 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp @@ -27,7 +27,8 @@ StarterRngPlanOptions::StarterRngPlanOptions() ) , SID( false, - "SID:
The SID, once known. Empty: plan for the SIDs SID Helper lists, from the two options below.", + "SID:
The SID, once known. Empty: plan for the SIDs SID Helper lists, from the two options below. " + "Run Starter RNG in AutoStory fills it in when a shiny Squirtle confirms the SID.", LockMode::LOCK_WHILE_RUNNING, "", "" ) , SID_HELPER_ADVANCES( From 698713cf608601f12eb4443d90eb9787dd82c568 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 20:58:30 -0800 Subject: [PATCH 08/10] FRLG AutoStory: start Starter RNG from the stored calibration, save it back Starter RNG in AutoStory started every program run from a zero calibration and dropped what it learned. It now starts from the RNG plan's calibration (the console's seed and CSF offsets, and Starter RNG's own in-game offset, STARTER_INGAME) and saves each reset's calibration back, so a stopped run keeps it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../AutoStory/PokemonFRLG_AutoStory.cpp | 10 ++- .../PokemonFRLG_AutoStoryRngLoop.cpp | 24 ++++++ .../AutoStory/PokemonFRLG_AutoStoryRngLoop.h | 18 +++++ .../PokemonFRLG_AutoStoryRngLoop_Tests.cpp | 75 +++++++++++++++++++ .../PokemonFRLG_AutoStoryRngOptions.cpp | 6 ++ .../PokemonFRLG_AutoStoryRngOptions.h | 2 + .../PokemonFRLG_StarterRngConsoleSteps.cpp | 4 +- .../PokemonFRLG_StarterRngConsoleSteps.h | 6 +- 8 files changed, 139 insertions(+), 6 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index bca45f1643..58127b8b00 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -415,9 +415,13 @@ static bool run_starter_rng_in_program( RngPlanTracker tracker( planned.attempts, options.plan_candidates(env.console, planned.tid), options.SHINY_REQUIRED, STARTER_RNG_LIMITS.max_retries ); - ConsoleStarterRngSteps steps( - env, context, StarterRngConsoleSettings{.language = language, .sound = options.SOUND}, notifications - ); + // The settings file gets the calibration saved after each reset when + // the program's panel is closed or the app quits. + RngStopCalibrationOptions& calibration = options.CALIBRATION; + ConsoleStarterRngSteps console_steps(env, context, StarterRngConsoleSettings{ + .language = language, .sound = options.SOUND, .calibration = calibration.calibration(calibration.STARTER_INGAME), + }, notifications); + CalibrationSavingSteps steps(console_steps, calibration, calibration.STARTER_INGAME); RngPlanLogger logger(env.console); const StarterRngLoopResult result = run_starter_rng_plan( logger, tracker, steps, STARTER_RNG_LIMITS, planned.tid, options.helper_candidates(planned.tid) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp index b30418f240..f6c1f5d3c9 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp @@ -64,6 +64,30 @@ std::string starter_rng_loop_message(const StarterRngLoopResult& result){ } +CalibrationSavingSteps::CalibrationSavingSteps( + StarterRngLoopSteps& steps, RngStopCalibrationOptions& calibration, FloatingPointOption& ingame +) + : m_steps(steps) + , m_calibration(calibration) + , m_ingame(ingame) +{} + +WallClock CalibrationSavingSteps::now(){ + return m_steps.now(); +} + +StarterRngResult CalibrationSavingSteps::run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call){ + StarterRngAttemptCall saving = call; + saving.on_reset = [&](const StarterRngProgress& progress){ + m_calibration.save(progress.calibrations, m_ingame); + if (call.on_reset){ + call.on_reset(progress); + } + }; + return m_steps.run_attempt(attempt, saving); +} + + std::vector rows_after_starter_rng( const std::vector& checkpoints, size_t ball_row, size_t last ){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h index 266204c6c4..a6c0f248af 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h @@ -19,6 +19,7 @@ #include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlan.h" #include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h" #include "PokemonFRLG_AutoStoryEvents.h" +#include "PokemonFRLG_AutoStoryRngOptions.h" namespace PokemonAutomation{ namespace NintendoSwitch{ @@ -35,6 +36,23 @@ struct StarterRngPlanned{ std::string starter_rng_loop_message(const StarterRngLoopResult& result); +// `steps`, with the calibration of each reset also kept in the RNG plan's +// calibration, with `ingame` as the stop's in-game advances offset, so the +// next run starts from it. +class CalibrationSavingSteps : public StarterRngLoopSteps{ +public: + CalibrationSavingSteps(StarterRngLoopSteps& steps, RngStopCalibrationOptions& calibration, FloatingPointOption& ingame); + + virtual WallClock now() override; + virtual StarterRngResult run_attempt(const RngAttempt& attempt, const StarterRngAttemptCall& call) override; + +private: + StarterRngLoopSteps& m_steps; + RngStopCalibrationOptions& m_calibration; + FloatingPointOption& m_ingame; +}; + + // The rows a run takes after a shiny from the loop, which leaves the player // under Squirtle's ball with the rival's ball taken: the row after // `ball_row` (00.04b) from its step after "rival_takes_bulbasaur", then diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp index 3dc8e25675..f042a5349c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp @@ -117,12 +117,87 @@ UnitTestResult test_rows_after_shiny(){ return true; } + +std::string calibration_text(const RngCalibrations& calibration){ + return std::format("{}/{}/{}", calibration.seed_offset, calibration.csf_offset, calibration.ingame_offset); +} + +// Starter RNG starts from the RNG plan's calibration: the console's seed +// and Continue Screen Frames offsets, and Starter RNG's in-game offset. +UnitTestResult test_starter_calibration_from_options(){ + StarterRngPlanOptions options; + RngStopCalibrationOptions& calibration = options.CALIBRATION; + const RngCalibrations zero{.seed_offset = 0, .csf_offset = 0, .ingame_offset = 0}; + if (calibration.calibration(calibration.STARTER_INGAME) != zero){ + return "Expected no calibration by default; got " + calibration_text(calibration.calibration(calibration.STARTER_INGAME)); + } + calibration.SEED.set(17); + calibration.CSF.set(0.5); + calibration.STARTER_INGAME.set(-1.2); + const RngCalibrations expected{.seed_offset = 17 / FRLG_FRAME_DURATION, .csf_offset = 0.5, .ingame_offset = -1.2}; + const RngCalibrations got = calibration.calibration(calibration.STARTER_INGAME); + if (got != expected){ + return std::format("Expected calibration {}; got {}", calibration_text(expected), calibration_text(got)); + } + return true; +} + +// Steps whose one try resets once for each calibration in `resets`. +class ResettingSteps : public StarterRngLoopSteps{ +public: + explicit ResettingSteps(std::vector resets) : m_resets(std::move(resets)) {} + virtual WallClock now() override{ return WallClock{}; } + virtual StarterRngResult run_attempt(const RngAttempt&, const StarterRngAttemptCall& call) override{ + for (size_t c = 0; c < m_resets.size(); c++){ + call.on_reset(StarterRngProgress{.resets = c + 1, .calibrations = m_resets[c]}); + } + return StarterRngResult{.outcome = StarterRngOutcome::out_of_resets, .pokemon = std::nullopt}; + } + +private: + std::vector m_resets; +}; + +// Each reset's calibration is kept in the RNG plan before the loop hears +// of the reset, so a run stopped after it keeps it. +UnitTestResult test_starter_calibration_saved(){ + StarterRngPlanOptions options; + RngStopCalibrationOptions& calibration = options.CALIBRATION; + ResettingSteps resetting({ + {.seed_offset = 0.5, .csf_offset = 0.25, .ingame_offset = -0.5}, + {.seed_offset = 1.0, .csf_offset = 0.5, .ingame_offset = -1.2}, + }); + CalibrationSavingSteps steps(resetting, calibration, calibration.STARTER_INGAME); + std::vector csf_at_reset; + steps.run_attempt(RngAttempt{}, StarterRngAttemptCall{ + .index = 0, .deadline = WallClock{}, .max_resets = 2, + .on_reset = [&](const StarterRngProgress&){ csf_at_reset.emplace_back(calibration.CSF); }, + }); + if (csf_at_reset != std::vector{0.25, 0.5}){ + std::string got; + for (double csf : csf_at_reset){ + got += std::format(" {}", csf); + } + return "Expected the CSF offset saved at each reset as 0.25 0.5; got" + got; + } + // The seed offset is kept in ms: 1.0 frame is 16.7 ms. + if (int64_t(calibration.SEED) != 17 || double(calibration.STARTER_INGAME) != -1.2){ + return std::format( + "Expected seed 17 ms and Starter RNG in-game -1.2 saved; got {} ms and {}", + int64_t(calibration.SEED), double(calibration.STARTER_INGAME) + ); + } + return true; +} + } void add_tests_AutoStoryRngLoop(UnitTestDatabase& database){ database.add("shiny messages", test_shiny_messages); database.add("rows after a shiny", test_rows_after_shiny); + database.add("Starter RNG starts from the RNG plan's calibration", test_starter_calibration_from_options); + database.add("Starter RNG saves its calibration after each reset", test_starter_calibration_saved); } diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp index 41a99e8a6e..57943c2dcd 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.cpp @@ -26,9 +26,15 @@ RngStopCalibrationOptions::RngStopCalibrationOptions() "Continue Screen Frames Calibration:
As in Starter RNG's RNG Calibration, kept as the seed's is.", LockMode::LOCK_WHILE_RUNNING, 0.0 ) + , STARTER_INGAME( + "Starter RNG's In-Game Advances Calibration:
As in Starter RNG's RNG Calibration, " + "for Squirtle only: each RNG stop keeps its own.", + LockMode::LOCK_WHILE_RUNNING, 0.0 + ) { PA_ADD_OPTION(SEED); PA_ADD_OPTION(CSF); + PA_ADD_OPTION(STARTER_INGAME); } RngCalibrations RngStopCalibrationOptions::calibration(const FloatingPointOption& ingame) const{ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h index b888a24fc3..dc0a8e1343 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngOptions.h @@ -49,6 +49,8 @@ class RngStopCalibrationOptions : public GroupOption{ public: SimpleIntegerOption SEED; FloatingPointOption CSF; + // Starter RNG's in-game advances offset. + FloatingPointOption STARTER_INGAME; }; diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp index cabc1322d9..4d62c83de4 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp @@ -35,7 +35,9 @@ ConsoleStarterRngSteps::ConsoleStarterRngSteps( , m_notifications(notifications) // TODO: LeafGreen, once AutoStory plays it. , m_seeds(seeds_json_path(true, settings.language)) -{} +{ + m_calibration_display.set_calibrations(settings.calibration); +} WallClock ConsoleStarterRngSteps::now(){ return current_time(); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h index 4b3f3b132e..315a6605dc 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h @@ -45,11 +45,13 @@ class RngPlanLogger : public Logger{ struct StarterRngConsoleSettings{ Language language = Language::English; SoundSetting sound = SoundSetting::Mono; + // The calibration the first try starts from. + RngCalibrations calibration = {}; }; // The loop's steps on the console, with Starter RNG's displays, stats and -// calibration kept here (AutoStory doesn't show them). Each try starts -// from the calibration the last one ended with. Squirtle, FireRed, the +// calibration kept here (AutoStory doesn't show them). Each try after the +// first starts from the calibration the last one ended with. Squirtle, FireRed, the // Switch's default profile. class ConsoleStarterRngSteps : public StarterRngLoopSteps{ public: From 7f8661a4f1083b59b858f83b0d2e3dce70ec8d03 Mon Sep 17 00:00:00 2001 From: dayfine Date: Mon, 2 Nov 2026 21:09:04 -0800 Subject: [PATCH 09/10] FRLG AutoStory: one short line per Starter RNG reset on the overlay log Each reset now puts one line on the log and the stream's overlay log, as "Starter RNG try 27/50: seed e66e (+1 frame late), advance 1677 (target 1670, +7). Missed." (rng_reset_line()). The long "RngPlan: state" lines stay in the log only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonFRLG_StarterRngConsoleSteps.cpp | 22 ++++- .../PokemonFRLG_StarterRngConsoleSteps.h | 19 ++++- .../PokemonFRLG_StarterRngLoop.cpp | 76 +++++++++++++++++ .../PokemonFRLG_StarterRngLoop.h | 21 +++++ .../PokemonFRLG_StarterRngLoop_Tests.cpp | 84 +++++++++++++++++++ 5 files changed, 217 insertions(+), 5 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp index 4d62c83de4..40d580b6a8 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp @@ -19,12 +19,31 @@ RngPlanLogger::RngPlanLogger(ConsoleHandle& console) void RngPlanLogger::log(const std::string& msg, Color color){ m_console.log(msg, color); - if (msg.starts_with("RngPlan: state") || msg.starts_with("RngPlan: result")){ + if (msg.starts_with("RngPlan: result")){ m_console.overlay().add_log(msg); } } +std::function reset_line_logger( + ConsoleHandle& console, std::string_view program, const RngAttempt& attempt, const SeedMatch& seed_match, uint64_t max_resets +){ + RngResetLine line{ + .program = program, .max_resets = max_resets, + .target_seed = attempt.target.seed.seed, .target_advances = attempt.target.advances, + .seed_values = seed_match.seed_values, .seed_position = seed_match.seed_position, + .read = {}, + }; + return [&console, line](const RngResetRead& read){ + RngResetLine reset = line; + reset.read = read; + const std::string text = rng_reset_line(reset); + console.log(text); + console.overlay().add_log(text); + }; +} + + ConsoleStarterRngSteps::ConsoleStarterRngSteps( SingleSwitchProgramEnvironment& env, ProControllerContext& context, const StarterRngConsoleSettings& settings, const StarterRngNotifications& notifications @@ -69,6 +88,7 @@ StarterRngResult ConsoleStarterRngSteps::run_attempt(const RngAttempt& attempt, return current_time() >= deadline ? uint64_t(0) : max_resets; }, .on_reset = call.on_reset, + .on_read = reset_line_logger(m_env.console, "Starter RNG", attempt, seed_match, call.max_resets), }, StarterRngDisplays{ .target = m_target_display, diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h index 315a6605dc..11a7a2adc1 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h @@ -10,7 +10,9 @@ #ifndef PokemonAutomation_PokemonFRLG_StarterRngConsoleSteps_H #define PokemonAutomation_PokemonFRLG_StarterRngConsoleSteps_H +#include #include +#include #include "Common/Cpp/Color.h" #include "Common/Cpp/Logging/AbstractLogger.h" #include "Common/Cpp/Time.h" @@ -30,8 +32,8 @@ namespace NintendoSwitch{ namespace PokemonFRLG{ -// The console's log, with the loop's state and result lines also on the -// stream's overlay log. +// The console's log, with the loop's result lines also on the stream's +// overlay log. Its state lines, too long for it, stay in the log. class RngPlanLogger : public Logger{ public: explicit RngPlanLogger(ConsoleHandle& console); @@ -42,6 +44,14 @@ class RngPlanLogger : public Logger{ }; +// An on_read for `program`'s tries at `attempt`, which puts each reset's +// line (rng_reset_line()) on the console's log and its stream's overlay +// log. `program` is a literal, as "Starter RNG". +std::function reset_line_logger( + ConsoleHandle& console, std::string_view program, const RngAttempt& attempt, const SeedMatch& seed_match, uint64_t max_resets +); + + struct StarterRngConsoleSettings{ Language language = Language::English; SoundSetting sound = SoundSetting::Mono; @@ -51,8 +61,9 @@ struct StarterRngConsoleSettings{ // The loop's steps on the console, with Starter RNG's displays, stats and // calibration kept here (AutoStory doesn't show them). Each try after the -// first starts from the calibration the last one ended with. Squirtle, FireRed, the -// Switch's default profile. +// first starts from the calibration the last one ended with, and each +// reset puts one line (rng_reset_line()) on the log and the stream's +// overlay log. Squirtle, FireRed, the Switch's default profile. class ConsoleStarterRngSteps : public StarterRngLoopSteps{ public: ConsoleStarterRngSteps( diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp index bff10d04b2..a8a1d94f8c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp @@ -5,7 +5,10 @@ */ #include +#include #include +#include +#include #include "Common/Cpp/Exceptions.h" #include "VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_RngPlanLog.h" #include "PokemonFRLG_StarterRngLoop.h" @@ -91,6 +94,79 @@ std::string rng_log_state(const RngLoopState& state){ } +std::optional seed_frame_offset(const std::vector& seed_values, int16_t target_position, uint16_t seed){ + const auto found = std::find(seed_values.begin(), seed_values.end(), seed); + if (target_position < 0 || found == seed_values.end()){ + return std::nullopt; + } + return int(found - seed_values.begin()) - target_position; +} + +namespace{ + +std::string seed_text(const RngResetLine& line, uint16_t seed){ + if (seed == line.target_seed){ + return std::format("seed {:04x} = target", seed); + } + const std::optional frames = seed_frame_offset(line.seed_values, line.seed_position, seed); + if (!frames){ + return std::format("seed {:04x} (not near the target)", seed); + } + return std::format( + "seed {:04x} ({:+} frame{} {})", seed, *frames, std::abs(*frames) == 1 ? "" : "s", *frames > 0 ? "late" : "early" + ); +} + +std::string advance_text(uint64_t target, uint64_t advance){ + if (advance == target){ + return std::format("advance {}", advance); + } + return std::format("advance {} (target {}, {:+})", advance, target, int64_t(advance) - int64_t(target)); +} + +size_t distinct_states(const std::vector& hits){ + std::set> states; + for (const AdvRngState& hit : hits){ + states.emplace(hit.seed, hit.advance); + } + return states.size(); +} + +std::string shiny_text(const RngResetLine& line){ + const std::vector& hits = line.read.hits; + const bool on_target = std::any_of(hits.begin(), hits.end(), [&](const AdvRngState& hit){ + return have_hit_target(line.target_seed, line.target_advances, hit); + }); + if (on_target){ + return seed_text(line, line.target_seed) + ", " + advance_text(line.target_advances, line.target_advances) + ". HIT, shiny!"; + } + return hits.empty() ? "shiny, not known if on the target." : "shiny, not on the target."; +} + +} + +std::string rng_reset_line(const RngResetLine& line){ + const RngResetRead& read = line.read; + const std::string head = std::format("{} try {}/{}: ", line.program, read.resets, line.max_resets); + if (read.shiny){ + return head + shiny_text(line); + } + const size_t states = distinct_states(read.hits); + std::optional hit = read.hit; + if (!hit && states == 1){ + hit = read.hits.front(); + } + if (!hit){ + return head + (states == 0 + ? std::string("no match read (stats fit no seed/advance).") + : std::format("{} possible matches, can't tell which.", states)); + } + const bool on_target = have_hit_target(line.target_seed, line.target_advances, *hit); + return head + seed_text(line, hit->seed) + ", " + advance_text(line.target_advances, hit->advance) + + (on_target ? ". HIT, not shiny." : ". Missed."); +} + + namespace{ std::optional loop_end(RngPlanStep step){ diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h index 1307ebb47d..bae408320b 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h @@ -17,6 +17,7 @@ #include #include #include +#include #include #include "Common/Cpp/Exceptions.h" #include "Common/Cpp/Logging/AbstractLogger.h" @@ -68,6 +69,26 @@ struct RngLoopState{ std::string rng_log_state(const RngLoopState& state); +// A reset's reads, for its one line on the stream's log. +struct RngResetLine{ + // "Starter RNG" or "Gift RNG". + std::string_view program; + uint64_t max_resets = 0; + uint16_t target_seed = 0; + uint64_t target_advances = 0; + // The seeds near the target, in the order of their delays, and the + // target's place among them (SeedMatch). + std::vector seed_values; + int16_t seed_position = -1; + RngResetRead read; +}; +// The frames from the target seed to `seed` among `seed_values`: +1 for +// the seed a frame later. None when either isn't among them. +std::optional seed_frame_offset(const std::vector& seed_values, int16_t target_position, uint16_t seed); +// As "Gift RNG try 28/50: seed 9cf3 = target, advance 1669 (target 1670, -1). Missed." +std::string rng_reset_line(const RngResetLine& line); + + struct StarterRngLoopLimits{ // An attempt makes no more resets after this long, and counts as missed. Milliseconds attempt_time = Milliseconds(0); diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp index 547b6b3dcc..4b24859aa0 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp @@ -413,6 +413,87 @@ UnitTestResult test_state_line(){ return true; } + + +AdvRngState state(uint16_t seed, uint64_t advance){ + AdvRngState hit{}; + hit.seed = seed; + hit.advance = advance; + return hit; +} + +// Target: seed 9cf3 at advance 1670, between 7425 a frame earlier and +// e66e a frame later. +struct ResetLineRow{ + std::string name; + std::string program; + RngResetRead read; + std::string expected; +}; + +const std::vector RESET_LINE_ROWS = { + { + .name = "seed on the target", .program = "Gift RNG", + .read = {.resets = 28, .hits = {state(0x9cf3, 1669)}, .hit = state(0x9cf3, 1669), .shiny = false}, + .expected = "Gift RNG try 28/50: seed 9cf3 = target, advance 1669 (target 1670, -1). Missed.", + }, + { + .name = "seed a frame late", .program = "Starter RNG", + .read = {.resets = 27, .hits = {state(0xe66e, 1677), state(0x7425, 1690)}, .hit = state(0xe66e, 1677), .shiny = false}, + .expected = "Starter RNG try 27/50: seed e66e (+1 frame late), advance 1677 (target 1670, +7). Missed.", + }, + { + .name = "seed a frame early", .program = "Gift RNG", + .read = {.resets = 4, .hits = {state(0x7425, 1670)}, .hit = std::nullopt, .shiny = false}, + .expected = "Gift RNG try 4/50: seed 7425 (-1 frame early), advance 1670. Missed.", + }, + { + .name = "seed not near the target", .program = "Gift RNG", + .read = {.resets = 5, .hits = {state(0x1234, 1670)}, .hit = state(0x1234, 1670), .shiny = false}, + .expected = "Gift RNG try 5/50: seed 1234 (not near the target), advance 1670. Missed.", + }, + { + .name = "no match", .program = "Gift RNG", + .read = {.resets = 19, .hits = {}, .hit = std::nullopt, .shiny = false}, + .expected = "Gift RNG try 19/50: no match read (stats fit no seed/advance).", + }, + { + .name = "several matches", .program = "Gift RNG", + .read = { + .resets = 3, .hits = {state(0x9cf3, 1668), state(0x9cf3, 1668), state(0xe66e, 1671), state(0x7425, 1675)}, + .hit = std::nullopt, .shiny = false, + }, + .expected = "Gift RNG try 3/50: 3 possible matches, can't tell which.", + }, + { + .name = "target hit", .program = "Starter RNG", + .read = {.resets = 12, .hits = {state(0x9cf3, 1670)}, .hit = state(0x9cf3, 1670), .shiny = false}, + .expected = "Starter RNG try 12/50: seed 9cf3 = target, advance 1670. HIT, not shiny.", + }, + { + .name = "shiny on the target", .program = "Gift RNG", + .read = {.resets = 31, .hits = {state(0xe66e, 1671), state(0x9cf3, 1670)}, .hit = std::nullopt, .shiny = true}, + .expected = "Gift RNG try 31/50: seed 9cf3 = target, advance 1670. HIT, shiny!", + }, + { + .name = "shiny off the target", .program = "Gift RNG", + .read = {.resets = 9, .hits = {state(0xe66e, 1671)}, .hit = std::nullopt, .shiny = true}, + .expected = "Gift RNG try 9/50: shiny, not on the target.", + }, +}; + +UnitTestResult test_reset_line(const ResetLineRow& row){ + const std::string got = rng_reset_line(RngResetLine{ + .program = row.program, .max_resets = 50, .target_seed = 0x9cf3, .target_advances = 1670, + .seed_values = {0x1111, 0x7425, 0x9cf3, 0xe66e, 0x2222}, .seed_position = 2, + .read = row.read, + }); + if (got != row.expected){ + return "Expected \"" + row.expected + "\", got \"" + got + "\"."; + } + return true; +} + } @@ -423,6 +504,9 @@ void add_tests_StarterRngLoop(UnitTestDatabase& database){ database.add("attempt deadlines", test_deadlines); database.add("a setup error stops the loop", test_setup_error_stops); database.add("state line", test_state_line); + for (const ResetLineRow& row : RESET_LINE_ROWS){ + database.add("reset line " + row.name, [row]{ return test_reset_line(row); }); + } } From 07819f4d08b0e27e0e662b4c5eac9d11cb8e6169 Mon Sep 17 00:00:00 2001 From: dayfine Date: Tue, 3 Nov 2026 09:23:04 -0800 Subject: [PATCH 10/10] FRLG AutoStory: program() within code health's 50 lines Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AKYzhrMnPK61XHWEch4a6E --- .../PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp index 6d312f566a..a57983b637 100644 --- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp @@ -575,14 +575,12 @@ void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContex first = checkpoint_index(checkpoints, "00.01b"); plan = plan_story_run(checkpoints, first, last, handoffs); } - StoryEnv story{env.console, context, checkpoints[first].supplies, checkpoints[first].supplies, false, RUN.checks()}; story.player_name = player_name; prepare_start(env, context, checkpoints, first, story); StoryExecutor executor(story); executor.set_checks(RUN.checks()); executor.set_language(RUN.language()); - StarterRngPlanned planned; std::function before; if (plan.stop == StoryHandoff::STARTER_RNG){