diff --git a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp
index e1f2ddcfcf..4ccaa6a0d7 100644
--- a/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp
+++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/PokemonFRLG_Tests.cpp
@@ -41,6 +41,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_AutoStoryTable.h"
#include "Programs/RngManipulation/PokemonFRLG_RngPlanInputs_Tests.h"
#include "Programs/RngManipulation/PokemonFRLG_RngPlanLog_Tests.h"
@@ -48,6 +49,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"
@@ -715,6 +717,7 @@ void add_tests(UnitTestDatabase& database){
add_tests_AutoStory(database);
add_tests_AutoStorySimulation(database);
add_tests_AutoStoryItems(database);
+ add_tests_AutoStoryRngLoop(database);
add_tests_NamingCursor(database);
add_tests_NamingPlan(database);
add_tests_NamingKeys(database);
@@ -725,6 +728,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 93171350f8..a57983b637 100644
--- a/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp
+++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStory.cpp
@@ -17,9 +17,15 @@
#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_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"
#include "PokemonFRLG_AutoStory.h"
@@ -57,6 +63,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(
@@ -89,16 +102,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);
}
@@ -295,8 +309,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
@@ -335,15 +347,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.");
}
@@ -362,8 +374,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,
@@ -379,59 +390,236 @@ 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: 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,
+};
+
+}
+
+// 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. 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, 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_LIMITS.max_retries
+ );
+ // 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)
+ );
+ 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);
+ 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;
+}
+
+// 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.
+ 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){
if (const std::optional verify = RUN.VERIFY.policy()){
verify_story_checkpoint(env, context, RUN, *verify, NOTIFICATION_PROGRAM_FINISH);
return;
}
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();
+ 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);
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;
+ }
+ send_story_finished(env, NOTIFICATION_PROGRAM_FINISH, done_through, sid_before, RNG_PLAN.SID);
+}
+
+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;
}
- env.console.log("AutoStory: done through " + plan.rows.back().id + ".");
- send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH);
+ 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..f6c1f5d3c9
--- /dev/null
+++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.cpp
@@ -0,0 +1,119 @@
+/* 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{
+
+
+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 starter_rng_loop_message(const StarterRngLoopResult& result){
+ const std::string sids = join_sids(result.remaining_sids);
+ switch (result.end){
+ case StarterRngLoopEnd::SHINY:
+ if (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.";
+ }
+ 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.";
+ 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::MISSED_EVERY_ATTEMPT_LEFT:
+ 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.",
+ result.attempts_run
+ );
+ }
+ throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Starter RNG loop end.");
+}
+
+
+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
+){
+ 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;
+}
+
+
+
+}
+}
+}
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..a6c0f248af
--- /dev/null
+++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop.h
@@ -0,0 +1,73 @@
+/* AutoStory RNG Loop
+ *
+ * From: https://github.com/PokemonAutomation/
+ *
+ * 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.
+ *
+ */
+
+#ifndef PokemonAutomation_PokemonFRLG_AutoStoryRngLoop_H
+#define PokemonAutomation_PokemonFRLG_AutoStoryRngLoop_H
+
+#include
+#include
+#include
+#include "Common/Cpp/TestRunners/UnitTestDatabase.h"
+#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{
+namespace PokemonFRLG{
+
+
+// The Starter RNG plan, for the TID it was made for.
+struct StarterRngPlanned{
+ uint16_t tid = 0;
+ std::vector attempts;
+};
+
+// What the run says when the loop ends with `result`.
+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
+// 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
+);
+
+
+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..f042a5349c
--- /dev/null
+++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryRngLoop_Tests.cpp
@@ -0,0 +1,207 @@
+/* AutoStory RNG Loop Tests
+ *
+ * From: https://github.com/PokemonAutomation/
+ *
+ * What the run says after a shiny, and the rows it takes then.
+ *
+ */
+
+#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;
+};
+
+
+
+// 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: 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},
+ .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;
+}
+
+
+// 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;
+}
+
+
+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 676ec0d9f9..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{
@@ -60,7 +66,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(
@@ -145,10 +152,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){
@@ -161,7 +177,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 3e08f2b94f..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;
};
@@ -66,6 +68,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/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp
new file mode 100644
index 0000000000..40d580b6a8
--- /dev/null
+++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.cpp
@@ -0,0 +1,117 @@
+/* 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: 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
+)
+ : 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))
+{
+ m_calibration_display.set_calibrations(settings.calibration);
+}
+
+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,
+ .on_read = reset_line_logger(m_env.console, "Starter RNG", attempt, seed_match, call.max_resets),
+ },
+ 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..11a7a2adc1
--- /dev/null
+++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngConsoleSteps.h
@@ -0,0 +1,93 @@
+/* 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
+#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 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);
+ virtual void log(const std::string& msg, Color color = Color()) override;
+
+private:
+ ConsoleHandle& m_console;
+};
+
+
+// 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;
+ // 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 after the
+// 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(
+ 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..a8a1d94f8c
--- /dev/null
+++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.cpp
@@ -0,0 +1,337 @@
+/* Starter RNG Loop
+ *
+ * From: https://github.com/PokemonAutomation/
+ *
+ */
+
+#include
+#include
+#include
+#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)
+ );
+}
+
+
+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){
+ 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..bae408320b
--- /dev/null
+++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop.h
@@ -0,0 +1,182 @@
+/* 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
+#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);
+
+
+// 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);
+ // 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..4b24859aa0
--- /dev/null
+++ b/SerialPrograms/Source/VideoGames/PokemonFRLG/Programs/RngManipulation/PokemonFRLG_StarterRngLoop_Tests.cpp
@@ -0,0 +1,516 @@
+/* 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;
+}
+
+
+
+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;
+}
+
+}
+
+
+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);
+ for (const ResetLineRow& row : RESET_LINE_ROWS){
+ database.add("reset line " + row.name, [row]{ return test_reset_line(row); });
+ }
+}
+
+
+
+}
+}
+}
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 2632021427..e1dee1738e 100644
--- a/SerialPrograms/cmake/SourceFiles.cmake
+++ b/SerialPrograms/cmake/SourceFiles.cmake
@@ -1859,15 +1859,18 @@ file(GLOB LIBRARY_SOURCES
Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.cpp
Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty.h
Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryParty_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_AutoStorySimulation_Tests.cpp
Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.cpp
Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStorySummary.h
Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.cpp
Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryTable.h
Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.cpp
Source/VideoGames/PokemonFRLG/Programs/AutoStory/PokemonFRLG_AutoStoryWinChance.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
@@ -1953,6 +1956,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